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 |
---|---|---|---|---|
window-properties.rs
|
extern crate sdl2;
use sdl2::pixels::Color;
pub fn main() {
let mut sdl_context = sdl2::init().video().unwrap();
let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600)
.resizable()
.build()
.unwrap();
let mut renderer = window.renderer().present_vsync().build().unwrap();
let mut running = true;
let mut tick = 0;
while running {
for event in sdl_context.event_pump().poll_iter() {
use sdl2::event::Event;
use sdl2::keycode::KeyCode;
match event {
Event::Quit {..} | Event::KeyDown { keycode: KeyCode::Escape,.. } => {
running = false
},
_ =>
|
}
}
{
// Update the window title.
// &sdl_context is needed to safely access the Window and to ensure that the event loop
// isn't running (which could mutate the Window).
// Note: if you don't use renderer: window.properties(&sdl_context);
let mut props = renderer.window_properties(&sdl_context).unwrap();
let position = props.get_position();
let size = props.get_size();
let title = format!("Window - pos({}x{}), size({}x{}): {}", position.0, position.1, size.0, size.1, tick);
props.set_title(&title);
tick += 1;
}
let mut drawer = renderer.drawer();
drawer.set_draw_color(Color::RGB(0, 0, 0));
drawer.clear();
drawer.present();
}
}
|
{}
|
conditional_block
|
window-properties.rs
|
extern crate sdl2;
use sdl2::pixels::Color;
pub fn
|
() {
let mut sdl_context = sdl2::init().video().unwrap();
let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600)
.resizable()
.build()
.unwrap();
let mut renderer = window.renderer().present_vsync().build().unwrap();
let mut running = true;
let mut tick = 0;
while running {
for event in sdl_context.event_pump().poll_iter() {
use sdl2::event::Event;
use sdl2::keycode::KeyCode;
match event {
Event::Quit {..} | Event::KeyDown { keycode: KeyCode::Escape,.. } => {
running = false
},
_ => {}
}
}
{
// Update the window title.
// &sdl_context is needed to safely access the Window and to ensure that the event loop
// isn't running (which could mutate the Window).
// Note: if you don't use renderer: window.properties(&sdl_context);
let mut props = renderer.window_properties(&sdl_context).unwrap();
let position = props.get_position();
let size = props.get_size();
let title = format!("Window - pos({}x{}), size({}x{}): {}", position.0, position.1, size.0, size.1, tick);
props.set_title(&title);
tick += 1;
}
let mut drawer = renderer.drawer();
drawer.set_draw_color(Color::RGB(0, 0, 0));
drawer.clear();
drawer.present();
}
}
|
main
|
identifier_name
|
window-properties.rs
|
extern crate sdl2;
use sdl2::pixels::Color;
pub fn main() {
let mut sdl_context = sdl2::init().video().unwrap();
let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600)
.resizable()
.build()
.unwrap();
let mut renderer = window.renderer().present_vsync().build().unwrap();
let mut running = true;
let mut tick = 0;
while running {
for event in sdl_context.event_pump().poll_iter() {
|
Event::Quit {..} | Event::KeyDown { keycode: KeyCode::Escape,.. } => {
running = false
},
_ => {}
}
}
{
// Update the window title.
// &sdl_context is needed to safely access the Window and to ensure that the event loop
// isn't running (which could mutate the Window).
// Note: if you don't use renderer: window.properties(&sdl_context);
let mut props = renderer.window_properties(&sdl_context).unwrap();
let position = props.get_position();
let size = props.get_size();
let title = format!("Window - pos({}x{}), size({}x{}): {}", position.0, position.1, size.0, size.1, tick);
props.set_title(&title);
tick += 1;
}
let mut drawer = renderer.drawer();
drawer.set_draw_color(Color::RGB(0, 0, 0));
drawer.clear();
drawer.present();
}
}
|
use sdl2::event::Event;
use sdl2::keycode::KeyCode;
match event {
|
random_line_split
|
toggle_tool_button.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Actionable;
use Bin;
use Buildable;
use Container;
use ToolButton;
use ToolItem;
use Widget;
use ffi;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib_wrapper! {
pub struct ToggleToolButton(Object<ffi::GtkToggleToolButton, ffi::GtkToggleToolButtonClass, ToggleToolButtonClass>) @extends ToolButton, ToolItem, Bin, Container, Widget, @implements Buildable, Actionable;
match fn {
get_type => || ffi::gtk_toggle_tool_button_get_type(),
}
}
impl ToggleToolButton {
pub fn new() -> ToggleToolButton {
assert_initialized_main_thread!();
unsafe {
ToolItem::from_glib_none(ffi::gtk_toggle_tool_button_new()).unsafe_cast()
}
}
}
impl Default for ToggleToolButton {
fn default() -> Self {
Self::new()
}
}
pub const NONE_TOGGLE_TOOL_BUTTON: Option<&ToggleToolButton> = None;
pub trait ToggleToolButtonExt:'static {
fn get_active(&self) -> bool;
fn set_active(&self, is_active: bool);
fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<ToggleToolButton>> ToggleToolButtonExt for O {
fn get_active(&self) -> bool {
unsafe {
from_glib(ffi::gtk_toggle_tool_button_get_active(self.as_ref().to_glib_none().0))
}
}
fn set_active(&self, is_active: bool) {
unsafe {
ffi::gtk_toggle_tool_button_set_active(self.as_ref().to_glib_none().0, is_active.to_glib());
}
}
fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"toggled\0".as_ptr() as *const _,
Some(transmute(toggled_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _,
Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
unsafe extern "C" fn toggled_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkToggleToolButton, f: glib_ffi::gpointer)
where P: IsA<ToggleToolButton> {
let f: &F = transmute(f);
f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast())
}
unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkToggleToolButton, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<ToggleToolButton> {
let f: &F = transmute(f);
f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast())
}
impl fmt::Display for ToggleToolButton {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ToggleToolButton")
}
}
|
fmt
|
identifier_name
|
toggle_tool_button.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Actionable;
use Bin;
use Buildable;
use Container;
use ToolButton;
use ToolItem;
use Widget;
use ffi;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib_wrapper! {
pub struct ToggleToolButton(Object<ffi::GtkToggleToolButton, ffi::GtkToggleToolButtonClass, ToggleToolButtonClass>) @extends ToolButton, ToolItem, Bin, Container, Widget, @implements Buildable, Actionable;
match fn {
get_type => || ffi::gtk_toggle_tool_button_get_type(),
}
}
impl ToggleToolButton {
pub fn new() -> ToggleToolButton {
assert_initialized_main_thread!();
unsafe {
ToolItem::from_glib_none(ffi::gtk_toggle_tool_button_new()).unsafe_cast()
}
}
}
impl Default for ToggleToolButton {
fn default() -> Self {
Self::new()
}
}
pub const NONE_TOGGLE_TOOL_BUTTON: Option<&ToggleToolButton> = None;
pub trait ToggleToolButtonExt:'static {
fn get_active(&self) -> bool;
fn set_active(&self, is_active: bool);
fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<ToggleToolButton>> ToggleToolButtonExt for O {
fn get_active(&self) -> bool {
unsafe {
from_glib(ffi::gtk_toggle_tool_button_get_active(self.as_ref().to_glib_none().0))
}
}
fn set_active(&self, is_active: bool) {
unsafe {
ffi::gtk_toggle_tool_button_set_active(self.as_ref().to_glib_none().0, is_active.to_glib());
}
}
fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"toggled\0".as_ptr() as *const _,
Some(transmute(toggled_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _,
Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
unsafe extern "C" fn toggled_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkToggleToolButton, f: glib_ffi::gpointer)
where P: IsA<ToggleToolButton> {
let f: &F = transmute(f);
f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast())
}
unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkToggleToolButton, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<ToggleToolButton>
|
impl fmt::Display for ToggleToolButton {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ToggleToolButton")
}
}
|
{
let f: &F = transmute(f);
f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast())
}
|
identifier_body
|
toggle_tool_button.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
|
use Buildable;
use Container;
use ToolButton;
use ToolItem;
use Widget;
use ffi;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib_wrapper! {
pub struct ToggleToolButton(Object<ffi::GtkToggleToolButton, ffi::GtkToggleToolButtonClass, ToggleToolButtonClass>) @extends ToolButton, ToolItem, Bin, Container, Widget, @implements Buildable, Actionable;
match fn {
get_type => || ffi::gtk_toggle_tool_button_get_type(),
}
}
impl ToggleToolButton {
pub fn new() -> ToggleToolButton {
assert_initialized_main_thread!();
unsafe {
ToolItem::from_glib_none(ffi::gtk_toggle_tool_button_new()).unsafe_cast()
}
}
}
impl Default for ToggleToolButton {
fn default() -> Self {
Self::new()
}
}
pub const NONE_TOGGLE_TOOL_BUTTON: Option<&ToggleToolButton> = None;
pub trait ToggleToolButtonExt:'static {
fn get_active(&self) -> bool;
fn set_active(&self, is_active: bool);
fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<ToggleToolButton>> ToggleToolButtonExt for O {
fn get_active(&self) -> bool {
unsafe {
from_glib(ffi::gtk_toggle_tool_button_get_active(self.as_ref().to_glib_none().0))
}
}
fn set_active(&self, is_active: bool) {
unsafe {
ffi::gtk_toggle_tool_button_set_active(self.as_ref().to_glib_none().0, is_active.to_glib());
}
}
fn connect_toggled<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"toggled\0".as_ptr() as *const _,
Some(transmute(toggled_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
fn connect_property_active_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _,
Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
unsafe extern "C" fn toggled_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkToggleToolButton, f: glib_ffi::gpointer)
where P: IsA<ToggleToolButton> {
let f: &F = transmute(f);
f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast())
}
unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) +'static>(this: *mut ffi::GtkToggleToolButton, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<ToggleToolButton> {
let f: &F = transmute(f);
f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast())
}
impl fmt::Display for ToggleToolButton {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ToggleToolButton")
}
}
|
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Actionable;
use Bin;
|
random_line_split
|
move-fragments-1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(tuple_indexing)]
// Test that we correctly compute the move fragments for a fn.
//
// Note that the code below is not actually incorrect; the
// `rustc_move_fragments` attribute is a hack that uses the error
// reporting mechanisms as a channel for communicating from the
// internals of the compiler.
// These are all fairly trivial cases: unused variables or direct
// drops of substructure.
pub struct D { d: int }
impl Drop for D { fn drop(&mut self) { } }
#[rustc_move_fragments]
pub fn test_noop() {
}
#[rustc_move_fragments]
|
#[rustc_move_fragments]
pub fn test_take_struct(_p: Pair<D, D>) {
//~^ ERROR assigned_leaf_path: `$(local _p)`
}
#[rustc_move_fragments]
pub fn test_drop_struct_part(p: Pair<D, D>) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR moved_leaf_path: `$(local p).x`
//~| ERROR unmoved_fragment: `$(local p).y`
drop(p.x);
}
#[rustc_move_fragments]
pub fn test_drop_tuple_part(p: (D, D)) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR moved_leaf_path: `$(local p).#0`
//~| ERROR unmoved_fragment: `$(local p).#1`
drop(p.0);
}
pub fn main() { }
|
pub fn test_take(_x: D) {
//~^ ERROR assigned_leaf_path: `$(local _x)`
}
pub struct Pair<X,Y> { x: X, y: Y }
|
random_line_split
|
move-fragments-1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(tuple_indexing)]
// Test that we correctly compute the move fragments for a fn.
//
// Note that the code below is not actually incorrect; the
// `rustc_move_fragments` attribute is a hack that uses the error
// reporting mechanisms as a channel for communicating from the
// internals of the compiler.
// These are all fairly trivial cases: unused variables or direct
// drops of substructure.
pub struct D { d: int }
impl Drop for D { fn drop(&mut self) { } }
#[rustc_move_fragments]
pub fn test_noop() {
}
#[rustc_move_fragments]
pub fn test_take(_x: D) {
//~^ ERROR assigned_leaf_path: `$(local _x)`
}
pub struct Pair<X,Y> { x: X, y: Y }
#[rustc_move_fragments]
pub fn test_take_struct(_p: Pair<D, D>) {
//~^ ERROR assigned_leaf_path: `$(local _p)`
}
#[rustc_move_fragments]
pub fn test_drop_struct_part(p: Pair<D, D>) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR moved_leaf_path: `$(local p).x`
//~| ERROR unmoved_fragment: `$(local p).y`
drop(p.x);
}
#[rustc_move_fragments]
pub fn test_drop_tuple_part(p: (D, D)) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR moved_leaf_path: `$(local p).#0`
//~| ERROR unmoved_fragment: `$(local p).#1`
drop(p.0);
}
pub fn
|
() { }
|
main
|
identifier_name
|
move-fragments-1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(tuple_indexing)]
// Test that we correctly compute the move fragments for a fn.
//
// Note that the code below is not actually incorrect; the
// `rustc_move_fragments` attribute is a hack that uses the error
// reporting mechanisms as a channel for communicating from the
// internals of the compiler.
// These are all fairly trivial cases: unused variables or direct
// drops of substructure.
pub struct D { d: int }
impl Drop for D { fn drop(&mut self) { } }
#[rustc_move_fragments]
pub fn test_noop()
|
#[rustc_move_fragments]
pub fn test_take(_x: D) {
//~^ ERROR assigned_leaf_path: `$(local _x)`
}
pub struct Pair<X,Y> { x: X, y: Y }
#[rustc_move_fragments]
pub fn test_take_struct(_p: Pair<D, D>) {
//~^ ERROR assigned_leaf_path: `$(local _p)`
}
#[rustc_move_fragments]
pub fn test_drop_struct_part(p: Pair<D, D>) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR moved_leaf_path: `$(local p).x`
//~| ERROR unmoved_fragment: `$(local p).y`
drop(p.x);
}
#[rustc_move_fragments]
pub fn test_drop_tuple_part(p: (D, D)) {
//~^ ERROR parent_of_fragments: `$(local p)`
//~| ERROR moved_leaf_path: `$(local p).#0`
//~| ERROR unmoved_fragment: `$(local p).#1`
drop(p.0);
}
pub fn main() { }
|
{
}
|
identifier_body
|
base64.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Base64 binary-to-text encoding
use std::str;
use std::fmt;
/// Available encoding character sets
pub enum CharacterSet {
/// The standard character set (uses `+` and `/`)
Standard,
/// The URL safe character set (uses `-` and `_`)
UrlSafe
}
/// Contains configuration parameters for `to_base64`.
pub struct Config {
/// Character set to use
pub char_set: CharacterSet,
/// True to pad output with `=` characters
pub pad: bool,
/// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping
pub line_length: Option<uint>
}
/// Configuration for RFC 4648 standard base64 encoding
pub static STANDARD: Config =
Config {char_set: Standard, pad: true, line_length: None};
/// Configuration for RFC 4648 base64url encoding
pub static URL_SAFE: Config =
Config {char_set: UrlSafe, pad: false, line_length: None};
/// Configuration for RFC 2045 MIME base64 encoding
pub static MIME: Config =
Config {char_set: Standard, pad: true, line_length: Some(76)};
static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789+/");
static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789-_");
/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
/// Converts the value of `self` to a base64 value following the specified
/// format configuration, returning the owned string.
fn to_base64(&self, config: Config) -> String;
}
impl<'a> ToBase64 for &'a [u8] {
/**
* Turn a vector of `u8` bytes into a base64 string.
*
* # Example
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, STANDARD};
*
* fn main () {
* let str = [52,32].to_base64(STANDARD);
* println!("base 64 output: {}", str);
* }
* ```
*/
fn to_base64(&self, config: Config) -> String {
let bytes = match config.char_set {
Standard => STANDARD_CHARS,
UrlSafe => URLSAFE_CHARS
};
let mut v = Vec::new();
let mut i = 0;
let mut cur_length = 0;
let len = self.len();
while i < len - (len % 3) {
match config.line_length {
Some(line_length) =>
if cur_length >= line_length {
v.push('\r' as u8);
v.push('\n' as u8);
cur_length = 0;
},
None => ()
}
let n = (self[i] as u32) << 16 |
(self[i + 1] as u32) << 8 |
(self[i + 2] as u32);
// This 24-bit number gets separated into four 6-bit numbers.
v.push(bytes[((n >> 18) & 63) as uint]);
v.push(bytes[((n >> 12) & 63) as uint]);
v.push(bytes[((n >> 6 ) & 63) as uint]);
v.push(bytes[(n & 63) as uint]);
cur_length += 4;
i += 3;
}
if len % 3!= 0 {
match config.line_length {
Some(line_length) =>
if cur_length >= line_length {
v.push('\r' as u8);
v.push('\n' as u8);
},
None => ()
}
}
// Heh, would be cool if we knew this was exhaustive
// (the dream of bounded integer types)
match len % 3 {
0 => (),
1 => {
let n = (self[i] as u32) << 16;
v.push(bytes[((n >> 18) & 63) as uint]);
v.push(bytes[((n >> 12) & 63) as uint]);
if config.pad {
v.push('=' as u8);
v.push('=' as u8);
}
}
2 => {
let n = (self[i] as u32) << 16 |
(self[i + 1u] as u32) << 8;
v.push(bytes[((n >> 18) & 63) as uint]);
v.push(bytes[((n >> 12) & 63) as uint]);
v.push(bytes[((n >> 6 ) & 63) as uint]);
if config.pad {
v.push('=' as u8);
}
}
_ => fail!("Algebra is broken, please alert the math police")
}
unsafe {
str::raw::from_utf8(v.as_slice()).to_string()
}
}
}
/// A trait for converting from base64 encoded values.
pub trait FromBase64 {
/// Converts the value of `self`, interpreted as base64 encoded data, into
/// an owned vector of bytes, returning the vector.
fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>;
}
/// Errors that can occur when decoding a base64 encoded string
pub enum FromBase64Error {
/// The input contained a character not part of the base64 format
InvalidBase64Character(char, uint),
/// The input had an invalid length
InvalidBase64Length,
}
impl fmt::Show for FromBase64Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidBase64Character(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidBase64Length => write!(f, "Invalid length"),
}
}
}
impl<'a> FromBase64 for &'a str {
/**
* Convert any base64 encoded string (literal, `@`, `&`, or `~`)
* to the byte values it encodes.
*
* You can use the `String::from_utf8` function in `std::string` to turn a
* `Vec<u8>` into a string with characters corresponding to those values.
*
* # Example
*
* This converts a string literal to base64 and back.
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, FromBase64, STANDARD};
*
* fn main () {
* let hello_str = bytes!("Hello, World").to_base64(STANDARD);
* println!("base64 output: {}", hello_str);
* let res = hello_str.as_slice().from_base64();
* if res.is_ok() {
* let opt_bytes = String::from_utf8(res.unwrap());
* if opt_bytes.is_ok() {
* println!("decoded from base64: {}", opt_bytes.unwrap());
* }
* }
* }
* ```
*/
fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
let mut r = Vec::new();
let mut buf: u32 = 0;
let mut modulus = 0;
let mut it = self.bytes().enumerate();
for (idx, byte) in it {
let val = byte as u32;
match byte as char {
'A'..'Z' => buf |= val - 0x41,
'a'..'z' => buf |= val - 0x47,
'0'..'9' => buf |= val + 0x04,
'+'|'-' => buf |= 0x3E,
'/'|'_' => buf |= 0x3F,
'\r'|'\n' => continue,
'=' => break,
_ => return Err(InvalidBase64Character(self.char_at(idx), idx)),
}
buf <<= 6;
modulus += 1;
if modulus == 4 {
modulus = 0;
r.push((buf >> 22) as u8);
r.push((buf >> 14) as u8);
r.push((buf >> 6 ) as u8);
}
}
for (idx, byte) in it {
match byte as char {
'='|'\r'|'\n' => continue,
_ => return Err(InvalidBase64Character(self.char_at(idx), idx)),
}
}
match modulus {
2 => {
r.push((buf >> 10) as u8);
}
3 => {
r.push((buf >> 16) as u8);
r.push((buf >> 8 ) as u8);
}
0 => (),
_ => return Err(InvalidBase64Length),
}
Ok(r)
}
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE};
#[test]
fn test_to_base64_basic() {
assert_eq!("".as_bytes().to_base64(STANDARD), "".to_string());
assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_string());
assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_string());
assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_string());
assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_string());
assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_string());
assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_string());
}
#[test]
fn test_to_base64_line_break() {
assert!(![0u8,..1000].to_base64(Config {line_length: None,..STANDARD})
.as_slice()
.contains("\r\n"));
assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
..STANDARD}),
"Zm9v\r\nYmFy".to_string());
}
#[test]
fn test_to_base64_padding() {
assert_eq!("f".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zg".to_string());
assert_eq!("fo".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zm8".to_string());
}
#[test]
fn test_to_base64_url_safe() {
assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_string());
assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_string());
}
#[test]
fn test_from_base64_basic() {
assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes());
assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes());
assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes());
assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes());
assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes());
assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes());
assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes());
}
#[test]
fn
|
() {
assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(),
"foobar".as_bytes());
assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(),
"foob".as_bytes());
}
#[test]
fn test_from_base64_urlsafe() {
assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap());
}
#[test]
fn test_from_base64_invalid_char() {
assert!("Zm$=".from_base64().is_err())
assert!("Zg==$".from_base64().is_err());
}
#[test]
fn test_from_base64_invalid_padding() {
assert!("Z===".from_base64().is_err());
}
#[test]
fn test_base64_random() {
use std::rand::{task_rng, random, Rng};
for _ in range(0, 1000) {
let times = task_rng().gen_range(1u, 100);
let v = Vec::from_fn(times, |_| random::<u8>());
assert_eq!(v.as_slice()
.to_base64(STANDARD)
.as_slice()
.from_base64()
.unwrap()
.as_slice(),
v.as_slice());
}
}
#[bench]
pub fn bench_to_base64(b: &mut Bencher) {
let s = "γ€γγγγγγ γγͺγγ«γ² γ―γ«γ¨γΏγ¬γ½ γγγγ©γ \
γ¦γ°γγͺγ―γ€γ γ±γγ³γ¨γ γ’γ΅γγ¦γ‘γγ· γ±γγ’γ»γΉγ³";
b.iter(|| {
s.as_bytes().to_base64(STANDARD);
});
b.bytes = s.len() as u64;
}
#[bench]
pub fn bench_from_base64(b: &mut Bencher) {
let s = "γ€γγγγγγ γγͺγγ«γ² γ―γ«γ¨γΏγ¬γ½ γγγγ©γ \
γ¦γ°γγͺγ―γ€γ γ±γγ³γ¨γ γ’γ΅γγ¦γ‘γγ· γ±γγ’γ»γΉγ³";
let sb = s.as_bytes().to_base64(STANDARD);
b.iter(|| {
sb.as_slice().from_base64().unwrap();
});
b.bytes = sb.len() as u64;
}
}
|
test_from_base64_newlines
|
identifier_name
|
base64.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Base64 binary-to-text encoding
use std::str;
use std::fmt;
/// Available encoding character sets
pub enum CharacterSet {
/// The standard character set (uses `+` and `/`)
Standard,
/// The URL safe character set (uses `-` and `_`)
UrlSafe
}
/// Contains configuration parameters for `to_base64`.
pub struct Config {
/// Character set to use
pub char_set: CharacterSet,
/// True to pad output with `=` characters
pub pad: bool,
/// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping
pub line_length: Option<uint>
}
/// Configuration for RFC 4648 standard base64 encoding
pub static STANDARD: Config =
Config {char_set: Standard, pad: true, line_length: None};
/// Configuration for RFC 4648 base64url encoding
pub static URL_SAFE: Config =
Config {char_set: UrlSafe, pad: false, line_length: None};
/// Configuration for RFC 2045 MIME base64 encoding
pub static MIME: Config =
Config {char_set: Standard, pad: true, line_length: Some(76)};
static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789+/");
static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz",
"0123456789-_");
/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
/// Converts the value of `self` to a base64 value following the specified
/// format configuration, returning the owned string.
fn to_base64(&self, config: Config) -> String;
}
impl<'a> ToBase64 for &'a [u8] {
/**
* Turn a vector of `u8` bytes into a base64 string.
*
* # Example
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, STANDARD};
*
* fn main () {
* let str = [52,32].to_base64(STANDARD);
* println!("base 64 output: {}", str);
* }
* ```
*/
fn to_base64(&self, config: Config) -> String {
let bytes = match config.char_set {
Standard => STANDARD_CHARS,
UrlSafe => URLSAFE_CHARS
};
let mut v = Vec::new();
let mut i = 0;
let mut cur_length = 0;
let len = self.len();
while i < len - (len % 3) {
match config.line_length {
Some(line_length) =>
if cur_length >= line_length {
v.push('\r' as u8);
v.push('\n' as u8);
cur_length = 0;
},
None => ()
}
let n = (self[i] as u32) << 16 |
(self[i + 1] as u32) << 8 |
(self[i + 2] as u32);
// This 24-bit number gets separated into four 6-bit numbers.
v.push(bytes[((n >> 18) & 63) as uint]);
v.push(bytes[((n >> 12) & 63) as uint]);
v.push(bytes[((n >> 6 ) & 63) as uint]);
v.push(bytes[(n & 63) as uint]);
cur_length += 4;
i += 3;
}
if len % 3!= 0 {
match config.line_length {
Some(line_length) =>
if cur_length >= line_length {
v.push('\r' as u8);
v.push('\n' as u8);
},
None => ()
}
}
// Heh, would be cool if we knew this was exhaustive
// (the dream of bounded integer types)
match len % 3 {
0 => (),
1 => {
let n = (self[i] as u32) << 16;
v.push(bytes[((n >> 18) & 63) as uint]);
v.push(bytes[((n >> 12) & 63) as uint]);
if config.pad {
v.push('=' as u8);
v.push('=' as u8);
}
|
}
2 => {
let n = (self[i] as u32) << 16 |
(self[i + 1u] as u32) << 8;
v.push(bytes[((n >> 18) & 63) as uint]);
v.push(bytes[((n >> 12) & 63) as uint]);
v.push(bytes[((n >> 6 ) & 63) as uint]);
if config.pad {
v.push('=' as u8);
}
}
_ => fail!("Algebra is broken, please alert the math police")
}
unsafe {
str::raw::from_utf8(v.as_slice()).to_string()
}
}
}
/// A trait for converting from base64 encoded values.
pub trait FromBase64 {
/// Converts the value of `self`, interpreted as base64 encoded data, into
/// an owned vector of bytes, returning the vector.
fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error>;
}
/// Errors that can occur when decoding a base64 encoded string
pub enum FromBase64Error {
/// The input contained a character not part of the base64 format
InvalidBase64Character(char, uint),
/// The input had an invalid length
InvalidBase64Length,
}
impl fmt::Show for FromBase64Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
InvalidBase64Character(ch, idx) =>
write!(f, "Invalid character '{}' at position {}", ch, idx),
InvalidBase64Length => write!(f, "Invalid length"),
}
}
}
impl<'a> FromBase64 for &'a str {
/**
* Convert any base64 encoded string (literal, `@`, `&`, or `~`)
* to the byte values it encodes.
*
* You can use the `String::from_utf8` function in `std::string` to turn a
* `Vec<u8>` into a string with characters corresponding to those values.
*
* # Example
*
* This converts a string literal to base64 and back.
*
* ```rust
* extern crate serialize;
* use serialize::base64::{ToBase64, FromBase64, STANDARD};
*
* fn main () {
* let hello_str = bytes!("Hello, World").to_base64(STANDARD);
* println!("base64 output: {}", hello_str);
* let res = hello_str.as_slice().from_base64();
* if res.is_ok() {
* let opt_bytes = String::from_utf8(res.unwrap());
* if opt_bytes.is_ok() {
* println!("decoded from base64: {}", opt_bytes.unwrap());
* }
* }
* }
* ```
*/
fn from_base64(&self) -> Result<Vec<u8>, FromBase64Error> {
let mut r = Vec::new();
let mut buf: u32 = 0;
let mut modulus = 0;
let mut it = self.bytes().enumerate();
for (idx, byte) in it {
let val = byte as u32;
match byte as char {
'A'..'Z' => buf |= val - 0x41,
'a'..'z' => buf |= val - 0x47,
'0'..'9' => buf |= val + 0x04,
'+'|'-' => buf |= 0x3E,
'/'|'_' => buf |= 0x3F,
'\r'|'\n' => continue,
'=' => break,
_ => return Err(InvalidBase64Character(self.char_at(idx), idx)),
}
buf <<= 6;
modulus += 1;
if modulus == 4 {
modulus = 0;
r.push((buf >> 22) as u8);
r.push((buf >> 14) as u8);
r.push((buf >> 6 ) as u8);
}
}
for (idx, byte) in it {
match byte as char {
'='|'\r'|'\n' => continue,
_ => return Err(InvalidBase64Character(self.char_at(idx), idx)),
}
}
match modulus {
2 => {
r.push((buf >> 10) as u8);
}
3 => {
r.push((buf >> 16) as u8);
r.push((buf >> 8 ) as u8);
}
0 => (),
_ => return Err(InvalidBase64Length),
}
Ok(r)
}
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use base64::{Config, FromBase64, ToBase64, STANDARD, URL_SAFE};
#[test]
fn test_to_base64_basic() {
assert_eq!("".as_bytes().to_base64(STANDARD), "".to_string());
assert_eq!("f".as_bytes().to_base64(STANDARD), "Zg==".to_string());
assert_eq!("fo".as_bytes().to_base64(STANDARD), "Zm8=".to_string());
assert_eq!("foo".as_bytes().to_base64(STANDARD), "Zm9v".to_string());
assert_eq!("foob".as_bytes().to_base64(STANDARD), "Zm9vYg==".to_string());
assert_eq!("fooba".as_bytes().to_base64(STANDARD), "Zm9vYmE=".to_string());
assert_eq!("foobar".as_bytes().to_base64(STANDARD), "Zm9vYmFy".to_string());
}
#[test]
fn test_to_base64_line_break() {
assert!(![0u8,..1000].to_base64(Config {line_length: None,..STANDARD})
.as_slice()
.contains("\r\n"));
assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
..STANDARD}),
"Zm9v\r\nYmFy".to_string());
}
#[test]
fn test_to_base64_padding() {
assert_eq!("f".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zg".to_string());
assert_eq!("fo".as_bytes().to_base64(Config {pad: false,..STANDARD}), "Zm8".to_string());
}
#[test]
fn test_to_base64_url_safe() {
assert_eq!([251, 255].to_base64(URL_SAFE), "-_8".to_string());
assert_eq!([251, 255].to_base64(STANDARD), "+/8=".to_string());
}
#[test]
fn test_from_base64_basic() {
assert_eq!("".from_base64().unwrap().as_slice(), "".as_bytes());
assert_eq!("Zg==".from_base64().unwrap().as_slice(), "f".as_bytes());
assert_eq!("Zm8=".from_base64().unwrap().as_slice(), "fo".as_bytes());
assert_eq!("Zm9v".from_base64().unwrap().as_slice(), "foo".as_bytes());
assert_eq!("Zm9vYg==".from_base64().unwrap().as_slice(), "foob".as_bytes());
assert_eq!("Zm9vYmE=".from_base64().unwrap().as_slice(), "fooba".as_bytes());
assert_eq!("Zm9vYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes());
}
#[test]
fn test_from_base64_newlines() {
assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(),
"foobar".as_bytes());
assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(),
"foob".as_bytes());
}
#[test]
fn test_from_base64_urlsafe() {
assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap());
}
#[test]
fn test_from_base64_invalid_char() {
assert!("Zm$=".from_base64().is_err())
assert!("Zg==$".from_base64().is_err());
}
#[test]
fn test_from_base64_invalid_padding() {
assert!("Z===".from_base64().is_err());
}
#[test]
fn test_base64_random() {
use std::rand::{task_rng, random, Rng};
for _ in range(0, 1000) {
let times = task_rng().gen_range(1u, 100);
let v = Vec::from_fn(times, |_| random::<u8>());
assert_eq!(v.as_slice()
.to_base64(STANDARD)
.as_slice()
.from_base64()
.unwrap()
.as_slice(),
v.as_slice());
}
}
#[bench]
pub fn bench_to_base64(b: &mut Bencher) {
let s = "γ€γγγγγγ γγͺγγ«γ² γ―γ«γ¨γΏγ¬γ½ γγγγ©γ \
γ¦γ°γγͺγ―γ€γ γ±γγ³γ¨γ γ’γ΅γγ¦γ‘γγ· γ±γγ’γ»γΉγ³";
b.iter(|| {
s.as_bytes().to_base64(STANDARD);
});
b.bytes = s.len() as u64;
}
#[bench]
pub fn bench_from_base64(b: &mut Bencher) {
let s = "γ€γγγγγγ γγͺγγ«γ² γ―γ«γ¨γΏγ¬γ½ γγγγ©γ \
γ¦γ°γγͺγ―γ€γ γ±γγ³γ¨γ γ’γ΅γγ¦γ‘γγ· γ±γγ’γ»γΉγ³";
let sb = s.as_bytes().to_base64(STANDARD);
b.iter(|| {
sb.as_slice().from_base64().unwrap();
});
b.bytes = sb.len() as u64;
}
}
|
random_line_split
|
|
stylesheet_loader.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 document_loader::LoadType;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::DomObject;
use dom::element::Element;
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::node::{document_from_node, window_from_node};
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use hyper_serde::Serde;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::{FetchResponseListener, FetchMetadata, Metadata, NetworkError, ReferrerPolicy};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use network_listener::{NetworkListener, PreInvoke};
use parking_lot::RwLock;
use script_layout_interface::message::Msg;
use servo_url::ServoUrl;
use std::mem;
use std::sync::{Arc, Mutex};
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::stylesheets::{ImportRule, Stylesheet, Origin};
use style::stylesheets::StylesheetLoader as StyleStylesheetLoader;
pub trait StylesheetOwner {
/// Returns whether this element was inserted by the parser (i.e., it should
/// trigger a document-load-blocking load).
fn parser_inserted(&self) -> bool;
/// Which referrer policy should loads triggered by this owner follow, or
/// `None` for the default.
fn referrer_policy(&self) -> Option<ReferrerPolicy>;
/// Notes that a new load is pending to finish.
fn increment_pending_loads_count(&self);
/// Returns None if there are still pending loads, or whether any load has
/// failed since the loads started.
fn load_finished(&self, successful: bool) -> Option<bool>;
}
pub enum StylesheetContextSource {
// NB: `media` is just an option so we avoid cloning it.
LinkElement { media: Option<MediaList>, url: ServoUrl },
Import(Arc<RwLock<ImportRule>>),
}
impl StylesheetContextSource {
fn url(&self) -> ServoUrl {
match *self {
StylesheetContextSource::LinkElement { ref url,.. } => url.clone(),
StylesheetContextSource::Import(ref import) =>
|
}
}
}
/// The context required for asynchronously loading an external stylesheet.
pub struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLElement>,
source: StylesheetContextSource,
metadata: Option<Metadata>,
/// The response body received to date.
data: Vec<u8>,
}
impl PreInvoke for StylesheetContext {}
impl FetchResponseListener for StylesheetContext {
fn process_request_body(&mut self) {}
fn process_request_eof(&mut self) {}
fn process_response(&mut self,
metadata: Result<FetchMetadata, NetworkError>) {
self.metadata = metadata.ok().map(|m| {
match m {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { unsafe_,.. } => unsafe_
}
});
}
fn process_response_chunk(&mut self, mut payload: Vec<u8>) {
self.data.append(&mut payload);
}
fn process_response_eof(&mut self, status: Result<(), NetworkError>) {
let elem = self.elem.root();
let document = document_from_node(&*elem);
let mut successful = false;
if status.is_ok() {
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
let is_css = metadata.content_type.map_or(false, |Serde(ContentType(Mime(top, sub, _)))|
top == TopLevel::Text && sub == SubLevel::Css);
let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] };
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let win = window_from_node(&*elem);
let loader = StylesheetLoader::for_element(&elem);
match self.source {
StylesheetContextSource::LinkElement { ref mut media,.. } => {
let sheet =
Arc::new(Stylesheet::from_bytes(&data, final_url,
protocol_encoding_label,
Some(environment_encoding),
Origin::Author,
media.take().unwrap(),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default()));
elem.downcast::<HTMLLinkElement>()
.unwrap()
.set_stylesheet(sheet.clone());
let win = window_from_node(&*elem);
win.layout_chan().send(Msg::AddStylesheet(sheet)).unwrap();
}
StylesheetContextSource::Import(ref import) => {
let import = import.read();
Stylesheet::update_from_bytes(&import.stylesheet,
&data,
protocol_encoding_label,
Some(environment_encoding),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default());
}
}
document.invalidate_stylesheets();
// FIXME: Revisit once consensus is reached at:
// https://github.com/whatwg/html/issues/1142
successful = metadata.status.map_or(false, |(code, _)| code == 200);
}
let owner = elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
if owner.parser_inserted() {
document.decrement_script_blocking_stylesheet_count();
}
let url = self.source.url();
document.finish_load(LoadType::Stylesheet(url));
if let Some(any_failed) = owner.load_finished(successful) {
let event = if any_failed { atom!("error") } else { atom!("load") };
elem.upcast::<EventTarget>().fire_event(event);
}
}
}
pub struct StylesheetLoader<'a> {
elem: &'a HTMLElement,
}
impl<'a> StylesheetLoader<'a> {
pub fn for_element(element: &'a HTMLElement) -> Self {
StylesheetLoader {
elem: element,
}
}
}
impl<'a> StylesheetLoader<'a> {
pub fn load(&self, source: StylesheetContextSource) {
let url = source.url();
let context = Arc::new(Mutex::new(StylesheetContext {
elem: Trusted::new(&*self.elem),
source: source,
metadata: None,
data: vec![],
}));
let document = document_from_node(self.elem);
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
task_source: document.window().networking_task_source(),
wrapper: Some(document.window().get_runnable_wrapper())
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_fetch(message.to().unwrap());
});
let owner = self.elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
let referrer_policy = owner.referrer_policy()
.or_else(|| document.get_referrer_policy());
owner.increment_pending_loads_count();
if owner.parser_inserted() {
document.increment_script_blocking_stylesheet_count();
}
let request = RequestInit {
url: url.clone(),
type_: RequestType::Style,
destination: Destination::Style,
credentials_mode: CredentialsMode::Include,
use_url_credentials: true,
origin: document.url(),
pipeline_id: Some(self.elem.global().pipeline_id()),
referrer_url: Some(document.url()),
referrer_policy: referrer_policy,
.. RequestInit::default()
};
document.fetch_async(LoadType::Stylesheet(url), request, action_sender);
}
}
impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> {
fn request_stylesheet(&self, import: &Arc<RwLock<ImportRule>>) {
self.load(StylesheetContextSource::Import(import.clone()))
}
}
|
{
let import = import.read();
// Look at the parser in style::stylesheets, where we don't
// trigger a load if the url is invalid.
import.url.url()
.expect("Invalid urls shouldn't enter the loader")
.clone()
}
|
conditional_block
|
stylesheet_loader.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 document_loader::LoadType;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::DomObject;
use dom::element::Element;
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::node::{document_from_node, window_from_node};
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use hyper_serde::Serde;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::{FetchResponseListener, FetchMetadata, Metadata, NetworkError, ReferrerPolicy};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use network_listener::{NetworkListener, PreInvoke};
use parking_lot::RwLock;
use script_layout_interface::message::Msg;
use servo_url::ServoUrl;
use std::mem;
use std::sync::{Arc, Mutex};
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::stylesheets::{ImportRule, Stylesheet, Origin};
use style::stylesheets::StylesheetLoader as StyleStylesheetLoader;
pub trait StylesheetOwner {
/// Returns whether this element was inserted by the parser (i.e., it should
/// trigger a document-load-blocking load).
fn parser_inserted(&self) -> bool;
/// Which referrer policy should loads triggered by this owner follow, or
/// `None` for the default.
fn referrer_policy(&self) -> Option<ReferrerPolicy>;
/// Notes that a new load is pending to finish.
fn increment_pending_loads_count(&self);
/// Returns None if there are still pending loads, or whether any load has
/// failed since the loads started.
fn load_finished(&self, successful: bool) -> Option<bool>;
}
pub enum StylesheetContextSource {
// NB: `media` is just an option so we avoid cloning it.
LinkElement { media: Option<MediaList>, url: ServoUrl },
Import(Arc<RwLock<ImportRule>>),
}
impl StylesheetContextSource {
fn url(&self) -> ServoUrl {
match *self {
StylesheetContextSource::LinkElement { ref url,.. } => url.clone(),
StylesheetContextSource::Import(ref import) => {
let import = import.read();
// Look at the parser in style::stylesheets, where we don't
// trigger a load if the url is invalid.
import.url.url()
.expect("Invalid urls shouldn't enter the loader")
.clone()
}
}
}
}
/// The context required for asynchronously loading an external stylesheet.
pub struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLElement>,
source: StylesheetContextSource,
metadata: Option<Metadata>,
/// The response body received to date.
data: Vec<u8>,
}
impl PreInvoke for StylesheetContext {}
impl FetchResponseListener for StylesheetContext {
fn process_request_body(&mut self)
|
fn process_request_eof(&mut self) {}
fn process_response(&mut self,
metadata: Result<FetchMetadata, NetworkError>) {
self.metadata = metadata.ok().map(|m| {
match m {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { unsafe_,.. } => unsafe_
}
});
}
fn process_response_chunk(&mut self, mut payload: Vec<u8>) {
self.data.append(&mut payload);
}
fn process_response_eof(&mut self, status: Result<(), NetworkError>) {
let elem = self.elem.root();
let document = document_from_node(&*elem);
let mut successful = false;
if status.is_ok() {
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
let is_css = metadata.content_type.map_or(false, |Serde(ContentType(Mime(top, sub, _)))|
top == TopLevel::Text && sub == SubLevel::Css);
let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] };
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let win = window_from_node(&*elem);
let loader = StylesheetLoader::for_element(&elem);
match self.source {
StylesheetContextSource::LinkElement { ref mut media,.. } => {
let sheet =
Arc::new(Stylesheet::from_bytes(&data, final_url,
protocol_encoding_label,
Some(environment_encoding),
Origin::Author,
media.take().unwrap(),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default()));
elem.downcast::<HTMLLinkElement>()
.unwrap()
.set_stylesheet(sheet.clone());
let win = window_from_node(&*elem);
win.layout_chan().send(Msg::AddStylesheet(sheet)).unwrap();
}
StylesheetContextSource::Import(ref import) => {
let import = import.read();
Stylesheet::update_from_bytes(&import.stylesheet,
&data,
protocol_encoding_label,
Some(environment_encoding),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default());
}
}
document.invalidate_stylesheets();
// FIXME: Revisit once consensus is reached at:
// https://github.com/whatwg/html/issues/1142
successful = metadata.status.map_or(false, |(code, _)| code == 200);
}
let owner = elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
if owner.parser_inserted() {
document.decrement_script_blocking_stylesheet_count();
}
let url = self.source.url();
document.finish_load(LoadType::Stylesheet(url));
if let Some(any_failed) = owner.load_finished(successful) {
let event = if any_failed { atom!("error") } else { atom!("load") };
elem.upcast::<EventTarget>().fire_event(event);
}
}
}
pub struct StylesheetLoader<'a> {
elem: &'a HTMLElement,
}
impl<'a> StylesheetLoader<'a> {
pub fn for_element(element: &'a HTMLElement) -> Self {
StylesheetLoader {
elem: element,
}
}
}
impl<'a> StylesheetLoader<'a> {
pub fn load(&self, source: StylesheetContextSource) {
let url = source.url();
let context = Arc::new(Mutex::new(StylesheetContext {
elem: Trusted::new(&*self.elem),
source: source,
metadata: None,
data: vec![],
}));
let document = document_from_node(self.elem);
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
task_source: document.window().networking_task_source(),
wrapper: Some(document.window().get_runnable_wrapper())
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_fetch(message.to().unwrap());
});
let owner = self.elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
let referrer_policy = owner.referrer_policy()
.or_else(|| document.get_referrer_policy());
owner.increment_pending_loads_count();
if owner.parser_inserted() {
document.increment_script_blocking_stylesheet_count();
}
let request = RequestInit {
url: url.clone(),
type_: RequestType::Style,
destination: Destination::Style,
credentials_mode: CredentialsMode::Include,
use_url_credentials: true,
origin: document.url(),
pipeline_id: Some(self.elem.global().pipeline_id()),
referrer_url: Some(document.url()),
referrer_policy: referrer_policy,
.. RequestInit::default()
};
document.fetch_async(LoadType::Stylesheet(url), request, action_sender);
}
}
impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> {
fn request_stylesheet(&self, import: &Arc<RwLock<ImportRule>>) {
self.load(StylesheetContextSource::Import(import.clone()))
}
}
|
{}
|
identifier_body
|
stylesheet_loader.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 document_loader::LoadType;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::DomObject;
use dom::element::Element;
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::node::{document_from_node, window_from_node};
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use hyper_serde::Serde;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::{FetchResponseListener, FetchMetadata, Metadata, NetworkError, ReferrerPolicy};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use network_listener::{NetworkListener, PreInvoke};
use parking_lot::RwLock;
use script_layout_interface::message::Msg;
use servo_url::ServoUrl;
use std::mem;
use std::sync::{Arc, Mutex};
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::stylesheets::{ImportRule, Stylesheet, Origin};
use style::stylesheets::StylesheetLoader as StyleStylesheetLoader;
pub trait StylesheetOwner {
/// Returns whether this element was inserted by the parser (i.e., it should
/// trigger a document-load-blocking load).
fn parser_inserted(&self) -> bool;
/// Which referrer policy should loads triggered by this owner follow, or
/// `None` for the default.
fn referrer_policy(&self) -> Option<ReferrerPolicy>;
/// Notes that a new load is pending to finish.
fn increment_pending_loads_count(&self);
/// Returns None if there are still pending loads, or whether any load has
/// failed since the loads started.
fn load_finished(&self, successful: bool) -> Option<bool>;
}
pub enum StylesheetContextSource {
// NB: `media` is just an option so we avoid cloning it.
LinkElement { media: Option<MediaList>, url: ServoUrl },
Import(Arc<RwLock<ImportRule>>),
}
impl StylesheetContextSource {
fn url(&self) -> ServoUrl {
match *self {
StylesheetContextSource::LinkElement { ref url,.. } => url.clone(),
StylesheetContextSource::Import(ref import) => {
let import = import.read();
// Look at the parser in style::stylesheets, where we don't
// trigger a load if the url is invalid.
import.url.url()
.expect("Invalid urls shouldn't enter the loader")
.clone()
}
}
}
}
/// The context required for asynchronously loading an external stylesheet.
pub struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLElement>,
source: StylesheetContextSource,
metadata: Option<Metadata>,
/// The response body received to date.
data: Vec<u8>,
}
impl PreInvoke for StylesheetContext {}
impl FetchResponseListener for StylesheetContext {
fn process_request_body(&mut self) {}
fn process_request_eof(&mut self) {}
fn process_response(&mut self,
metadata: Result<FetchMetadata, NetworkError>) {
self.metadata = metadata.ok().map(|m| {
match m {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { unsafe_,.. } => unsafe_
}
});
}
fn process_response_chunk(&mut self, mut payload: Vec<u8>) {
self.data.append(&mut payload);
}
fn process_response_eof(&mut self, status: Result<(), NetworkError>) {
let elem = self.elem.root();
let document = document_from_node(&*elem);
let mut successful = false;
if status.is_ok() {
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
let is_css = metadata.content_type.map_or(false, |Serde(ContentType(Mime(top, sub, _)))|
top == TopLevel::Text && sub == SubLevel::Css);
let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] };
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let win = window_from_node(&*elem);
let loader = StylesheetLoader::for_element(&elem);
match self.source {
StylesheetContextSource::LinkElement { ref mut media,.. } => {
let sheet =
Arc::new(Stylesheet::from_bytes(&data, final_url,
protocol_encoding_label,
Some(environment_encoding),
Origin::Author,
media.take().unwrap(),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default()));
elem.downcast::<HTMLLinkElement>()
.unwrap()
.set_stylesheet(sheet.clone());
let win = window_from_node(&*elem);
win.layout_chan().send(Msg::AddStylesheet(sheet)).unwrap();
}
StylesheetContextSource::Import(ref import) => {
let import = import.read();
Stylesheet::update_from_bytes(&import.stylesheet,
&data,
protocol_encoding_label,
Some(environment_encoding),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default());
}
}
document.invalidate_stylesheets();
// FIXME: Revisit once consensus is reached at:
// https://github.com/whatwg/html/issues/1142
successful = metadata.status.map_or(false, |(code, _)| code == 200);
}
let owner = elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
if owner.parser_inserted() {
document.decrement_script_blocking_stylesheet_count();
}
let url = self.source.url();
document.finish_load(LoadType::Stylesheet(url));
if let Some(any_failed) = owner.load_finished(successful) {
let event = if any_failed { atom!("error") } else { atom!("load") };
elem.upcast::<EventTarget>().fire_event(event);
}
}
}
pub struct StylesheetLoader<'a> {
elem: &'a HTMLElement,
}
impl<'a> StylesheetLoader<'a> {
pub fn
|
(element: &'a HTMLElement) -> Self {
StylesheetLoader {
elem: element,
}
}
}
impl<'a> StylesheetLoader<'a> {
pub fn load(&self, source: StylesheetContextSource) {
let url = source.url();
let context = Arc::new(Mutex::new(StylesheetContext {
elem: Trusted::new(&*self.elem),
source: source,
metadata: None,
data: vec![],
}));
let document = document_from_node(self.elem);
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
task_source: document.window().networking_task_source(),
wrapper: Some(document.window().get_runnable_wrapper())
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_fetch(message.to().unwrap());
});
let owner = self.elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
let referrer_policy = owner.referrer_policy()
.or_else(|| document.get_referrer_policy());
owner.increment_pending_loads_count();
if owner.parser_inserted() {
document.increment_script_blocking_stylesheet_count();
}
let request = RequestInit {
url: url.clone(),
type_: RequestType::Style,
destination: Destination::Style,
credentials_mode: CredentialsMode::Include,
use_url_credentials: true,
origin: document.url(),
pipeline_id: Some(self.elem.global().pipeline_id()),
referrer_url: Some(document.url()),
referrer_policy: referrer_policy,
.. RequestInit::default()
};
document.fetch_async(LoadType::Stylesheet(url), request, action_sender);
}
}
impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> {
fn request_stylesheet(&self, import: &Arc<RwLock<ImportRule>>) {
self.load(StylesheetContextSource::Import(import.clone()))
}
}
|
for_element
|
identifier_name
|
stylesheet_loader.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 document_loader::LoadType;
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::DomObject;
use dom::element::Element;
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement;
use dom::htmllinkelement::HTMLLinkElement;
use dom::node::{document_from_node, window_from_node};
use encoding::EncodingRef;
use encoding::all::UTF_8;
use hyper::header::ContentType;
use hyper::mime::{Mime, TopLevel, SubLevel};
use hyper_serde::Serde;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::{FetchResponseListener, FetchMetadata, Metadata, NetworkError, ReferrerPolicy};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use network_listener::{NetworkListener, PreInvoke};
use parking_lot::RwLock;
use script_layout_interface::message::Msg;
use servo_url::ServoUrl;
use std::mem;
use std::sync::{Arc, Mutex};
use style::media_queries::MediaList;
use style::parser::ParserContextExtraData;
use style::stylesheets::{ImportRule, Stylesheet, Origin};
use style::stylesheets::StylesheetLoader as StyleStylesheetLoader;
pub trait StylesheetOwner {
/// Returns whether this element was inserted by the parser (i.e., it should
/// trigger a document-load-blocking load).
fn parser_inserted(&self) -> bool;
/// Which referrer policy should loads triggered by this owner follow, or
/// `None` for the default.
fn referrer_policy(&self) -> Option<ReferrerPolicy>;
/// Notes that a new load is pending to finish.
fn increment_pending_loads_count(&self);
/// Returns None if there are still pending loads, or whether any load has
/// failed since the loads started.
fn load_finished(&self, successful: bool) -> Option<bool>;
}
pub enum StylesheetContextSource {
// NB: `media` is just an option so we avoid cloning it.
LinkElement { media: Option<MediaList>, url: ServoUrl },
Import(Arc<RwLock<ImportRule>>),
}
impl StylesheetContextSource {
fn url(&self) -> ServoUrl {
match *self {
StylesheetContextSource::LinkElement { ref url,.. } => url.clone(),
StylesheetContextSource::Import(ref import) => {
let import = import.read();
// Look at the parser in style::stylesheets, where we don't
// trigger a load if the url is invalid.
import.url.url()
.expect("Invalid urls shouldn't enter the loader")
.clone()
}
}
}
}
/// The context required for asynchronously loading an external stylesheet.
pub struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLElement>,
source: StylesheetContextSource,
metadata: Option<Metadata>,
/// The response body received to date.
data: Vec<u8>,
}
impl PreInvoke for StylesheetContext {}
impl FetchResponseListener for StylesheetContext {
fn process_request_body(&mut self) {}
fn process_request_eof(&mut self) {}
fn process_response(&mut self,
metadata: Result<FetchMetadata, NetworkError>) {
self.metadata = metadata.ok().map(|m| {
match m {
FetchMetadata::Unfiltered(m) => m,
FetchMetadata::Filtered { unsafe_,.. } => unsafe_
}
});
}
fn process_response_chunk(&mut self, mut payload: Vec<u8>) {
self.data.append(&mut payload);
}
fn process_response_eof(&mut self, status: Result<(), NetworkError>) {
let elem = self.elem.root();
let document = document_from_node(&*elem);
let mut successful = false;
if status.is_ok() {
let metadata = match self.metadata.take() {
Some(meta) => meta,
None => return,
};
|
let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] };
// TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding
let environment_encoding = UTF_8 as EncodingRef;
let protocol_encoding_label = metadata.charset.as_ref().map(|s| &**s);
let final_url = metadata.final_url;
let win = window_from_node(&*elem);
let loader = StylesheetLoader::for_element(&elem);
match self.source {
StylesheetContextSource::LinkElement { ref mut media,.. } => {
let sheet =
Arc::new(Stylesheet::from_bytes(&data, final_url,
protocol_encoding_label,
Some(environment_encoding),
Origin::Author,
media.take().unwrap(),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default()));
elem.downcast::<HTMLLinkElement>()
.unwrap()
.set_stylesheet(sheet.clone());
let win = window_from_node(&*elem);
win.layout_chan().send(Msg::AddStylesheet(sheet)).unwrap();
}
StylesheetContextSource::Import(ref import) => {
let import = import.read();
Stylesheet::update_from_bytes(&import.stylesheet,
&data,
protocol_encoding_label,
Some(environment_encoding),
Some(&loader),
win.css_error_reporter(),
ParserContextExtraData::default());
}
}
document.invalidate_stylesheets();
// FIXME: Revisit once consensus is reached at:
// https://github.com/whatwg/html/issues/1142
successful = metadata.status.map_or(false, |(code, _)| code == 200);
}
let owner = elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
if owner.parser_inserted() {
document.decrement_script_blocking_stylesheet_count();
}
let url = self.source.url();
document.finish_load(LoadType::Stylesheet(url));
if let Some(any_failed) = owner.load_finished(successful) {
let event = if any_failed { atom!("error") } else { atom!("load") };
elem.upcast::<EventTarget>().fire_event(event);
}
}
}
pub struct StylesheetLoader<'a> {
elem: &'a HTMLElement,
}
impl<'a> StylesheetLoader<'a> {
pub fn for_element(element: &'a HTMLElement) -> Self {
StylesheetLoader {
elem: element,
}
}
}
impl<'a> StylesheetLoader<'a> {
pub fn load(&self, source: StylesheetContextSource) {
let url = source.url();
let context = Arc::new(Mutex::new(StylesheetContext {
elem: Trusted::new(&*self.elem),
source: source,
metadata: None,
data: vec![],
}));
let document = document_from_node(self.elem);
let (action_sender, action_receiver) = ipc::channel().unwrap();
let listener = NetworkListener {
context: context,
task_source: document.window().networking_task_source(),
wrapper: Some(document.window().get_runnable_wrapper())
};
ROUTER.add_route(action_receiver.to_opaque(), box move |message| {
listener.notify_fetch(message.to().unwrap());
});
let owner = self.elem.upcast::<Element>().as_stylesheet_owner()
.expect("Stylesheet not loaded by <style> or <link> element!");
let referrer_policy = owner.referrer_policy()
.or_else(|| document.get_referrer_policy());
owner.increment_pending_loads_count();
if owner.parser_inserted() {
document.increment_script_blocking_stylesheet_count();
}
let request = RequestInit {
url: url.clone(),
type_: RequestType::Style,
destination: Destination::Style,
credentials_mode: CredentialsMode::Include,
use_url_credentials: true,
origin: document.url(),
pipeline_id: Some(self.elem.global().pipeline_id()),
referrer_url: Some(document.url()),
referrer_policy: referrer_policy,
.. RequestInit::default()
};
document.fetch_async(LoadType::Stylesheet(url), request, action_sender);
}
}
impl<'a> StyleStylesheetLoader for StylesheetLoader<'a> {
fn request_stylesheet(&self, import: &Arc<RwLock<ImportRule>>) {
self.load(StylesheetContextSource::Import(import.clone()))
}
}
|
let is_css = metadata.content_type.map_or(false, |Serde(ContentType(Mime(top, sub, _)))|
top == TopLevel::Text && sub == SubLevel::Css);
|
random_line_split
|
main.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate time;
#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
use std::io::Cursor;
use gfx::traits::{Factory, Stream, FactoryExt};
gfx_vertex!( Vertex {
a_Pos@ pos: [f32; 2],
a_Uv@ uv: [f32; 2],
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
gfx_parameters!( Params {
t_Color@ color: gfx::shade::TextureParam<R>,
t_Flow@ flow: gfx::shade::TextureParam<R>,
t_Noise@ noise: gfx::shade::TextureParam<R>,
f_Offset0@ offset0: f32,
f_Offset1@ offset1: f32,
});
fn
|
<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::Texture<R>, String>
where R: gfx::Resources, F: gfx::device::Factory<R> {
let img = image::load(Cursor::new(data), image::PNG).unwrap();
let img = match img {
image::DynamicImage::ImageRgba8(img) => img,
img => img.to_rgba()
};
let (width, height) = img.dimensions();
let tex_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Kind::D2,
format: gfx::tex::RGBA8
};
Ok(factory.create_texture_static(tex_info, &img).unwrap())
}
pub fn main() {
use time::precise_time_s;
let (mut stream, mut device, mut factory) = gfx_window_glutin::init(
glutin::WindowBuilder::new()
.with_title("Flowmap example".to_string())
.with_dimensions(800, 600).build().unwrap()
);
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, -1.0], [1.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, 1.0], [0.0, 1.0]),
];
let mesh = factory.create_mesh(&vertex_data);
let water_texture = load_texture(&mut factory, &include_bytes!("image/water.png")[..]).unwrap();
let flow_texture = load_texture(&mut factory, &include_bytes!("image/flow.png")[..]).unwrap();
let noise_texture = load_texture(&mut factory, &include_bytes!("image/noise.png")[..]).unwrap();
let program = {
let vs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslv")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslv")),
.. gfx::ShaderSource::empty()
};
let fs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslf")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslf")),
.. gfx::ShaderSource::empty()
};
factory.link_program_source(vs, fs).unwrap()
};
let uniforms = Params {
color: (water_texture, None),
flow: (flow_texture, None),
noise: (noise_texture, None),
offset0: 0f32,
offset1: 0.5f32,
_r: std::marker::PhantomData,
};
let mut batch = gfx::batch::Full::new(mesh, program, uniforms).unwrap();
let mut cycle0 = 0.0f32;
let mut cycle1 = 0.5f32;
let mut time_start = precise_time_s();
let mut time_end;
'main: loop {
time_end = time_start;
time_start = precise_time_s();
let delta = (time_start - time_end) as f32;
// quit when Esc is pressed.
for event in stream.out.window.poll_events() {
match event {
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break'main,
glutin::Event::Closed => break'main,
_ => {},
}
}
// since we sample our diffuse texture twice we need to lerp between
// them to get a smooth transition (shouldn't even be noticable).
// they start half a cycle apart (0.5) and is later used to calculate
// the interpolation amount via `2.0 * abs(cycle0 -.5f)`
cycle0 += 0.25f32 * delta;
if cycle0 > 1f32 {
cycle0 -= 1f32;
}
cycle1 += 0.25f32 * delta;
if cycle1 > 1f32 {
cycle1 -= 1f32;
}
batch.params.offset0 = cycle0;
batch.params.offset1 = cycle1;
stream.clear(gfx::ClearData {
color: [0.3, 0.3, 0.3, 1.0],
depth: 1.0,
stencil: 0,
});
stream.draw(&batch).unwrap();
stream.present(&mut device);
}
}
|
load_texture
|
identifier_name
|
main.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate time;
#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
use std::io::Cursor;
use gfx::traits::{Factory, Stream, FactoryExt};
gfx_vertex!( Vertex {
a_Pos@ pos: [f32; 2],
a_Uv@ uv: [f32; 2],
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
gfx_parameters!( Params {
t_Color@ color: gfx::shade::TextureParam<R>,
t_Flow@ flow: gfx::shade::TextureParam<R>,
t_Noise@ noise: gfx::shade::TextureParam<R>,
f_Offset0@ offset0: f32,
f_Offset1@ offset1: f32,
});
fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::Texture<R>, String>
where R: gfx::Resources, F: gfx::device::Factory<R> {
let img = image::load(Cursor::new(data), image::PNG).unwrap();
let img = match img {
image::DynamicImage::ImageRgba8(img) => img,
img => img.to_rgba()
};
let (width, height) = img.dimensions();
let tex_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Kind::D2,
format: gfx::tex::RGBA8
};
Ok(factory.create_texture_static(tex_info, &img).unwrap())
}
pub fn main()
|
let water_texture = load_texture(&mut factory, &include_bytes!("image/water.png")[..]).unwrap();
let flow_texture = load_texture(&mut factory, &include_bytes!("image/flow.png")[..]).unwrap();
let noise_texture = load_texture(&mut factory, &include_bytes!("image/noise.png")[..]).unwrap();
let program = {
let vs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslv")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslv")),
.. gfx::ShaderSource::empty()
};
let fs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslf")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslf")),
.. gfx::ShaderSource::empty()
};
factory.link_program_source(vs, fs).unwrap()
};
let uniforms = Params {
color: (water_texture, None),
flow: (flow_texture, None),
noise: (noise_texture, None),
offset0: 0f32,
offset1: 0.5f32,
_r: std::marker::PhantomData,
};
let mut batch = gfx::batch::Full::new(mesh, program, uniforms).unwrap();
let mut cycle0 = 0.0f32;
let mut cycle1 = 0.5f32;
let mut time_start = precise_time_s();
let mut time_end;
'main: loop {
time_end = time_start;
time_start = precise_time_s();
let delta = (time_start - time_end) as f32;
// quit when Esc is pressed.
for event in stream.out.window.poll_events() {
match event {
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break'main,
glutin::Event::Closed => break'main,
_ => {},
}
}
// since we sample our diffuse texture twice we need to lerp between
// them to get a smooth transition (shouldn't even be noticable).
// they start half a cycle apart (0.5) and is later used to calculate
// the interpolation amount via `2.0 * abs(cycle0 -.5f)`
cycle0 += 0.25f32 * delta;
if cycle0 > 1f32 {
cycle0 -= 1f32;
}
cycle1 += 0.25f32 * delta;
if cycle1 > 1f32 {
cycle1 -= 1f32;
}
batch.params.offset0 = cycle0;
batch.params.offset1 = cycle1;
stream.clear(gfx::ClearData {
color: [0.3, 0.3, 0.3, 1.0],
depth: 1.0,
stencil: 0,
});
stream.draw(&batch).unwrap();
stream.present(&mut device);
}
}
|
{
use time::precise_time_s;
let (mut stream, mut device, mut factory) = gfx_window_glutin::init(
glutin::WindowBuilder::new()
.with_title("Flowmap example".to_string())
.with_dimensions(800, 600).build().unwrap()
);
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, -1.0], [1.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, 1.0], [0.0, 1.0]),
];
let mesh = factory.create_mesh(&vertex_data);
|
identifier_body
|
main.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate time;
#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
use std::io::Cursor;
use gfx::traits::{Factory, Stream, FactoryExt};
gfx_vertex!( Vertex {
a_Pos@ pos: [f32; 2],
a_Uv@ uv: [f32; 2],
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
gfx_parameters!( Params {
t_Color@ color: gfx::shade::TextureParam<R>,
t_Flow@ flow: gfx::shade::TextureParam<R>,
t_Noise@ noise: gfx::shade::TextureParam<R>,
f_Offset0@ offset0: f32,
f_Offset1@ offset1: f32,
});
fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::Texture<R>, String>
where R: gfx::Resources, F: gfx::device::Factory<R> {
let img = image::load(Cursor::new(data), image::PNG).unwrap();
let img = match img {
image::DynamicImage::ImageRgba8(img) => img,
img => img.to_rgba()
};
let (width, height) = img.dimensions();
let tex_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Kind::D2,
format: gfx::tex::RGBA8
};
Ok(factory.create_texture_static(tex_info, &img).unwrap())
}
pub fn main() {
use time::precise_time_s;
let (mut stream, mut device, mut factory) = gfx_window_glutin::init(
glutin::WindowBuilder::new()
.with_title("Flowmap example".to_string())
.with_dimensions(800, 600).build().unwrap()
);
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, -1.0], [1.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, 1.0], [0.0, 1.0]),
];
let mesh = factory.create_mesh(&vertex_data);
let water_texture = load_texture(&mut factory, &include_bytes!("image/water.png")[..]).unwrap();
let flow_texture = load_texture(&mut factory, &include_bytes!("image/flow.png")[..]).unwrap();
let noise_texture = load_texture(&mut factory, &include_bytes!("image/noise.png")[..]).unwrap();
let program = {
let vs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslv")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslv")),
.. gfx::ShaderSource::empty()
};
let fs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslf")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslf")),
.. gfx::ShaderSource::empty()
};
factory.link_program_source(vs, fs).unwrap()
};
let uniforms = Params {
color: (water_texture, None),
flow: (flow_texture, None),
noise: (noise_texture, None),
offset0: 0f32,
offset1: 0.5f32,
_r: std::marker::PhantomData,
};
let mut batch = gfx::batch::Full::new(mesh, program, uniforms).unwrap();
let mut cycle0 = 0.0f32;
let mut cycle1 = 0.5f32;
let mut time_start = precise_time_s();
let mut time_end;
'main: loop {
time_end = time_start;
time_start = precise_time_s();
let delta = (time_start - time_end) as f32;
// quit when Esc is pressed.
for event in stream.out.window.poll_events() {
match event {
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break'main,
glutin::Event::Closed => break'main,
_ =>
|
,
}
}
// since we sample our diffuse texture twice we need to lerp between
// them to get a smooth transition (shouldn't even be noticable).
// they start half a cycle apart (0.5) and is later used to calculate
// the interpolation amount via `2.0 * abs(cycle0 -.5f)`
cycle0 += 0.25f32 * delta;
if cycle0 > 1f32 {
cycle0 -= 1f32;
}
cycle1 += 0.25f32 * delta;
if cycle1 > 1f32 {
cycle1 -= 1f32;
}
batch.params.offset0 = cycle0;
batch.params.offset1 = cycle1;
stream.clear(gfx::ClearData {
color: [0.3, 0.3, 0.3, 1.0],
depth: 1.0,
stencil: 0,
});
stream.draw(&batch).unwrap();
stream.present(&mut device);
}
}
|
{}
|
conditional_block
|
main.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate time;
#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
use std::io::Cursor;
use gfx::traits::{Factory, Stream, FactoryExt};
gfx_vertex!( Vertex {
a_Pos@ pos: [f32; 2],
a_Uv@ uv: [f32; 2],
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
gfx_parameters!( Params {
t_Color@ color: gfx::shade::TextureParam<R>,
t_Flow@ flow: gfx::shade::TextureParam<R>,
t_Noise@ noise: gfx::shade::TextureParam<R>,
f_Offset0@ offset0: f32,
f_Offset1@ offset1: f32,
});
fn load_texture<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::Texture<R>, String>
where R: gfx::Resources, F: gfx::device::Factory<R> {
let img = image::load(Cursor::new(data), image::PNG).unwrap();
let img = match img {
image::DynamicImage::ImageRgba8(img) => img,
img => img.to_rgba()
};
let (width, height) = img.dimensions();
let tex_info = gfx::tex::TextureInfo {
width: width as u16,
height: height as u16,
depth: 1,
levels: 1,
kind: gfx::tex::Kind::D2,
format: gfx::tex::RGBA8
};
Ok(factory.create_texture_static(tex_info, &img).unwrap())
}
pub fn main() {
use time::precise_time_s;
let (mut stream, mut device, mut factory) = gfx_window_glutin::init(
glutin::WindowBuilder::new()
.with_title("Flowmap example".to_string())
.with_dimensions(800, 600).build().unwrap()
);
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, -1.0], [1.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, -1.0], [0.0, 0.0]),
Vertex::new([ 1.0, 1.0], [1.0, 1.0]),
Vertex::new([-1.0, 1.0], [0.0, 1.0]),
];
let mesh = factory.create_mesh(&vertex_data);
let water_texture = load_texture(&mut factory, &include_bytes!("image/water.png")[..]).unwrap();
let flow_texture = load_texture(&mut factory, &include_bytes!("image/flow.png")[..]).unwrap();
let noise_texture = load_texture(&mut factory, &include_bytes!("image/noise.png")[..]).unwrap();
let program = {
let vs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslv")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslv")),
.. gfx::ShaderSource::empty()
};
let fs = gfx::ShaderSource {
glsl_120: Some(include_bytes!("shader/flowmap_120.glslf")),
glsl_150: Some(include_bytes!("shader/flowmap_150.glslf")),
.. gfx::ShaderSource::empty()
};
factory.link_program_source(vs, fs).unwrap()
};
let uniforms = Params {
color: (water_texture, None),
flow: (flow_texture, None),
noise: (noise_texture, None),
offset0: 0f32,
offset1: 0.5f32,
_r: std::marker::PhantomData,
};
let mut batch = gfx::batch::Full::new(mesh, program, uniforms).unwrap();
let mut cycle0 = 0.0f32;
let mut cycle1 = 0.5f32;
let mut time_start = precise_time_s();
let mut time_end;
'main: loop {
time_end = time_start;
time_start = precise_time_s();
let delta = (time_start - time_end) as f32;
// quit when Esc is pressed.
for event in stream.out.window.poll_events() {
match event {
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break'main,
glutin::Event::Closed => break'main,
_ => {},
}
}
// since we sample our diffuse texture twice we need to lerp between
// them to get a smooth transition (shouldn't even be noticable).
// they start half a cycle apart (0.5) and is later used to calculate
// the interpolation amount via `2.0 * abs(cycle0 -.5f)`
cycle0 += 0.25f32 * delta;
if cycle0 > 1f32 {
cycle0 -= 1f32;
}
cycle1 += 0.25f32 * delta;
if cycle1 > 1f32 {
cycle1 -= 1f32;
}
batch.params.offset0 = cycle0;
batch.params.offset1 = cycle1;
stream.clear(gfx::ClearData {
|
});
stream.draw(&batch).unwrap();
stream.present(&mut device);
}
}
|
color: [0.3, 0.3, 0.3, 1.0],
depth: 1.0,
stencil: 0,
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of stylesheets.
//!
//! [computed]: https://drafts.csswg.org/css-cascade/#computed
//! [specified]: https://drafts.csswg.org/css-cascade/#specified
//!
//! In particular, this crate contains the definitions of supported properties,
//! the code to parse them into specified values and calculate the computed
//! values based on the specified values, as well as the code to serialize both
//! specified and computed values.
//!
//! The main entry point is [`recalc_style_at`][recalc_style_at].
//!
//! [recalc_style_at]: traversal/fn.recalc_style_at.html
//!
//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
//! crates.
//!
//! [cssparser]:../cssparser/index.html
//! [selectors]:../selectors/index.html
#![deny(missing_docs)]
extern crate app_units;
extern crate arrayvec;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)]
extern crate byteorder;
#[cfg(feature = "gecko")]
#[macro_use]
#[no_link]
extern crate cfg_if;
#[cfg(feature = "servo")]
extern crate crossbeam_channel;
#[macro_use]
extern crate cssparser;
#[macro_use]
extern crate debug_unreachable;
extern crate euclid;
extern crate fallible;
extern crate fxhash;
#[cfg(feature = "gecko")]
#[macro_use]
pub mod gecko_string_cache;
extern crate hashglobe;
#[cfg(feature = "servo")]
#[macro_use]
extern crate html5ever;
extern crate itertools;
extern crate itoa;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of;
#[macro_use]
extern crate malloc_size_of_derive;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate matches;
#[cfg(feature = "gecko")]
pub extern crate nsstring;
#[cfg(feature = "gecko")]
extern crate num_cpus;
#[macro_use]
extern crate num_derive;
extern crate num_integer;
extern crate num_traits;
extern crate ordered_float;
extern crate owning_ref;
extern crate parking_lot;
extern crate precomputed_hash;
extern crate rayon;
extern crate selectors;
#[cfg(feature = "servo")]
#[macro_use]
extern crate serde;
pub extern crate servo_arc;
#[cfg(feature = "servo")]
#[macro_use]
extern crate servo_atoms;
#[cfg(feature = "servo")]
extern crate servo_config;
#[cfg(feature = "servo")]
extern crate servo_url;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")]
extern crate string_cache;
#[macro_use]
extern crate style_derive;
extern crate style_traits;
#[cfg(feature = "gecko")]
extern crate thin_slice;
extern crate time;
extern crate uluru;
extern crate unicode_bidi;
#[allow(unused_extern_crates)]
extern crate unicode_segmentation;
extern crate void;
#[macro_use]
mod macros;
pub mod animation;
pub mod applicable_declarations;
#[allow(missing_docs)] // TODO.
#[cfg(feature = "servo")]
pub mod attr;
pub mod author_styles;
pub mod bezier;
pub mod bloom;
pub mod context;
pub mod counter_style;
pub mod custom_properties;
pub mod data;
pub mod dom;
pub mod dom_apis;
pub mod driver;
pub mod element_state;
#[cfg(feature = "servo")]
mod encoding_support;
pub mod error_reporting;
pub mod font_face;
pub mod font_metrics;
#[cfg(feature = "gecko")]
#[allow(unsafe_code)]
pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
#[macro_use]
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cache;
pub mod rule_collector;
pub mod rule_tree;
pub mod scoped_tls;
pub mod selector_map;
pub mod selector_parser;
pub mod shared_lock;
pub mod sharing;
pub mod str;
pub mod style_adjuster;
pub mod style_resolver;
pub mod stylesheet_set;
|
pub mod timer;
pub mod traversal;
pub mod traversal_flags;
pub mod use_counters;
#[macro_use]
#[allow(non_camel_case_types)]
pub mod values;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache as string_cache;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom as Prefix;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom as LocalName;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Namespace;
#[cfg(feature = "servo")]
pub use html5ever::LocalName;
#[cfg(feature = "servo")]
pub use html5ever::Namespace;
#[cfg(feature = "servo")]
pub use html5ever::Prefix;
#[cfg(feature = "servo")]
pub use servo_atoms::Atom;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
#[deny(missing_docs)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
#[cfg(feature = "gecko")]
#[allow(unsafe_code)]
pub mod gecko;
// uses a macro from properties
#[cfg(feature = "servo")]
#[allow(unsafe_code)]
pub mod servo;
#[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)]
pub mod gecko_properties {
include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use crate::properties::longhands::$name::computed_value as $name;
)+
// Don't use a side-specific name needlessly:
pub use crate::properties::longhands::border_top_style::computed_value as border_style;
}
}
}
longhand_properties_idents!(reexport_computed_values);
#[cfg(feature = "gecko")]
use crate::gecko_string_cache::WeakAtom;
#[cfg(feature = "servo")]
use servo_atoms::Atom as WeakAtom;
/// Extension methods for selectors::attr::CaseSensitivity
pub trait CaseSensitivityExt {
/// Return whether two atoms compare equal according to this case sensitivity.
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
}
impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
}
|
pub mod stylesheets;
pub mod stylist;
pub mod thread_state;
|
random_line_split
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of stylesheets.
//!
//! [computed]: https://drafts.csswg.org/css-cascade/#computed
//! [specified]: https://drafts.csswg.org/css-cascade/#specified
//!
//! In particular, this crate contains the definitions of supported properties,
//! the code to parse them into specified values and calculate the computed
//! values based on the specified values, as well as the code to serialize both
//! specified and computed values.
//!
//! The main entry point is [`recalc_style_at`][recalc_style_at].
//!
//! [recalc_style_at]: traversal/fn.recalc_style_at.html
//!
//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
//! crates.
//!
//! [cssparser]:../cssparser/index.html
//! [selectors]:../selectors/index.html
#![deny(missing_docs)]
extern crate app_units;
extern crate arrayvec;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)]
extern crate byteorder;
#[cfg(feature = "gecko")]
#[macro_use]
#[no_link]
extern crate cfg_if;
#[cfg(feature = "servo")]
extern crate crossbeam_channel;
#[macro_use]
extern crate cssparser;
#[macro_use]
extern crate debug_unreachable;
extern crate euclid;
extern crate fallible;
extern crate fxhash;
#[cfg(feature = "gecko")]
#[macro_use]
pub mod gecko_string_cache;
extern crate hashglobe;
#[cfg(feature = "servo")]
#[macro_use]
extern crate html5ever;
extern crate itertools;
extern crate itoa;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of;
#[macro_use]
extern crate malloc_size_of_derive;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate matches;
#[cfg(feature = "gecko")]
pub extern crate nsstring;
#[cfg(feature = "gecko")]
extern crate num_cpus;
#[macro_use]
extern crate num_derive;
extern crate num_integer;
extern crate num_traits;
extern crate ordered_float;
extern crate owning_ref;
extern crate parking_lot;
extern crate precomputed_hash;
extern crate rayon;
extern crate selectors;
#[cfg(feature = "servo")]
#[macro_use]
extern crate serde;
pub extern crate servo_arc;
#[cfg(feature = "servo")]
#[macro_use]
extern crate servo_atoms;
#[cfg(feature = "servo")]
extern crate servo_config;
#[cfg(feature = "servo")]
extern crate servo_url;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")]
extern crate string_cache;
#[macro_use]
extern crate style_derive;
extern crate style_traits;
#[cfg(feature = "gecko")]
extern crate thin_slice;
extern crate time;
extern crate uluru;
extern crate unicode_bidi;
#[allow(unused_extern_crates)]
extern crate unicode_segmentation;
extern crate void;
#[macro_use]
mod macros;
pub mod animation;
pub mod applicable_declarations;
#[allow(missing_docs)] // TODO.
#[cfg(feature = "servo")]
pub mod attr;
pub mod author_styles;
pub mod bezier;
pub mod bloom;
pub mod context;
pub mod counter_style;
pub mod custom_properties;
pub mod data;
pub mod dom;
pub mod dom_apis;
pub mod driver;
pub mod element_state;
#[cfg(feature = "servo")]
mod encoding_support;
pub mod error_reporting;
pub mod font_face;
pub mod font_metrics;
#[cfg(feature = "gecko")]
#[allow(unsafe_code)]
pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
#[macro_use]
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cache;
pub mod rule_collector;
pub mod rule_tree;
pub mod scoped_tls;
pub mod selector_map;
pub mod selector_parser;
pub mod shared_lock;
pub mod sharing;
pub mod str;
pub mod style_adjuster;
pub mod style_resolver;
pub mod stylesheet_set;
pub mod stylesheets;
pub mod stylist;
pub mod thread_state;
pub mod timer;
pub mod traversal;
pub mod traversal_flags;
pub mod use_counters;
#[macro_use]
#[allow(non_camel_case_types)]
pub mod values;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache as string_cache;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom as Prefix;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom as LocalName;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Namespace;
#[cfg(feature = "servo")]
pub use html5ever::LocalName;
#[cfg(feature = "servo")]
pub use html5ever::Namespace;
#[cfg(feature = "servo")]
pub use html5ever::Prefix;
#[cfg(feature = "servo")]
pub use servo_atoms::Atom;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
#[deny(missing_docs)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
#[cfg(feature = "gecko")]
#[allow(unsafe_code)]
pub mod gecko;
// uses a macro from properties
#[cfg(feature = "servo")]
#[allow(unsafe_code)]
pub mod servo;
#[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)]
pub mod gecko_properties {
include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use crate::properties::longhands::$name::computed_value as $name;
)+
// Don't use a side-specific name needlessly:
pub use crate::properties::longhands::border_top_style::computed_value as border_style;
}
}
}
longhand_properties_idents!(reexport_computed_values);
#[cfg(feature = "gecko")]
use crate::gecko_string_cache::WeakAtom;
#[cfg(feature = "servo")]
use servo_atoms::Atom as WeakAtom;
/// Extension methods for selectors::attr::CaseSensitivity
pub trait CaseSensitivityExt {
/// Return whether two atoms compare equal according to this case sensitivity.
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
}
impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
fn
|
(self, a: &WeakAtom, b: &WeakAtom) -> bool {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
}
|
eq_atom
|
identifier_name
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of stylesheets.
//!
//! [computed]: https://drafts.csswg.org/css-cascade/#computed
//! [specified]: https://drafts.csswg.org/css-cascade/#specified
//!
//! In particular, this crate contains the definitions of supported properties,
//! the code to parse them into specified values and calculate the computed
//! values based on the specified values, as well as the code to serialize both
//! specified and computed values.
//!
//! The main entry point is [`recalc_style_at`][recalc_style_at].
//!
//! [recalc_style_at]: traversal/fn.recalc_style_at.html
//!
//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
//! crates.
//!
//! [cssparser]:../cssparser/index.html
//! [selectors]:../selectors/index.html
#![deny(missing_docs)]
extern crate app_units;
extern crate arrayvec;
extern crate atomic_refcell;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)]
extern crate byteorder;
#[cfg(feature = "gecko")]
#[macro_use]
#[no_link]
extern crate cfg_if;
#[cfg(feature = "servo")]
extern crate crossbeam_channel;
#[macro_use]
extern crate cssparser;
#[macro_use]
extern crate debug_unreachable;
extern crate euclid;
extern crate fallible;
extern crate fxhash;
#[cfg(feature = "gecko")]
#[macro_use]
pub mod gecko_string_cache;
extern crate hashglobe;
#[cfg(feature = "servo")]
#[macro_use]
extern crate html5ever;
extern crate itertools;
extern crate itoa;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate malloc_size_of;
#[macro_use]
extern crate malloc_size_of_derive;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate matches;
#[cfg(feature = "gecko")]
pub extern crate nsstring;
#[cfg(feature = "gecko")]
extern crate num_cpus;
#[macro_use]
extern crate num_derive;
extern crate num_integer;
extern crate num_traits;
extern crate ordered_float;
extern crate owning_ref;
extern crate parking_lot;
extern crate precomputed_hash;
extern crate rayon;
extern crate selectors;
#[cfg(feature = "servo")]
#[macro_use]
extern crate serde;
pub extern crate servo_arc;
#[cfg(feature = "servo")]
#[macro_use]
extern crate servo_atoms;
#[cfg(feature = "servo")]
extern crate servo_config;
#[cfg(feature = "servo")]
extern crate servo_url;
extern crate smallbitvec;
extern crate smallvec;
#[cfg(feature = "servo")]
extern crate string_cache;
#[macro_use]
extern crate style_derive;
extern crate style_traits;
#[cfg(feature = "gecko")]
extern crate thin_slice;
extern crate time;
extern crate uluru;
extern crate unicode_bidi;
#[allow(unused_extern_crates)]
extern crate unicode_segmentation;
extern crate void;
#[macro_use]
mod macros;
pub mod animation;
pub mod applicable_declarations;
#[allow(missing_docs)] // TODO.
#[cfg(feature = "servo")]
pub mod attr;
pub mod author_styles;
pub mod bezier;
pub mod bloom;
pub mod context;
pub mod counter_style;
pub mod custom_properties;
pub mod data;
pub mod dom;
pub mod dom_apis;
pub mod driver;
pub mod element_state;
#[cfg(feature = "servo")]
mod encoding_support;
pub mod error_reporting;
pub mod font_face;
pub mod font_metrics;
#[cfg(feature = "gecko")]
#[allow(unsafe_code)]
pub mod gecko_bindings;
pub mod hash;
pub mod invalidation;
#[allow(missing_docs)] // TODO.
pub mod logical_geometry;
pub mod matching;
#[macro_use]
pub mod media_queries;
pub mod parallel;
pub mod parser;
pub mod rule_cache;
pub mod rule_collector;
pub mod rule_tree;
pub mod scoped_tls;
pub mod selector_map;
pub mod selector_parser;
pub mod shared_lock;
pub mod sharing;
pub mod str;
pub mod style_adjuster;
pub mod style_resolver;
pub mod stylesheet_set;
pub mod stylesheets;
pub mod stylist;
pub mod thread_state;
pub mod timer;
pub mod traversal;
pub mod traversal_flags;
pub mod use_counters;
#[macro_use]
#[allow(non_camel_case_types)]
pub mod values;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache as string_cache;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom as Prefix;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Atom as LocalName;
#[cfg(feature = "gecko")]
pub use crate::gecko_string_cache::Namespace;
#[cfg(feature = "servo")]
pub use html5ever::LocalName;
#[cfg(feature = "servo")]
pub use html5ever::Namespace;
#[cfg(feature = "servo")]
pub use html5ever::Prefix;
#[cfg(feature = "servo")]
pub use servo_atoms::Atom;
/// The CSS properties supported by the style system.
/// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
#[deny(missing_docs)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs"));
}
#[cfg(feature = "gecko")]
#[allow(unsafe_code)]
pub mod gecko;
// uses a macro from properties
#[cfg(feature = "servo")]
#[allow(unsafe_code)]
pub mod servo;
#[cfg(feature = "gecko")]
#[allow(unsafe_code, missing_docs)]
pub mod gecko_properties {
include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use crate::properties::longhands::$name::computed_value as $name;
)+
// Don't use a side-specific name needlessly:
pub use crate::properties::longhands::border_top_style::computed_value as border_style;
}
}
}
longhand_properties_idents!(reexport_computed_values);
#[cfg(feature = "gecko")]
use crate::gecko_string_cache::WeakAtom;
#[cfg(feature = "servo")]
use servo_atoms::Atom as WeakAtom;
/// Extension methods for selectors::attr::CaseSensitivity
pub trait CaseSensitivityExt {
/// Return whether two atoms compare equal according to this case sensitivity.
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
}
impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool
|
}
|
{
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
}
|
identifier_body
|
main.rs
|
extern crate mio;
extern crate rand;
mod quote_provider;
mod server;
use mio::{EventLoop,Token, Interest, PollOpt};
use mio::tcp::*;
use mio::udp::*;
use quote_provider::*;
pub const TCP_SERVER: mio::Token = mio::Token(0);
pub const UDP_SERVER: mio::Token = mio::Token(1);
#[macro_export]
macro_rules! mytry {
($e:expr) => ({
use ::std::result::Result::{Ok, Err};
match $e {
Ok(e) => e,
Err(e) => return Err(e),
}
})
}
fn
|
() {
println!("QOTD starting. Initializing quote provider.");
let quote_provider: QuoteProvider = QuoteProviderImpl::new();
println!("Sample quote: {:?}", quote_provider.get_random_quote());
println!("Binding sockets");
let address = "0.0.0.0:6567".parse().unwrap();
let tcp_server = TcpListener::bind(&address).unwrap();
let udp_server = UdpSocket::v4().unwrap();
let _ = udp_server.bind(&address);
println!("Setting up async IO");
let mut event_loop = EventLoop::new().unwrap();
let _ = event_loop.register_opt(&tcp_server, TCP_SERVER, Interest::readable(), PollOpt::edge());
let _ = event_loop.register_opt(&udp_server, UDP_SERVER, Interest::readable(), PollOpt::edge());
println!("Starting server");
let mut qotd_server = server::QotdServer
{
tcp_server: tcp_server,
udp_server: udp_server,
quote_provider: quote_provider
};
let _ = event_loop.run(&mut qotd_server);
drop(qotd_server.udp_server);
drop(qotd_server.tcp_server);
}
|
main
|
identifier_name
|
main.rs
|
extern crate mio;
extern crate rand;
mod quote_provider;
mod server;
use mio::{EventLoop,Token, Interest, PollOpt};
use mio::tcp::*;
use mio::udp::*;
use quote_provider::*;
pub const TCP_SERVER: mio::Token = mio::Token(0);
pub const UDP_SERVER: mio::Token = mio::Token(1);
#[macro_export]
macro_rules! mytry {
($e:expr) => ({
use ::std::result::Result::{Ok, Err};
match $e {
Ok(e) => e,
Err(e) => return Err(e),
}
})
}
fn main()
|
udp_server: udp_server,
quote_provider: quote_provider
};
let _ = event_loop.run(&mut qotd_server);
drop(qotd_server.udp_server);
drop(qotd_server.tcp_server);
}
|
{
println!("QOTD starting. Initializing quote provider.");
let quote_provider: QuoteProvider = QuoteProviderImpl::new();
println!("Sample quote: {:?}", quote_provider.get_random_quote());
println!("Binding sockets");
let address = "0.0.0.0:6567".parse().unwrap();
let tcp_server = TcpListener::bind(&address).unwrap();
let udp_server = UdpSocket::v4().unwrap();
let _ = udp_server.bind(&address);
println!("Setting up async IO");
let mut event_loop = EventLoop::new().unwrap();
let _ = event_loop.register_opt(&tcp_server, TCP_SERVER, Interest::readable(), PollOpt::edge());
let _ = event_loop.register_opt(&udp_server, UDP_SERVER, Interest::readable(), PollOpt::edge());
println!("Starting server");
let mut qotd_server = server::QotdServer
{
tcp_server: tcp_server,
|
identifier_body
|
main.rs
|
extern crate mio;
extern crate rand;
mod quote_provider;
mod server;
use mio::{EventLoop,Token, Interest, PollOpt};
use mio::tcp::*;
use mio::udp::*;
use quote_provider::*;
pub const TCP_SERVER: mio::Token = mio::Token(0);
pub const UDP_SERVER: mio::Token = mio::Token(1);
#[macro_export]
macro_rules! mytry {
($e:expr) => ({
use ::std::result::Result::{Ok, Err};
match $e {
Ok(e) => e,
Err(e) => return Err(e),
}
})
}
fn main() {
println!("QOTD starting. Initializing quote provider.");
let quote_provider: QuoteProvider = QuoteProviderImpl::new();
println!("Sample quote: {:?}", quote_provider.get_random_quote());
println!("Binding sockets");
let address = "0.0.0.0:6567".parse().unwrap();
let tcp_server = TcpListener::bind(&address).unwrap();
let udp_server = UdpSocket::v4().unwrap();
let _ = udp_server.bind(&address);
println!("Setting up async IO");
let mut event_loop = EventLoop::new().unwrap();
let _ = event_loop.register_opt(&tcp_server, TCP_SERVER, Interest::readable(), PollOpt::edge());
let _ = event_loop.register_opt(&udp_server, UDP_SERVER, Interest::readable(), PollOpt::edge());
println!("Starting server");
let mut qotd_server = server::QotdServer
{
tcp_server: tcp_server,
udp_server: udp_server,
quote_provider: quote_provider
};
let _ = event_loop.run(&mut qotd_server);
drop(qotd_server.udp_server);
|
drop(qotd_server.tcp_server);
}
|
random_line_split
|
|
aarch64.rs
|
//! Mask reductions implementation for `aarch64` targets
/// 128-bit wide vectors
macro_rules! aarch64_128_neon_impl {
($id:ident, $vmin:ident, $vmax:ident) => {
impl All for $id {
#[inline]
#[target_feature(enable = "neon")]
unsafe fn all(self) -> bool {
use crate::arch::aarch64::$vmin;
$vmin(crate::mem::transmute(self))!= 0
}
}
impl Any for $id {
#[inline]
#[target_feature(enable = "neon")]
unsafe fn any(self) -> bool {
use crate::arch::aarch64::$vmax;
$vmax(crate::mem::transmute(self))!= 0
}
}
}
}
/// 64-bit wide vectors
macro_rules! aarch64_64_neon_impl {
($id:ident, $vec128:ident) => {
impl All for $id {
#[inline]
#[target_feature(enable = "neon")]
|
union U {
halves: ($id, $id),
vec: $vec128,
}
U {
halves: (self, self),
}.vec.all()
}
}
impl Any for $id {
#[inline]
#[target_feature(enable = "neon")]
unsafe fn any(self) -> bool {
union U {
halves: ($id, $id),
vec: $vec128,
}
U {
halves: (self, self),
}.vec.any()
}
}
};
}
/// Mask reduction implementation for `aarch64` targets
macro_rules! impl_mask_reductions {
// 64-bit wide masks
(m8x8) => { aarch64_64_neon_impl!(m8x8, m8x16); };
(m16x4) => { aarch64_64_neon_impl!(m16x4, m16x8); };
(m32x2) => { aarch64_64_neon_impl!(m32x2, m32x4); };
// 128-bit wide masks
(m8x16) => { aarch64_128_neon_impl!(m8x16, vminvq_u8, vmaxvq_u8); };
(m16x8) => { aarch64_128_neon_impl!(m16x8, vminvq_u16, vmaxvq_u16); };
(m32x4) => { aarch64_128_neon_impl!(m32x4, vminvq_u32, vmaxvq_u32); };
// Fallback to LLVM's default code-generation:
($id:ident) => { fallback_impl!($id); };
}
|
unsafe fn all(self) -> bool {
// Duplicates the 64-bit vector into a 128-bit one and
// calls all on that.
|
random_line_split
|
level.rs
|
use std::collections::BTreeMap;
use super::machine::{Input, Output, Registers, Tile};
pub type Level = (Input, Registers, Output);
// Copy inbox to outbox
pub fn level_1() -> Level {
let input = from_numbers(&[1, 2, 3]);
let registers = BTreeMap::new();
let output = input.clone();
(input, registers, output)
}
// Copy long inbox to outbox
pub fn level_2() -> Level {
let input = from_string("initialize");
let registers = BTreeMap::new();
let output = input.clone();
(input, registers, output)
}
// Copy from tiles to outbox
pub fn level_3() -> Level {
let input = from_numbers(&[-99, -99, -99, -99]);
let mut registers = BTreeMap::new();
for (i, c) in "ujxgbe".chars().enumerate() {
registers.insert(i as u8, Tile::Letter(c));
}
let output = from_string("bug");
(input, registers, output)
}
// Swap pairs from the input
pub fn level_4() -> Level {
let input = parse_mixed("6,4,-1,7,ih");
let registers = BTreeMap::new();
let output = parse_mixed("4,6,7,-1,hi");
(input, registers, output)
}
// Copy inbox to outbox, losing duplicates
pub fn level_35() -> Level {
let input = from_string("eabedebaeb");
let mut registers = BTreeMap::new();
registers.insert(14, Tile::num(0));
let output = from_string("eabd");
(input, registers, output)
}
// Given two zero-terminated words, output the word that is first in
// alphabetical order
pub fn level_36() -> Level {
let mut input = Vec::new();
append_zero_terminated_string(&mut input, "aab");
append_zero_terminated_string(&mut input, "aaa");
let mut registers = BTreeMap::new();
registers.insert(23, Tile::num(0));
registers.insert(24, Tile::num(10));
let output = from_string("aaa");
(input, registers, output)
}
// There are pairs of letters and next pointers in the registers,
// starting at the input, follow the chain of registers until you get
// to -1. Output each letter on the way.
pub fn level_37() -> Level {
let input = from_numbers(&[0, 23]);
let mut registers = BTreeMap::new();
let z = [
(0, 'e', 13),
(3, 'c', 23),
(10, 'p', 20),
(13,'s', 3),
(20, 'e', -1),
(23, 'a', 10),
];
for &(idx, c, v) in &z {
registers.insert(idx, Tile::Letter(c));
registers.insert(idx + 1, Tile::num(v));
}
let output = from_string("escapeape");
(input, registers, output)
}
// Given numbers, output the digits of the numbers
pub fn level_38() -> Level {
let input = from_numbers(&[33, 505, 7, 979]);
let mut registers = BTreeMap::new();
registers.insert(9, Tile::num(0));
registers.insert(10, Tile::num(10));
registers.insert(11, Tile::num(100));
let output = from_numbers(&[3, 3, 5, 0, 5, 7, 9, 7, 9]);
(input, registers, output)
}
fn parse_mixed(s: &str) -> Input {
let mut input = Vec::new();
for part in s.split(",") {
match part.parse() {
Ok(n) => input.push(Tile::num(n)),
Err(..) => append_string(&mut input, part),
}
}
input
}
fn from_numbers(n: &[i16]) -> Input {
let mut input = Vec::new();
append_numbers(&mut input, n);
input
}
fn append_numbers(input: &mut Input, n: &[i16]) {
input.extend(n.iter().cloned().map(Tile::num))
}
fn from_string(s: &str) -> Input {
let mut input = Vec::new();
append_string(&mut input, s);
input
}
|
input.extend(s.chars().map(Tile::Letter));
}
fn append_zero_terminated_string(input: &mut Input, s: &str) {
append_string(input, s);
input.push(Tile::num(0));
}
|
fn append_string(input: &mut Input, s: &str) {
|
random_line_split
|
level.rs
|
use std::collections::BTreeMap;
use super::machine::{Input, Output, Registers, Tile};
pub type Level = (Input, Registers, Output);
// Copy inbox to outbox
pub fn level_1() -> Level {
let input = from_numbers(&[1, 2, 3]);
let registers = BTreeMap::new();
let output = input.clone();
(input, registers, output)
}
// Copy long inbox to outbox
pub fn level_2() -> Level {
let input = from_string("initialize");
let registers = BTreeMap::new();
let output = input.clone();
(input, registers, output)
}
// Copy from tiles to outbox
pub fn level_3() -> Level {
let input = from_numbers(&[-99, -99, -99, -99]);
let mut registers = BTreeMap::new();
for (i, c) in "ujxgbe".chars().enumerate() {
registers.insert(i as u8, Tile::Letter(c));
}
let output = from_string("bug");
(input, registers, output)
}
// Swap pairs from the input
pub fn level_4() -> Level {
let input = parse_mixed("6,4,-1,7,ih");
let registers = BTreeMap::new();
let output = parse_mixed("4,6,7,-1,hi");
(input, registers, output)
}
// Copy inbox to outbox, losing duplicates
pub fn level_35() -> Level {
let input = from_string("eabedebaeb");
let mut registers = BTreeMap::new();
registers.insert(14, Tile::num(0));
let output = from_string("eabd");
(input, registers, output)
}
// Given two zero-terminated words, output the word that is first in
// alphabetical order
pub fn level_36() -> Level {
let mut input = Vec::new();
append_zero_terminated_string(&mut input, "aab");
append_zero_terminated_string(&mut input, "aaa");
let mut registers = BTreeMap::new();
registers.insert(23, Tile::num(0));
registers.insert(24, Tile::num(10));
let output = from_string("aaa");
(input, registers, output)
}
// There are pairs of letters and next pointers in the registers,
// starting at the input, follow the chain of registers until you get
// to -1. Output each letter on the way.
pub fn level_37() -> Level {
let input = from_numbers(&[0, 23]);
let mut registers = BTreeMap::new();
let z = [
(0, 'e', 13),
(3, 'c', 23),
(10, 'p', 20),
(13,'s', 3),
(20, 'e', -1),
(23, 'a', 10),
];
for &(idx, c, v) in &z {
registers.insert(idx, Tile::Letter(c));
registers.insert(idx + 1, Tile::num(v));
}
let output = from_string("escapeape");
(input, registers, output)
}
// Given numbers, output the digits of the numbers
pub fn level_38() -> Level {
let input = from_numbers(&[33, 505, 7, 979]);
let mut registers = BTreeMap::new();
registers.insert(9, Tile::num(0));
registers.insert(10, Tile::num(10));
registers.insert(11, Tile::num(100));
let output = from_numbers(&[3, 3, 5, 0, 5, 7, 9, 7, 9]);
(input, registers, output)
}
fn parse_mixed(s: &str) -> Input {
let mut input = Vec::new();
for part in s.split(",") {
match part.parse() {
Ok(n) => input.push(Tile::num(n)),
Err(..) => append_string(&mut input, part),
}
}
input
}
fn
|
(n: &[i16]) -> Input {
let mut input = Vec::new();
append_numbers(&mut input, n);
input
}
fn append_numbers(input: &mut Input, n: &[i16]) {
input.extend(n.iter().cloned().map(Tile::num))
}
fn from_string(s: &str) -> Input {
let mut input = Vec::new();
append_string(&mut input, s);
input
}
fn append_string(input: &mut Input, s: &str) {
input.extend(s.chars().map(Tile::Letter));
}
fn append_zero_terminated_string(input: &mut Input, s: &str) {
append_string(input, s);
input.push(Tile::num(0));
}
|
from_numbers
|
identifier_name
|
level.rs
|
use std::collections::BTreeMap;
use super::machine::{Input, Output, Registers, Tile};
pub type Level = (Input, Registers, Output);
// Copy inbox to outbox
pub fn level_1() -> Level {
let input = from_numbers(&[1, 2, 3]);
let registers = BTreeMap::new();
let output = input.clone();
(input, registers, output)
}
// Copy long inbox to outbox
pub fn level_2() -> Level {
let input = from_string("initialize");
let registers = BTreeMap::new();
let output = input.clone();
(input, registers, output)
}
// Copy from tiles to outbox
pub fn level_3() -> Level {
let input = from_numbers(&[-99, -99, -99, -99]);
let mut registers = BTreeMap::new();
for (i, c) in "ujxgbe".chars().enumerate() {
registers.insert(i as u8, Tile::Letter(c));
}
let output = from_string("bug");
(input, registers, output)
}
// Swap pairs from the input
pub fn level_4() -> Level
|
// Copy inbox to outbox, losing duplicates
pub fn level_35() -> Level {
let input = from_string("eabedebaeb");
let mut registers = BTreeMap::new();
registers.insert(14, Tile::num(0));
let output = from_string("eabd");
(input, registers, output)
}
// Given two zero-terminated words, output the word that is first in
// alphabetical order
pub fn level_36() -> Level {
let mut input = Vec::new();
append_zero_terminated_string(&mut input, "aab");
append_zero_terminated_string(&mut input, "aaa");
let mut registers = BTreeMap::new();
registers.insert(23, Tile::num(0));
registers.insert(24, Tile::num(10));
let output = from_string("aaa");
(input, registers, output)
}
// There are pairs of letters and next pointers in the registers,
// starting at the input, follow the chain of registers until you get
// to -1. Output each letter on the way.
pub fn level_37() -> Level {
let input = from_numbers(&[0, 23]);
let mut registers = BTreeMap::new();
let z = [
(0, 'e', 13),
(3, 'c', 23),
(10, 'p', 20),
(13,'s', 3),
(20, 'e', -1),
(23, 'a', 10),
];
for &(idx, c, v) in &z {
registers.insert(idx, Tile::Letter(c));
registers.insert(idx + 1, Tile::num(v));
}
let output = from_string("escapeape");
(input, registers, output)
}
// Given numbers, output the digits of the numbers
pub fn level_38() -> Level {
let input = from_numbers(&[33, 505, 7, 979]);
let mut registers = BTreeMap::new();
registers.insert(9, Tile::num(0));
registers.insert(10, Tile::num(10));
registers.insert(11, Tile::num(100));
let output = from_numbers(&[3, 3, 5, 0, 5, 7, 9, 7, 9]);
(input, registers, output)
}
fn parse_mixed(s: &str) -> Input {
let mut input = Vec::new();
for part in s.split(",") {
match part.parse() {
Ok(n) => input.push(Tile::num(n)),
Err(..) => append_string(&mut input, part),
}
}
input
}
fn from_numbers(n: &[i16]) -> Input {
let mut input = Vec::new();
append_numbers(&mut input, n);
input
}
fn append_numbers(input: &mut Input, n: &[i16]) {
input.extend(n.iter().cloned().map(Tile::num))
}
fn from_string(s: &str) -> Input {
let mut input = Vec::new();
append_string(&mut input, s);
input
}
fn append_string(input: &mut Input, s: &str) {
input.extend(s.chars().map(Tile::Letter));
}
fn append_zero_terminated_string(input: &mut Input, s: &str) {
append_string(input, s);
input.push(Tile::num(0));
}
|
{
let input = parse_mixed("6,4,-1,7,ih");
let registers = BTreeMap::new();
let output = parse_mixed("4,6,7,-1,hi");
(input, registers, output)
}
|
identifier_body
|
trait-cast.rs
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test cyclic detector when using trait instances.
struct Tree(@mut TreeR);
struct TreeR {
left: Option<Tree>,
right: Option<Tree>,
val: ~to_str
}
trait to_str {
fn to_str_(&self) -> ~str;
}
impl<T:to_str> to_str for Option<T> {
fn to_str_(&self) -> ~str {
match *self {
None => { ~"none" }
Some(ref t) => { ~"some(" + t.to_str_() + ~")" }
}
}
}
impl to_str for int {
fn to_str_(&self) -> ~str { self.to_str() }
}
impl to_str for Tree {
fn to_str_(&self) -> ~str {
let (l, r) = (self.left, self.right);
let val = &self.val;
format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_())
}
}
fn foo<T:to_str>(x: T) -> ~str { x.to_str_() }
pub fn main() {
let t1 = Tree(@mut TreeR{left: None,
right: None,
val: ~1 as ~to_str });
let t2 = Tree(@mut TreeR{left: Some(t1),
right: Some(t1),
val: ~2 as ~to_str });
let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
assert!(t2.to_str_() == expected);
assert!(foo(t2) == expected);
t1.left = Some(t2); // create cycle
}
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
|
random_line_split
|
|
trait-cast.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test cyclic detector when using trait instances.
struct Tree(@mut TreeR);
struct TreeR {
left: Option<Tree>,
right: Option<Tree>,
val: ~to_str
}
trait to_str {
fn to_str_(&self) -> ~str;
}
impl<T:to_str> to_str for Option<T> {
fn to_str_(&self) -> ~str {
match *self {
None => { ~"none" }
Some(ref t) =>
|
}
}
}
impl to_str for int {
fn to_str_(&self) -> ~str { self.to_str() }
}
impl to_str for Tree {
fn to_str_(&self) -> ~str {
let (l, r) = (self.left, self.right);
let val = &self.val;
format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_())
}
}
fn foo<T:to_str>(x: T) -> ~str { x.to_str_() }
pub fn main() {
let t1 = Tree(@mut TreeR{left: None,
right: None,
val: ~1 as ~to_str });
let t2 = Tree(@mut TreeR{left: Some(t1),
right: Some(t1),
val: ~2 as ~to_str });
let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
assert!(t2.to_str_() == expected);
assert!(foo(t2) == expected);
t1.left = Some(t2); // create cycle
}
|
{ ~"some(" + t.to_str_() + ~")" }
|
conditional_block
|
trait-cast.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test cyclic detector when using trait instances.
struct Tree(@mut TreeR);
struct TreeR {
left: Option<Tree>,
right: Option<Tree>,
val: ~to_str
}
trait to_str {
fn to_str_(&self) -> ~str;
}
impl<T:to_str> to_str for Option<T> {
fn to_str_(&self) -> ~str {
match *self {
None => { ~"none" }
Some(ref t) => { ~"some(" + t.to_str_() + ~")" }
}
}
}
impl to_str for int {
fn to_str_(&self) -> ~str
|
}
impl to_str for Tree {
fn to_str_(&self) -> ~str {
let (l, r) = (self.left, self.right);
let val = &self.val;
format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_())
}
}
fn foo<T:to_str>(x: T) -> ~str { x.to_str_() }
pub fn main() {
let t1 = Tree(@mut TreeR{left: None,
right: None,
val: ~1 as ~to_str });
let t2 = Tree(@mut TreeR{left: Some(t1),
right: Some(t1),
val: ~2 as ~to_str });
let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
assert!(t2.to_str_() == expected);
assert!(foo(t2) == expected);
t1.left = Some(t2); // create cycle
}
|
{ self.to_str() }
|
identifier_body
|
trait-cast.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test cyclic detector when using trait instances.
struct
|
(@mut TreeR);
struct TreeR {
left: Option<Tree>,
right: Option<Tree>,
val: ~to_str
}
trait to_str {
fn to_str_(&self) -> ~str;
}
impl<T:to_str> to_str for Option<T> {
fn to_str_(&self) -> ~str {
match *self {
None => { ~"none" }
Some(ref t) => { ~"some(" + t.to_str_() + ~")" }
}
}
}
impl to_str for int {
fn to_str_(&self) -> ~str { self.to_str() }
}
impl to_str for Tree {
fn to_str_(&self) -> ~str {
let (l, r) = (self.left, self.right);
let val = &self.val;
format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_())
}
}
fn foo<T:to_str>(x: T) -> ~str { x.to_str_() }
pub fn main() {
let t1 = Tree(@mut TreeR{left: None,
right: None,
val: ~1 as ~to_str });
let t2 = Tree(@mut TreeR{left: Some(t1),
right: Some(t1),
val: ~2 as ~to_str });
let expected = ~"[2, some([1, none, none]), some([1, none, none])]";
assert!(t2.to_str_() == expected);
assert!(foo(t2) == expected);
t1.left = Some(t2); // create cycle
}
|
Tree
|
identifier_name
|
extern-call-deep.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
mod rustrt {
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1
|
else {
count(data - 1) + 1
}
}
fn count(n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
let result = count(1000);
println!("result = {}", result);
assert_eq!(result, 1000);
}
|
{
data
}
|
conditional_block
|
extern-call-deep.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
mod rustrt {
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1 {
data
} else {
count(data - 1) + 1
}
}
fn count(n: libc::uintptr_t) -> libc::uintptr_t
|
pub fn main() {
let result = count(1000);
println!("result = {}", result);
assert_eq!(result, 1000);
}
|
{
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
|
identifier_body
|
extern-call-deep.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
extern crate libc;
mod rustrt {
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn
|
(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1 {
data
} else {
count(data - 1) + 1
}
}
fn count(n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
let result = count(1000);
println!("result = {}", result);
assert_eq!(result, 1000);
}
|
cb
|
identifier_name
|
extern-call-deep.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
extern crate libc;
mod rustrt {
extern crate libc;
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t,
data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1 {
data
} else {
count(data - 1) + 1
}
}
fn count(n: libc::uintptr_t) -> libc::uintptr_t {
unsafe {
println!("n = {}", n);
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
let result = count(1000);
println!("result = {}", result);
assert_eq!(result, 1000);
}
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(libc)]
|
random_line_split
|
event.rs
|
//! The `event` module contains traits and structs to actually run your game mainloop
//! and handle top-level state, as well as handle input events such as keyboard
//! and mouse.
/// A key code.
pub use sdl2::keyboard::Keycode;
/// A struct that holds the state of modifier buttons such as ctrl or shift.
pub use sdl2::keyboard::Mod;
/// A mouse button press.
pub use sdl2::mouse::MouseButton;
/// A struct containing the mouse state at a given instant.
pub use sdl2::mouse::MouseState;
/// A controller button.
pub use sdl2::controller::Button;
/// A controller axis.
pub use sdl2::controller::Axis;
use sdl2::event::Event::*;
use sdl2::event;
use sdl2::mouse;
use sdl2::keyboard;
use context::Context;
use GameResult;
use timer;
|
use std::time::Duration;
/// A trait defining event callbacks; your primary interface with
/// `ggez`'s event loop. Have a type implement this trait and
/// override at least the update() and draw() methods, then pass it to
/// `event::run()` to run the game's mainloop.
///
/// The default event handlers do nothing, apart from
/// `key_down_event()`, which will by default exit the game if escape
/// is pressed. Just override the methods you want to do things with.
pub trait EventHandler {
/// Called upon each physics update to the game.
/// This should be where the game's logic takes place.
fn update(&mut self, ctx: &mut Context, dt: Duration) -> GameResult<()>;
/// Called to do the drawing of your game.
/// You probably want to start this with
/// `graphics::clear()` and end it with
/// `graphics::present()` and `timer::sleep_until_next_frame()`
fn draw(&mut self, ctx: &mut Context) -> GameResult<()>;
fn mouse_button_down_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_button_up_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_motion_event(&mut self,
_state: mouse::MouseState,
_x: i32,
_y: i32,
_xrel: i32,
_yrel: i32) {
}
fn mouse_wheel_event(&mut self, _x: i32, _y: i32) {}
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn controller_button_down_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_button_up_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_axis_event(&mut self, _axis: Axis, _value: i16, _instance_id: i32) {}
fn focus_event(&mut self, _gained: bool) {}
/// Called upon a quit event. If it returns true,
/// the game does not exit.
fn quit_event(&mut self) -> bool {
println!("Quitting game");
false
}
}
/// Runs the game's main loop, calling event callbacks on the given state
/// object as events occur.
///
/// It does not try to do any type of framerate limiting. See the
/// documentation for the `timer` module for more info.
pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()>
where S: EventHandler
{
{
let mut event_pump = ctx.sdl_context.event_pump()?;
let mut continuing = true;
while continuing {
ctx.timer_context.tick();
for event in event_pump.poll_iter() {
match event {
Quit {.. } => {
continuing = state.quit_event();
// println!("Quit event: {:?}", t);
}
KeyDown {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
if key == keyboard::Keycode::Escape {
ctx.quit()?;
} else {
state.key_down_event(key, keymod, repeat)
}
}
}
KeyUp {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
state.key_up_event(key, keymod, repeat)
}
}
MouseButtonDown { mouse_btn, x, y,.. } => {
state.mouse_button_down_event(mouse_btn, x, y)
}
MouseButtonUp { mouse_btn, x, y,.. } => {
state.mouse_button_up_event(mouse_btn, x, y)
}
MouseMotion {
mousestate,
x,
y,
xrel,
yrel,
..
} => state.mouse_motion_event(mousestate, x, y, xrel, yrel),
MouseWheel { x, y,.. } => state.mouse_wheel_event(x, y),
ControllerButtonDown { button, which,.. } => {
state.controller_button_down_event(button, which)
}
ControllerButtonUp { button, which,.. } =>
state.controller_button_up_event(button, which),
ControllerAxisMotion { axis, value, which,.. } => {
state.controller_axis_event(axis, value, which)
}
Window { win_event: event::WindowEvent::FocusGained,.. } => {
state.focus_event(true)
}
Window { win_event: event::WindowEvent::FocusLost,.. } => {
state.focus_event(false)
}
_ => {}
}
}
let dt = timer::get_delta(ctx);
state.update(ctx, dt)?;
state.draw(ctx)?;
}
}
Ok(())
}
|
random_line_split
|
|
event.rs
|
//! The `event` module contains traits and structs to actually run your game mainloop
//! and handle top-level state, as well as handle input events such as keyboard
//! and mouse.
/// A key code.
pub use sdl2::keyboard::Keycode;
/// A struct that holds the state of modifier buttons such as ctrl or shift.
pub use sdl2::keyboard::Mod;
/// A mouse button press.
pub use sdl2::mouse::MouseButton;
/// A struct containing the mouse state at a given instant.
pub use sdl2::mouse::MouseState;
/// A controller button.
pub use sdl2::controller::Button;
/// A controller axis.
pub use sdl2::controller::Axis;
use sdl2::event::Event::*;
use sdl2::event;
use sdl2::mouse;
use sdl2::keyboard;
use context::Context;
use GameResult;
use timer;
use std::time::Duration;
/// A trait defining event callbacks; your primary interface with
/// `ggez`'s event loop. Have a type implement this trait and
/// override at least the update() and draw() methods, then pass it to
/// `event::run()` to run the game's mainloop.
///
/// The default event handlers do nothing, apart from
/// `key_down_event()`, which will by default exit the game if escape
/// is pressed. Just override the methods you want to do things with.
pub trait EventHandler {
/// Called upon each physics update to the game.
/// This should be where the game's logic takes place.
fn update(&mut self, ctx: &mut Context, dt: Duration) -> GameResult<()>;
/// Called to do the drawing of your game.
/// You probably want to start this with
/// `graphics::clear()` and end it with
/// `graphics::present()` and `timer::sleep_until_next_frame()`
fn draw(&mut self, ctx: &mut Context) -> GameResult<()>;
fn mouse_button_down_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_button_up_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_motion_event(&mut self,
_state: mouse::MouseState,
_x: i32,
_y: i32,
_xrel: i32,
_yrel: i32) {
}
fn mouse_wheel_event(&mut self, _x: i32, _y: i32) {}
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn controller_button_down_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_button_up_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_axis_event(&mut self, _axis: Axis, _value: i16, _instance_id: i32) {}
fn focus_event(&mut self, _gained: bool) {}
/// Called upon a quit event. If it returns true,
/// the game does not exit.
fn quit_event(&mut self) -> bool
|
}
/// Runs the game's main loop, calling event callbacks on the given state
/// object as events occur.
///
/// It does not try to do any type of framerate limiting. See the
/// documentation for the `timer` module for more info.
pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()>
where S: EventHandler
{
{
let mut event_pump = ctx.sdl_context.event_pump()?;
let mut continuing = true;
while continuing {
ctx.timer_context.tick();
for event in event_pump.poll_iter() {
match event {
Quit {.. } => {
continuing = state.quit_event();
// println!("Quit event: {:?}", t);
}
KeyDown {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
if key == keyboard::Keycode::Escape {
ctx.quit()?;
} else {
state.key_down_event(key, keymod, repeat)
}
}
}
KeyUp {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
state.key_up_event(key, keymod, repeat)
}
}
MouseButtonDown { mouse_btn, x, y,.. } => {
state.mouse_button_down_event(mouse_btn, x, y)
}
MouseButtonUp { mouse_btn, x, y,.. } => {
state.mouse_button_up_event(mouse_btn, x, y)
}
MouseMotion {
mousestate,
x,
y,
xrel,
yrel,
..
} => state.mouse_motion_event(mousestate, x, y, xrel, yrel),
MouseWheel { x, y,.. } => state.mouse_wheel_event(x, y),
ControllerButtonDown { button, which,.. } => {
state.controller_button_down_event(button, which)
}
ControllerButtonUp { button, which,.. } =>
state.controller_button_up_event(button, which),
ControllerAxisMotion { axis, value, which,.. } => {
state.controller_axis_event(axis, value, which)
}
Window { win_event: event::WindowEvent::FocusGained,.. } => {
state.focus_event(true)
}
Window { win_event: event::WindowEvent::FocusLost,.. } => {
state.focus_event(false)
}
_ => {}
}
}
let dt = timer::get_delta(ctx);
state.update(ctx, dt)?;
state.draw(ctx)?;
}
}
Ok(())
}
|
{
println!("Quitting game");
false
}
|
identifier_body
|
event.rs
|
//! The `event` module contains traits and structs to actually run your game mainloop
//! and handle top-level state, as well as handle input events such as keyboard
//! and mouse.
/// A key code.
pub use sdl2::keyboard::Keycode;
/// A struct that holds the state of modifier buttons such as ctrl or shift.
pub use sdl2::keyboard::Mod;
/// A mouse button press.
pub use sdl2::mouse::MouseButton;
/// A struct containing the mouse state at a given instant.
pub use sdl2::mouse::MouseState;
/// A controller button.
pub use sdl2::controller::Button;
/// A controller axis.
pub use sdl2::controller::Axis;
use sdl2::event::Event::*;
use sdl2::event;
use sdl2::mouse;
use sdl2::keyboard;
use context::Context;
use GameResult;
use timer;
use std::time::Duration;
/// A trait defining event callbacks; your primary interface with
/// `ggez`'s event loop. Have a type implement this trait and
/// override at least the update() and draw() methods, then pass it to
/// `event::run()` to run the game's mainloop.
///
/// The default event handlers do nothing, apart from
/// `key_down_event()`, which will by default exit the game if escape
/// is pressed. Just override the methods you want to do things with.
pub trait EventHandler {
/// Called upon each physics update to the game.
/// This should be where the game's logic takes place.
fn update(&mut self, ctx: &mut Context, dt: Duration) -> GameResult<()>;
/// Called to do the drawing of your game.
/// You probably want to start this with
/// `graphics::clear()` and end it with
/// `graphics::present()` and `timer::sleep_until_next_frame()`
fn draw(&mut self, ctx: &mut Context) -> GameResult<()>;
fn mouse_button_down_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_button_up_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_motion_event(&mut self,
_state: mouse::MouseState,
_x: i32,
_y: i32,
_xrel: i32,
_yrel: i32) {
}
fn mouse_wheel_event(&mut self, _x: i32, _y: i32) {}
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn controller_button_down_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_button_up_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_axis_event(&mut self, _axis: Axis, _value: i16, _instance_id: i32) {}
fn focus_event(&mut self, _gained: bool) {}
/// Called upon a quit event. If it returns true,
/// the game does not exit.
fn quit_event(&mut self) -> bool {
println!("Quitting game");
false
}
}
/// Runs the game's main loop, calling event callbacks on the given state
/// object as events occur.
///
/// It does not try to do any type of framerate limiting. See the
/// documentation for the `timer` module for more info.
pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()>
where S: EventHandler
{
{
let mut event_pump = ctx.sdl_context.event_pump()?;
let mut continuing = true;
while continuing {
ctx.timer_context.tick();
for event in event_pump.poll_iter() {
match event {
Quit {.. } => {
continuing = state.quit_event();
// println!("Quit event: {:?}", t);
}
KeyDown {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
if key == keyboard::Keycode::Escape {
ctx.quit()?;
} else {
state.key_down_event(key, keymod, repeat)
}
}
}
KeyUp {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
state.key_up_event(key, keymod, repeat)
}
}
MouseButtonDown { mouse_btn, x, y,.. } => {
state.mouse_button_down_event(mouse_btn, x, y)
}
MouseButtonUp { mouse_btn, x, y,.. } =>
|
MouseMotion {
mousestate,
x,
y,
xrel,
yrel,
..
} => state.mouse_motion_event(mousestate, x, y, xrel, yrel),
MouseWheel { x, y,.. } => state.mouse_wheel_event(x, y),
ControllerButtonDown { button, which,.. } => {
state.controller_button_down_event(button, which)
}
ControllerButtonUp { button, which,.. } =>
state.controller_button_up_event(button, which),
ControllerAxisMotion { axis, value, which,.. } => {
state.controller_axis_event(axis, value, which)
}
Window { win_event: event::WindowEvent::FocusGained,.. } => {
state.focus_event(true)
}
Window { win_event: event::WindowEvent::FocusLost,.. } => {
state.focus_event(false)
}
_ => {}
}
}
let dt = timer::get_delta(ctx);
state.update(ctx, dt)?;
state.draw(ctx)?;
}
}
Ok(())
}
|
{
state.mouse_button_up_event(mouse_btn, x, y)
}
|
conditional_block
|
event.rs
|
//! The `event` module contains traits and structs to actually run your game mainloop
//! and handle top-level state, as well as handle input events such as keyboard
//! and mouse.
/// A key code.
pub use sdl2::keyboard::Keycode;
/// A struct that holds the state of modifier buttons such as ctrl or shift.
pub use sdl2::keyboard::Mod;
/// A mouse button press.
pub use sdl2::mouse::MouseButton;
/// A struct containing the mouse state at a given instant.
pub use sdl2::mouse::MouseState;
/// A controller button.
pub use sdl2::controller::Button;
/// A controller axis.
pub use sdl2::controller::Axis;
use sdl2::event::Event::*;
use sdl2::event;
use sdl2::mouse;
use sdl2::keyboard;
use context::Context;
use GameResult;
use timer;
use std::time::Duration;
/// A trait defining event callbacks; your primary interface with
/// `ggez`'s event loop. Have a type implement this trait and
/// override at least the update() and draw() methods, then pass it to
/// `event::run()` to run the game's mainloop.
///
/// The default event handlers do nothing, apart from
/// `key_down_event()`, which will by default exit the game if escape
/// is pressed. Just override the methods you want to do things with.
pub trait EventHandler {
/// Called upon each physics update to the game.
/// This should be where the game's logic takes place.
fn update(&mut self, ctx: &mut Context, dt: Duration) -> GameResult<()>;
/// Called to do the drawing of your game.
/// You probably want to start this with
/// `graphics::clear()` and end it with
/// `graphics::present()` and `timer::sleep_until_next_frame()`
fn draw(&mut self, ctx: &mut Context) -> GameResult<()>;
fn mouse_button_down_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_button_up_event(&mut self, _button: mouse::MouseButton, _x: i32, _y: i32) {}
fn mouse_motion_event(&mut self,
_state: mouse::MouseState,
_x: i32,
_y: i32,
_xrel: i32,
_yrel: i32) {
}
fn mouse_wheel_event(&mut self, _x: i32, _y: i32) {}
fn key_down_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn key_up_event(&mut self, _keycode: Keycode, _keymod: Mod, _repeat: bool) {}
fn controller_button_down_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_button_up_event(&mut self, _btn: Button, _instance_id: i32) {}
fn controller_axis_event(&mut self, _axis: Axis, _value: i16, _instance_id: i32) {}
fn
|
(&mut self, _gained: bool) {}
/// Called upon a quit event. If it returns true,
/// the game does not exit.
fn quit_event(&mut self) -> bool {
println!("Quitting game");
false
}
}
/// Runs the game's main loop, calling event callbacks on the given state
/// object as events occur.
///
/// It does not try to do any type of framerate limiting. See the
/// documentation for the `timer` module for more info.
pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()>
where S: EventHandler
{
{
let mut event_pump = ctx.sdl_context.event_pump()?;
let mut continuing = true;
while continuing {
ctx.timer_context.tick();
for event in event_pump.poll_iter() {
match event {
Quit {.. } => {
continuing = state.quit_event();
// println!("Quit event: {:?}", t);
}
KeyDown {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
if key == keyboard::Keycode::Escape {
ctx.quit()?;
} else {
state.key_down_event(key, keymod, repeat)
}
}
}
KeyUp {
keycode,
keymod,
repeat,
..
} => {
if let Some(key) = keycode {
state.key_up_event(key, keymod, repeat)
}
}
MouseButtonDown { mouse_btn, x, y,.. } => {
state.mouse_button_down_event(mouse_btn, x, y)
}
MouseButtonUp { mouse_btn, x, y,.. } => {
state.mouse_button_up_event(mouse_btn, x, y)
}
MouseMotion {
mousestate,
x,
y,
xrel,
yrel,
..
} => state.mouse_motion_event(mousestate, x, y, xrel, yrel),
MouseWheel { x, y,.. } => state.mouse_wheel_event(x, y),
ControllerButtonDown { button, which,.. } => {
state.controller_button_down_event(button, which)
}
ControllerButtonUp { button, which,.. } =>
state.controller_button_up_event(button, which),
ControllerAxisMotion { axis, value, which,.. } => {
state.controller_axis_event(axis, value, which)
}
Window { win_event: event::WindowEvent::FocusGained,.. } => {
state.focus_event(true)
}
Window { win_event: event::WindowEvent::FocusLost,.. } => {
state.focus_event(false)
}
_ => {}
}
}
let dt = timer::get_delta(ctx);
state.update(ctx, dt)?;
state.draw(ctx)?;
}
}
Ok(())
}
|
focus_event
|
identifier_name
|
unify.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{Bounds, uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use std::mem;
use syntax::ast;
use util::ppaux::Repr;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `TyVid`, which represents normal
* type variables, and `IntVid`, which represents integral variables.
*
* Each key type has an associated value type `V`. For example,
* for `TyVid`, this is `Bounds<ty::t>`, representing a pair of
* upper- and lower-bound types.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note
* that this is typically not the end type that the value will
* take on, but rather some wrapper: for example, for normal type
* variables, the associated type is not `ty::t` but rather
* `Bounds<ty::t>`.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: Vec<VarValue<K,V>>,
/**
* When a snapshot is active, logs each change made to the table
* so that they can be unrolled.
*/
undo_log: Vec<UndoLog<K,V>>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *commited* or *rolled back*.
*/
pub struct Snapshot<K> {
// Ensure that this snapshot is keyed to the table type.
marker1: marker::CovariantType<K>,
// Snapshots are tokens that should be created/consumed linearly.
marker2: marker::NoCopy,
// Length of the undo log at the time the snapshot was taken.
length: uint,
}
#[deriving(PartialEq)]
enum UndoLog<K,V> {
/// Indicates where a snapshot started.
OpenSnapshot,
/// Indicates a snapshot that has been committed.
CommittedSnapshot,
/// New variable with given index was created.
NewVar(uint),
/// Variable with given index was changed *from* the given value.
SetVar(uint, VarValue<K,V>),
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Bounds<U> for some
// other type parameter U, and we have no way to say
// Bounds<U>:
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: Vec::new(),
undo_log: Vec::new()
}
}
pub fn in_snapshot(&self) -> bool {
/*! True if a snapshot has been started. */
self.undo_log.len() > 0
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or commited in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
let length = self.undo_log.len();
debug!("{}: snapshot at length {}",
UnifyKey::tag(None::<K>),
length);
self.undo_log.push(OpenSnapshot);
Snapshot { length: length,
marker1: marker::CovariantType,
marker2: marker::NoCopy }
}
fn assert_open_snapshot(&self, snapshot: &Snapshot<K>) {
// Or else there was a failure to follow a stack discipline:
assert!(self.undo_log.len() > snapshot.length);
// Invariant established by start_snapshot():
assert!(*self.undo_log.get(snapshot.length) == OpenSnapshot);
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, tcx: &ty::ctxt, snapshot: Snapshot<K>) {
debug!("{}: rollback_to({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
while self.undo_log.len() > snapshot.length + 1 {
match self.undo_log.pop().unwrap() {
OpenSnapshot => {
// This indicates a failure to obey the stack discipline.
tcx.sess.bug("Cannot rollback an uncommited snapshot");
}
CommittedSnapshot => {
// This occurs when there are nested snapshots and
// the inner is commited but outer is rolled back.
}
NewVar(i) => {
assert!(self.values.len() == i);
self.values.pop();
}
SetVar(i, v) => {
*self.values.get_mut(i) = v;
}
}
}
let v = self.undo_log.pop().unwrap();
assert!(v == OpenSnapshot);
assert!(self.undo_log.len() == snapshot.length);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
if snapshot.length == 0 {
// The root snapshot.
self.undo_log.truncate(0);
} else {
*self.undo_log.get_mut(snapshot.length) = CommittedSnapshot;
}
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.len();
if self.in_snapshot() {
self.undo_log.push(NewVar(index));
}
self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
fn swap_value(&mut self,
index: uint,
new_value: VarValue<K,V>)
-> VarValue<K,V>
{
/*!
* Primitive operation to swap a value in the var array.
* Caller should update the undo log if we are in a snapshot.
*/
let loc = self.values.get_mut(index);
mem::replace(loc, new_value)
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
let old_value =
self.swap_value(index, Redirect(node.key.clone()));
// If we are in a snapshot, record this compression,
// because it's possible that the unification which
// caused it will be rolled back later.
if self.in_snapshot() {
self.undo_log.push(SetVar(index, old_value));
}
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
assert!(self.in_snapshot());
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
let index = key.index();
let old_value = self.swap_value(index, new_value);
self.undo_log.push(SetVar(index, old_value));
}
pub fn unify(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool,
a_t: V,
b_t: V) -> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) =>
|
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
{
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => {
if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// General type keys
impl UnifyKey<Bounds<ty::t>> for ty::TyVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::TyVid { ty::TyVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::TyVid, Bounds<ty::t>>>
{
return &infcx.type_unification_table;
}
fn tag(_: Option<ty::TyVid>) -> &'static str {
"TyVid"
}
}
impl UnifyValue for Bounds<ty::t> { }
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
|
{
Some((*v).clone())
}
|
conditional_block
|
unify.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{Bounds, uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use std::mem;
use syntax::ast;
use util::ppaux::Repr;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `TyVid`, which represents normal
* type variables, and `IntVid`, which represents integral variables.
*
* Each key type has an associated value type `V`. For example,
* for `TyVid`, this is `Bounds<ty::t>`, representing a pair of
* upper- and lower-bound types.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note
* that this is typically not the end type that the value will
* take on, but rather some wrapper: for example, for normal type
* variables, the associated type is not `ty::t` but rather
|
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: Vec<VarValue<K,V>>,
/**
* When a snapshot is active, logs each change made to the table
* so that they can be unrolled.
*/
undo_log: Vec<UndoLog<K,V>>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *commited* or *rolled back*.
*/
pub struct Snapshot<K> {
// Ensure that this snapshot is keyed to the table type.
marker1: marker::CovariantType<K>,
// Snapshots are tokens that should be created/consumed linearly.
marker2: marker::NoCopy,
// Length of the undo log at the time the snapshot was taken.
length: uint,
}
#[deriving(PartialEq)]
enum UndoLog<K,V> {
/// Indicates where a snapshot started.
OpenSnapshot,
/// Indicates a snapshot that has been committed.
CommittedSnapshot,
/// New variable with given index was created.
NewVar(uint),
/// Variable with given index was changed *from* the given value.
SetVar(uint, VarValue<K,V>),
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Bounds<U> for some
// other type parameter U, and we have no way to say
// Bounds<U>:
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: Vec::new(),
undo_log: Vec::new()
}
}
pub fn in_snapshot(&self) -> bool {
/*! True if a snapshot has been started. */
self.undo_log.len() > 0
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or commited in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
let length = self.undo_log.len();
debug!("{}: snapshot at length {}",
UnifyKey::tag(None::<K>),
length);
self.undo_log.push(OpenSnapshot);
Snapshot { length: length,
marker1: marker::CovariantType,
marker2: marker::NoCopy }
}
fn assert_open_snapshot(&self, snapshot: &Snapshot<K>) {
// Or else there was a failure to follow a stack discipline:
assert!(self.undo_log.len() > snapshot.length);
// Invariant established by start_snapshot():
assert!(*self.undo_log.get(snapshot.length) == OpenSnapshot);
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, tcx: &ty::ctxt, snapshot: Snapshot<K>) {
debug!("{}: rollback_to({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
while self.undo_log.len() > snapshot.length + 1 {
match self.undo_log.pop().unwrap() {
OpenSnapshot => {
// This indicates a failure to obey the stack discipline.
tcx.sess.bug("Cannot rollback an uncommited snapshot");
}
CommittedSnapshot => {
// This occurs when there are nested snapshots and
// the inner is commited but outer is rolled back.
}
NewVar(i) => {
assert!(self.values.len() == i);
self.values.pop();
}
SetVar(i, v) => {
*self.values.get_mut(i) = v;
}
}
}
let v = self.undo_log.pop().unwrap();
assert!(v == OpenSnapshot);
assert!(self.undo_log.len() == snapshot.length);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
if snapshot.length == 0 {
// The root snapshot.
self.undo_log.truncate(0);
} else {
*self.undo_log.get_mut(snapshot.length) = CommittedSnapshot;
}
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.len();
if self.in_snapshot() {
self.undo_log.push(NewVar(index));
}
self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
fn swap_value(&mut self,
index: uint,
new_value: VarValue<K,V>)
-> VarValue<K,V>
{
/*!
* Primitive operation to swap a value in the var array.
* Caller should update the undo log if we are in a snapshot.
*/
let loc = self.values.get_mut(index);
mem::replace(loc, new_value)
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
let old_value =
self.swap_value(index, Redirect(node.key.clone()));
// If we are in a snapshot, record this compression,
// because it's possible that the unification which
// caused it will be rolled back later.
if self.in_snapshot() {
self.undo_log.push(SetVar(index, old_value));
}
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
assert!(self.in_snapshot());
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
let index = key.index();
let old_value = self.swap_value(index, new_value);
self.undo_log.push(SetVar(index, old_value));
}
pub fn unify(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool,
a_t: V,
b_t: V) -> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) => {
Some((*v).clone())
}
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
{
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => {
if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// General type keys
impl UnifyKey<Bounds<ty::t>> for ty::TyVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::TyVid { ty::TyVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::TyVid, Bounds<ty::t>>>
{
return &infcx.type_unification_table;
}
fn tag(_: Option<ty::TyVid>) -> &'static str {
"TyVid"
}
}
impl UnifyValue for Bounds<ty::t> { }
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
|
* `Bounds<ty::t>`.
|
random_line_split
|
unify.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{Bounds, uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use std::mem;
use syntax::ast;
use util::ppaux::Repr;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `TyVid`, which represents normal
* type variables, and `IntVid`, which represents integral variables.
*
* Each key type has an associated value type `V`. For example,
* for `TyVid`, this is `Bounds<ty::t>`, representing a pair of
* upper- and lower-bound types.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note
* that this is typically not the end type that the value will
* take on, but rather some wrapper: for example, for normal type
* variables, the associated type is not `ty::t` but rather
* `Bounds<ty::t>`.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: Vec<VarValue<K,V>>,
/**
* When a snapshot is active, logs each change made to the table
* so that they can be unrolled.
*/
undo_log: Vec<UndoLog<K,V>>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *commited* or *rolled back*.
*/
pub struct Snapshot<K> {
// Ensure that this snapshot is keyed to the table type.
marker1: marker::CovariantType<K>,
// Snapshots are tokens that should be created/consumed linearly.
marker2: marker::NoCopy,
// Length of the undo log at the time the snapshot was taken.
length: uint,
}
#[deriving(PartialEq)]
enum UndoLog<K,V> {
/// Indicates where a snapshot started.
OpenSnapshot,
/// Indicates a snapshot that has been committed.
CommittedSnapshot,
/// New variable with given index was created.
NewVar(uint),
/// Variable with given index was changed *from* the given value.
SetVar(uint, VarValue<K,V>),
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Bounds<U> for some
// other type parameter U, and we have no way to say
// Bounds<U>:
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: Vec::new(),
undo_log: Vec::new()
}
}
pub fn in_snapshot(&self) -> bool {
/*! True if a snapshot has been started. */
self.undo_log.len() > 0
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or commited in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
let length = self.undo_log.len();
debug!("{}: snapshot at length {}",
UnifyKey::tag(None::<K>),
length);
self.undo_log.push(OpenSnapshot);
Snapshot { length: length,
marker1: marker::CovariantType,
marker2: marker::NoCopy }
}
fn assert_open_snapshot(&self, snapshot: &Snapshot<K>) {
// Or else there was a failure to follow a stack discipline:
assert!(self.undo_log.len() > snapshot.length);
// Invariant established by start_snapshot():
assert!(*self.undo_log.get(snapshot.length) == OpenSnapshot);
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, tcx: &ty::ctxt, snapshot: Snapshot<K>) {
debug!("{}: rollback_to({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
while self.undo_log.len() > snapshot.length + 1 {
match self.undo_log.pop().unwrap() {
OpenSnapshot => {
// This indicates a failure to obey the stack discipline.
tcx.sess.bug("Cannot rollback an uncommited snapshot");
}
CommittedSnapshot => {
// This occurs when there are nested snapshots and
// the inner is commited but outer is rolled back.
}
NewVar(i) => {
assert!(self.values.len() == i);
self.values.pop();
}
SetVar(i, v) => {
*self.values.get_mut(i) = v;
}
}
}
let v = self.undo_log.pop().unwrap();
assert!(v == OpenSnapshot);
assert!(self.undo_log.len() == snapshot.length);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
if snapshot.length == 0 {
// The root snapshot.
self.undo_log.truncate(0);
} else {
*self.undo_log.get_mut(snapshot.length) = CommittedSnapshot;
}
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.len();
if self.in_snapshot() {
self.undo_log.push(NewVar(index));
}
self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
fn swap_value(&mut self,
index: uint,
new_value: VarValue<K,V>)
-> VarValue<K,V>
{
/*!
* Primitive operation to swap a value in the var array.
* Caller should update the undo log if we are in a snapshot.
*/
let loc = self.values.get_mut(index);
mem::replace(loc, new_value)
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
let old_value =
self.swap_value(index, Redirect(node.key.clone()));
// If we are in a snapshot, record this compression,
// because it's possible that the unification which
// caused it will be rolled back later.
if self.in_snapshot() {
self.undo_log.push(SetVar(index, old_value));
}
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
|
pub fn unify(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool,
a_t: V,
b_t: V) -> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) => {
Some((*v).clone())
}
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
{
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => {
if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// General type keys
impl UnifyKey<Bounds<ty::t>> for ty::TyVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::TyVid { ty::TyVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::TyVid, Bounds<ty::t>>>
{
return &infcx.type_unification_table;
}
fn tag(_: Option<ty::TyVid>) -> &'static str {
"TyVid"
}
}
impl UnifyValue for Bounds<ty::t> { }
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
|
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
assert!(self.in_snapshot());
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
let index = key.index();
let old_value = self.swap_value(index, new_value);
self.undo_log.push(SetVar(index, old_value));
}
|
identifier_body
|
unify.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{Bounds, uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use std::mem;
use syntax::ast;
use util::ppaux::Repr;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `TyVid`, which represents normal
* type variables, and `IntVid`, which represents integral variables.
*
* Each key type has an associated value type `V`. For example,
* for `TyVid`, this is `Bounds<ty::t>`, representing a pair of
* upper- and lower-bound types.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note
* that this is typically not the end type that the value will
* take on, but rather some wrapper: for example, for normal type
* variables, the associated type is not `ty::t` but rather
* `Bounds<ty::t>`.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: Vec<VarValue<K,V>>,
/**
* When a snapshot is active, logs each change made to the table
* so that they can be unrolled.
*/
undo_log: Vec<UndoLog<K,V>>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *commited* or *rolled back*.
*/
pub struct Snapshot<K> {
// Ensure that this snapshot is keyed to the table type.
marker1: marker::CovariantType<K>,
// Snapshots are tokens that should be created/consumed linearly.
marker2: marker::NoCopy,
// Length of the undo log at the time the snapshot was taken.
length: uint,
}
#[deriving(PartialEq)]
enum UndoLog<K,V> {
/// Indicates where a snapshot started.
OpenSnapshot,
/// Indicates a snapshot that has been committed.
CommittedSnapshot,
/// New variable with given index was created.
NewVar(uint),
/// Variable with given index was changed *from* the given value.
SetVar(uint, VarValue<K,V>),
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Bounds<U> for some
// other type parameter U, and we have no way to say
// Bounds<U>:
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: Vec::new(),
undo_log: Vec::new()
}
}
pub fn in_snapshot(&self) -> bool {
/*! True if a snapshot has been started. */
self.undo_log.len() > 0
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or commited in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
let length = self.undo_log.len();
debug!("{}: snapshot at length {}",
UnifyKey::tag(None::<K>),
length);
self.undo_log.push(OpenSnapshot);
Snapshot { length: length,
marker1: marker::CovariantType,
marker2: marker::NoCopy }
}
fn assert_open_snapshot(&self, snapshot: &Snapshot<K>) {
// Or else there was a failure to follow a stack discipline:
assert!(self.undo_log.len() > snapshot.length);
// Invariant established by start_snapshot():
assert!(*self.undo_log.get(snapshot.length) == OpenSnapshot);
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, tcx: &ty::ctxt, snapshot: Snapshot<K>) {
debug!("{}: rollback_to({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
while self.undo_log.len() > snapshot.length + 1 {
match self.undo_log.pop().unwrap() {
OpenSnapshot => {
// This indicates a failure to obey the stack discipline.
tcx.sess.bug("Cannot rollback an uncommited snapshot");
}
CommittedSnapshot => {
// This occurs when there are nested snapshots and
// the inner is commited but outer is rolled back.
}
NewVar(i) => {
assert!(self.values.len() == i);
self.values.pop();
}
SetVar(i, v) => {
*self.values.get_mut(i) = v;
}
}
}
let v = self.undo_log.pop().unwrap();
assert!(v == OpenSnapshot);
assert!(self.undo_log.len() == snapshot.length);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit({})",
UnifyKey::tag(None::<K>),
snapshot.length);
self.assert_open_snapshot(&snapshot);
if snapshot.length == 0 {
// The root snapshot.
self.undo_log.truncate(0);
} else {
*self.undo_log.get_mut(snapshot.length) = CommittedSnapshot;
}
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.len();
if self.in_snapshot() {
self.undo_log.push(NewVar(index));
}
self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
fn swap_value(&mut self,
index: uint,
new_value: VarValue<K,V>)
-> VarValue<K,V>
{
/*!
* Primitive operation to swap a value in the var array.
* Caller should update the undo log if we are in a snapshot.
*/
let loc = self.values.get_mut(index);
mem::replace(loc, new_value)
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
let old_value =
self.swap_value(index, Redirect(node.key.clone()));
// If we are in a snapshot, record this compression,
// because it's possible that the unification which
// caused it will be rolled back later.
if self.in_snapshot() {
self.undo_log.push(SetVar(index, old_value));
}
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
assert!(self.in_snapshot());
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
let index = key.index();
let old_value = self.swap_value(index, new_value);
self.undo_log.push(SetVar(index, old_value));
}
pub fn
|
(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool,
a_t: V,
b_t: V) -> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) => {
Some((*v).clone())
}
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
{
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => {
if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// General type keys
impl UnifyKey<Bounds<ty::t>> for ty::TyVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::TyVid { ty::TyVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::TyVid, Bounds<ty::t>>>
{
return &infcx.type_unification_table;
}
fn tag(_: Option<ty::TyVid>) -> &'static str {
"TyVid"
}
}
impl UnifyValue for Bounds<ty::t> { }
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
|
unify
|
identifier_name
|
lib.rs
|
extern crate phf;
extern crate unicase;
#[cfg(test)]
mod test {
use unicase::Ascii;
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
#[test]
fn map() {
assert_eq!("a", MAP[&1]);
assert_eq!("b", MAP[&2]);
assert_eq!("c", MAP[&3]);
assert!(!MAP.contains_key(&100));
}
#[test]
fn set()
|
#[test]
fn ordered_map() {
assert_eq!("a", ORDERED_MAP[&1]);
assert_eq!("b", ORDERED_MAP[&2]);
assert_eq!("c", ORDERED_MAP[&3]);
assert!(!ORDERED_MAP.contains_key(&100));
assert_eq!(&["a", "b", "c"][..], &ORDERED_MAP.values().cloned().collect::<Vec<_>>()[..]);
}
#[test]
fn ordered_set() {
assert!(ORDERED_SET.contains(&1));
assert!(ORDERED_SET.contains(&2));
assert!(ORDERED_SET.contains(&3));
assert!(!ORDERED_SET.contains(&4));
assert_eq!(&[1, 2, 3][..], &ORDERED_SET.iter().cloned().collect::<Vec<_>>()[..]);
}
#[test]
fn str_keys() {
assert_eq!(1, STR_KEYS["a"]);
assert_eq!(2, STR_KEYS["b"]);
assert_eq!(3, STR_KEYS["c"]);
}
#[test]
fn unicase_map() {
assert_eq!("a", UNICASE_MAP[&Ascii::new("AbC")]);
assert_eq!("a", UNICASE_MAP[&Ascii::new("abc")]);
assert_eq!("b", UNICASE_MAP[&Ascii::new("DEf")]);
assert!(!UNICASE_MAP.contains_key(&Ascii::new("XyZ")));
}
}
|
{
assert!(SET.contains(&1));
assert!(SET.contains(&2));
assert!(SET.contains(&3));
assert!(!SET.contains(&4));
}
|
identifier_body
|
lib.rs
|
extern crate phf;
extern crate unicase;
#[cfg(test)]
mod test {
use unicase::Ascii;
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
#[test]
fn map() {
assert_eq!("a", MAP[&1]);
assert_eq!("b", MAP[&2]);
assert_eq!("c", MAP[&3]);
assert!(!MAP.contains_key(&100));
}
#[test]
fn set() {
assert!(SET.contains(&1));
assert!(SET.contains(&2));
assert!(SET.contains(&3));
assert!(!SET.contains(&4));
}
#[test]
fn ordered_map() {
assert_eq!("a", ORDERED_MAP[&1]);
assert_eq!("b", ORDERED_MAP[&2]);
assert_eq!("c", ORDERED_MAP[&3]);
assert!(!ORDERED_MAP.contains_key(&100));
assert_eq!(&["a", "b", "c"][..], &ORDERED_MAP.values().cloned().collect::<Vec<_>>()[..]);
}
#[test]
fn ordered_set() {
assert!(ORDERED_SET.contains(&1));
assert!(ORDERED_SET.contains(&2));
assert!(ORDERED_SET.contains(&3));
assert!(!ORDERED_SET.contains(&4));
assert_eq!(&[1, 2, 3][..], &ORDERED_SET.iter().cloned().collect::<Vec<_>>()[..]);
}
#[test]
fn str_keys() {
assert_eq!(1, STR_KEYS["a"]);
assert_eq!(2, STR_KEYS["b"]);
assert_eq!(3, STR_KEYS["c"]);
}
#[test]
fn unicase_map() {
assert_eq!("a", UNICASE_MAP[&Ascii::new("AbC")]);
assert_eq!("a", UNICASE_MAP[&Ascii::new("abc")]);
|
assert!(!UNICASE_MAP.contains_key(&Ascii::new("XyZ")));
}
}
|
assert_eq!("b", UNICASE_MAP[&Ascii::new("DEf")]);
|
random_line_split
|
lib.rs
|
extern crate phf;
extern crate unicase;
#[cfg(test)]
mod test {
use unicase::Ascii;
include!(concat!(env!("OUT_DIR"), "/codegen.rs"));
#[test]
fn
|
() {
assert_eq!("a", MAP[&1]);
assert_eq!("b", MAP[&2]);
assert_eq!("c", MAP[&3]);
assert!(!MAP.contains_key(&100));
}
#[test]
fn set() {
assert!(SET.contains(&1));
assert!(SET.contains(&2));
assert!(SET.contains(&3));
assert!(!SET.contains(&4));
}
#[test]
fn ordered_map() {
assert_eq!("a", ORDERED_MAP[&1]);
assert_eq!("b", ORDERED_MAP[&2]);
assert_eq!("c", ORDERED_MAP[&3]);
assert!(!ORDERED_MAP.contains_key(&100));
assert_eq!(&["a", "b", "c"][..], &ORDERED_MAP.values().cloned().collect::<Vec<_>>()[..]);
}
#[test]
fn ordered_set() {
assert!(ORDERED_SET.contains(&1));
assert!(ORDERED_SET.contains(&2));
assert!(ORDERED_SET.contains(&3));
assert!(!ORDERED_SET.contains(&4));
assert_eq!(&[1, 2, 3][..], &ORDERED_SET.iter().cloned().collect::<Vec<_>>()[..]);
}
#[test]
fn str_keys() {
assert_eq!(1, STR_KEYS["a"]);
assert_eq!(2, STR_KEYS["b"]);
assert_eq!(3, STR_KEYS["c"]);
}
#[test]
fn unicase_map() {
assert_eq!("a", UNICASE_MAP[&Ascii::new("AbC")]);
assert_eq!("a", UNICASE_MAP[&Ascii::new("abc")]);
assert_eq!("b", UNICASE_MAP[&Ascii::new("DEf")]);
assert!(!UNICASE_MAP.contains_key(&Ascii::new("XyZ")));
}
}
|
map
|
identifier_name
|
headless.rs
|
use crate::errors::*;
use crate::math::prelude::Vector2;
use super::super::events::Event;
use super::Visitor;
pub struct HeadlessVisitor {}
impl Visitor for HeadlessVisitor {
#[inline]
fn show(&self) {}
#[inline]
fn hide(&self) {}
#[inline]
fn position(&self) -> Vector2<i32> {
(0, 0).into()
}
#[inline]
fn dimensions(&self) -> Vector2<u32> {
(0, 0).into()
}
#[inline]
fn device_pixel_ratio(&self) -> f32 {
1.0
}
#[inline]
fn resize(&self, _: Vector2<u32>) {}
#[inline]
fn poll_events(&mut self, _: &mut Vec<Event>) {}
#[inline]
fn is_current(&self) -> bool {
true
}
#[inline]
fn make_current(&self) -> Result<()> {
Ok(())
}
#[inline]
fn
|
(&self) -> Result<()> {
Ok(())
}
}
|
swap_buffers
|
identifier_name
|
headless.rs
|
use crate::errors::*;
use crate::math::prelude::Vector2;
use super::super::events::Event;
use super::Visitor;
pub struct HeadlessVisitor {}
impl Visitor for HeadlessVisitor {
#[inline]
fn show(&self) {}
#[inline]
fn hide(&self) {}
#[inline]
fn position(&self) -> Vector2<i32> {
(0, 0).into()
}
#[inline]
fn dimensions(&self) -> Vector2<u32> {
(0, 0).into()
}
#[inline]
fn device_pixel_ratio(&self) -> f32 {
1.0
}
#[inline]
fn resize(&self, _: Vector2<u32>) {}
#[inline]
fn poll_events(&mut self, _: &mut Vec<Event>)
|
#[inline]
fn is_current(&self) -> bool {
true
}
#[inline]
fn make_current(&self) -> Result<()> {
Ok(())
}
#[inline]
fn swap_buffers(&self) -> Result<()> {
Ok(())
}
}
|
{}
|
identifier_body
|
headless.rs
|
use crate::errors::*;
use crate::math::prelude::Vector2;
use super::super::events::Event;
|
pub struct HeadlessVisitor {}
impl Visitor for HeadlessVisitor {
#[inline]
fn show(&self) {}
#[inline]
fn hide(&self) {}
#[inline]
fn position(&self) -> Vector2<i32> {
(0, 0).into()
}
#[inline]
fn dimensions(&self) -> Vector2<u32> {
(0, 0).into()
}
#[inline]
fn device_pixel_ratio(&self) -> f32 {
1.0
}
#[inline]
fn resize(&self, _: Vector2<u32>) {}
#[inline]
fn poll_events(&mut self, _: &mut Vec<Event>) {}
#[inline]
fn is_current(&self) -> bool {
true
}
#[inline]
fn make_current(&self) -> Result<()> {
Ok(())
}
#[inline]
fn swap_buffers(&self) -> Result<()> {
Ok(())
}
}
|
use super::Visitor;
|
random_line_split
|
casing.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 syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::codemap::Span;
use syntax::ast;
use syntax::ext::base;
use syntax::parse::token;
pub fn
|
<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |s| { s.to_lowercase() })
}
pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |s| { s.to_uppercase() })
}
fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T)
-> Box<base::MacResult + 'cx>
where T: Fn(&str) -> String
{
let es = match base::get_exprs_from_tts(cx, sp, tts) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut it = es.iter();
let res = if let Some(expr) = it.next() {
if let ast::ExprLit(ref lit) = expr.node {
if let ast::LitStr(ref s, _) = lit.node {
Some((s, lit.span))
} else {
cx.span_err(expr.span, "expected a string literal");
None
}
} else {
cx.span_err(expr.span, "expected a string literal");
None
}
} else {
cx.span_err(sp, "expected 1 argument, found 0");
None
};
match (res, it.count()) {
(Some((s, span)), 0) => {
base::MacEager::expr(cx.expr_str(span, token::intern_and_get_ident(&transform(&s))))
}
(_, rest) => {
if rest > 0 {
cx.span_err(sp, &format!("expected 1 argument, found {}", rest + 1));
}
base::DummyResult::expr(sp)
}
}
}
|
expand_lower
|
identifier_name
|
casing.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 syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::codemap::Span;
use syntax::ast;
use syntax::ext::base;
use syntax::parse::token;
pub fn expand_lower<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |s| { s.to_lowercase() })
}
pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |s| { s.to_uppercase() })
|
-> Box<base::MacResult + 'cx>
where T: Fn(&str) -> String
{
let es = match base::get_exprs_from_tts(cx, sp, tts) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut it = es.iter();
let res = if let Some(expr) = it.next() {
if let ast::ExprLit(ref lit) = expr.node {
if let ast::LitStr(ref s, _) = lit.node {
Some((s, lit.span))
} else {
cx.span_err(expr.span, "expected a string literal");
None
}
} else {
cx.span_err(expr.span, "expected a string literal");
None
}
} else {
cx.span_err(sp, "expected 1 argument, found 0");
None
};
match (res, it.count()) {
(Some((s, span)), 0) => {
base::MacEager::expr(cx.expr_str(span, token::intern_and_get_ident(&transform(&s))))
}
(_, rest) => {
if rest > 0 {
cx.span_err(sp, &format!("expected 1 argument, found {}", rest + 1));
}
base::DummyResult::expr(sp)
}
}
}
|
}
fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T)
|
random_line_split
|
casing.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 syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::codemap::Span;
use syntax::ast;
use syntax::ext::base;
use syntax::parse::token;
pub fn expand_lower<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx> {
expand_cased(cx, sp, tts, |s| { s.to_lowercase() })
}
pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult + 'cx>
|
fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T)
-> Box<base::MacResult + 'cx>
where T: Fn(&str) -> String
{
let es = match base::get_exprs_from_tts(cx, sp, tts) {
Some(e) => e,
None => return base::DummyResult::expr(sp)
};
let mut it = es.iter();
let res = if let Some(expr) = it.next() {
if let ast::ExprLit(ref lit) = expr.node {
if let ast::LitStr(ref s, _) = lit.node {
Some((s, lit.span))
} else {
cx.span_err(expr.span, "expected a string literal");
None
}
} else {
cx.span_err(expr.span, "expected a string literal");
None
}
} else {
cx.span_err(sp, "expected 1 argument, found 0");
None
};
match (res, it.count()) {
(Some((s, span)), 0) => {
base::MacEager::expr(cx.expr_str(span, token::intern_and_get_ident(&transform(&s))))
}
(_, rest) => {
if rest > 0 {
cx.span_err(sp, &format!("expected 1 argument, found {}", rest + 1));
}
base::DummyResult::expr(sp)
}
}
}
|
{
expand_cased(cx, sp, tts, |s| { s.to_uppercase() })
}
|
identifier_body
|
io_sync_bridge.rs
|
#![cfg(feature = "io-util")]
use std::error::Error;
use std::io::{Cursor, Read, Result as IoResult};
use tokio::io::AsyncRead;
use tokio_util::io::SyncIoBridge;
async fn test_reader_len(
r: impl AsyncRead + Unpin + Send +'static,
expected_len: usize,
) -> IoResult<()> {
let mut r = SyncIoBridge::new(r);
let res = tokio::task::spawn_blocking(move || {
let mut buf = Vec::new();
r.read_to_end(&mut buf)?;
Ok::<_, std::io::Error>(buf)
})
.await?;
assert_eq!(res?.len(), expected_len);
Ok(())
}
#[tokio::test]
async fn
|
() -> Result<(), Box<dyn Error>> {
test_reader_len(tokio::io::empty(), 0).await?;
let buf = b"hello world";
test_reader_len(Cursor::new(buf), buf.len()).await?;
Ok(())
}
#[tokio::test]
async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> {
let mut dest = Vec::new();
let src = b"hello world";
let dest = tokio::task::spawn_blocking(move || -> Result<_, String> {
let mut w = SyncIoBridge::new(Cursor::new(&mut dest));
std::io::copy(&mut Cursor::new(src), &mut w).map_err(|e| e.to_string())?;
Ok(dest)
})
.await??;
assert_eq!(dest.as_slice(), src);
Ok(())
}
|
test_async_read_to_sync
|
identifier_name
|
io_sync_bridge.rs
|
#![cfg(feature = "io-util")]
use std::error::Error;
use std::io::{Cursor, Read, Result as IoResult};
use tokio::io::AsyncRead;
use tokio_util::io::SyncIoBridge;
async fn test_reader_len(
r: impl AsyncRead + Unpin + Send +'static,
expected_len: usize,
) -> IoResult<()> {
let mut r = SyncIoBridge::new(r);
let res = tokio::task::spawn_blocking(move || {
let mut buf = Vec::new();
r.read_to_end(&mut buf)?;
Ok::<_, std::io::Error>(buf)
})
.await?;
assert_eq!(res?.len(), expected_len);
Ok(())
}
|
test_reader_len(Cursor::new(buf), buf.len()).await?;
Ok(())
}
#[tokio::test]
async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> {
let mut dest = Vec::new();
let src = b"hello world";
let dest = tokio::task::spawn_blocking(move || -> Result<_, String> {
let mut w = SyncIoBridge::new(Cursor::new(&mut dest));
std::io::copy(&mut Cursor::new(src), &mut w).map_err(|e| e.to_string())?;
Ok(dest)
})
.await??;
assert_eq!(dest.as_slice(), src);
Ok(())
}
|
#[tokio::test]
async fn test_async_read_to_sync() -> Result<(), Box<dyn Error>> {
test_reader_len(tokio::io::empty(), 0).await?;
let buf = b"hello world";
|
random_line_split
|
io_sync_bridge.rs
|
#![cfg(feature = "io-util")]
use std::error::Error;
use std::io::{Cursor, Read, Result as IoResult};
use tokio::io::AsyncRead;
use tokio_util::io::SyncIoBridge;
async fn test_reader_len(
r: impl AsyncRead + Unpin + Send +'static,
expected_len: usize,
) -> IoResult<()> {
let mut r = SyncIoBridge::new(r);
let res = tokio::task::spawn_blocking(move || {
let mut buf = Vec::new();
r.read_to_end(&mut buf)?;
Ok::<_, std::io::Error>(buf)
})
.await?;
assert_eq!(res?.len(), expected_len);
Ok(())
}
#[tokio::test]
async fn test_async_read_to_sync() -> Result<(), Box<dyn Error>>
|
#[tokio::test]
async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> {
let mut dest = Vec::new();
let src = b"hello world";
let dest = tokio::task::spawn_blocking(move || -> Result<_, String> {
let mut w = SyncIoBridge::new(Cursor::new(&mut dest));
std::io::copy(&mut Cursor::new(src), &mut w).map_err(|e| e.to_string())?;
Ok(dest)
})
.await??;
assert_eq!(dest.as_slice(), src);
Ok(())
}
|
{
test_reader_len(tokio::io::empty(), 0).await?;
let buf = b"hello world";
test_reader_len(Cursor::new(buf), buf.len()).await?;
Ok(())
}
|
identifier_body
|
timers.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::callback::ExceptionHandling::Report;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::global::global_root_from_reflector;
use dom::bindings::reflector::Reflectable;
use dom::bindings::trace::JSTraceable;
use dom::window::ScriptHelpers;
use euclid::length::Length;
use ipc_channel::ipc::IpcSender;
use js::jsapi::{HandleValue, Heap, RootedValue};
use js::jsval::{JSVal, UndefinedValue};
use num::traits::Saturating;
use script_traits::{MsDuration, precise_time_ms};
use script_traits::{TimerEvent, TimerEventId, TimerEventRequest, TimerSource};
use std::cell::Cell;
use std::cmp::{self, Ord, Ordering};
use std::default::Default;
use std::rc::Rc;
use util::mem::HeapSizeOf;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Eq, Copy, Clone, HeapSizeOf, Hash, PartialOrd, Ord, Debug)]
pub struct TimerHandle(i32);
#[derive(JSTraceable, HeapSizeOf)]
#[privatize]
pub struct ActiveTimers {
#[ignore_heap_size_of = "Defined in std"]
timer_event_chan: IpcSender<TimerEvent>,
#[ignore_heap_size_of = "Defined in std"]
scheduler_chan: IpcSender<TimerEventRequest>,
next_timer_handle: Cell<TimerHandle>,
timers: DOMRefCell<Vec<Timer>>,
suspended_since: Cell<Option<MsDuration>>,
/// Initially 0, increased whenever the associated document is reactivated
/// by the amount of ms the document was inactive. The current time can be
/// offset back by this amount for a coherent time across document
/// activations.
suspension_offset: Cell<MsDuration>,
/// Calls to `fire_timer` with a different argument than this get ignored.
/// They were previously scheduled and got invalidated when
/// - timers were suspended,
/// - the timer it was scheduled for got canceled or
/// - a timer was added with an earlier callback time. In this case the
/// original timer is rescheduled when it is the next one to get called.
expected_event_id: Cell<TimerEventId>,
/// The nesting level of the currently executing timer task or 0.
nesting_level: Cell<u32>,
}
// Holder for the various JS values associated with setTimeout
// (ie. function value to invoke and all arguments to pass
// to the function when calling it)
// TODO: Handle rooting during fire_timer when movable GC is turned on
#[derive(JSTraceable, HeapSizeOf)]
#[privatize]
struct Timer {
handle: TimerHandle,
source: TimerSource,
callback: InternalTimerCallback,
is_interval: IsInterval,
nesting_level: u32,
duration: MsDuration,
next_call: MsDuration,
}
// Enum allowing more descriptive values for the is_interval field
#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf)]
pub enum IsInterval {
Interval,
NonInterval,
}
impl Ord for Timer {
fn cmp(&self, other: &Timer) -> Ordering {
match self.next_call.cmp(&other.next_call).reverse() {
Ordering::Equal => self.handle.cmp(&other.handle).reverse(),
res => res
}
}
}
impl PartialOrd for Timer {
fn partial_cmp(&self, other: &Timer) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for Timer {}
impl PartialEq for Timer {
fn eq(&self, other: &Timer) -> bool {
self as *const Timer == other as *const Timer
}
}
#[derive(Clone)]
pub enum TimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Rc<Function>),
}
#[derive(JSTraceable, Clone)]
enum InternalTimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Rc<Function>, Rc<Vec<Heap<JSVal>>>),
InternalCallback(Box<ScheduledCallback>),
}
impl HeapSizeOf for InternalTimerCallback {
fn heap_size_of_children(&self) -> usize {
// FIXME: Rc<T> isn't HeapSizeOf and we can't ignore it due to #6870 and #6871
0
}
}
pub trait ScheduledCallback: JSTraceable + HeapSizeOf {
fn invoke(self: Box<Self>);
fn box_clone(&self) -> Box<ScheduledCallback>;
}
impl Clone for Box<ScheduledCallback> {
fn clone(&self) -> Box<ScheduledCallback> {
self.box_clone()
}
}
impl ActiveTimers {
pub fn new(timer_event_chan: IpcSender<TimerEvent>,
scheduler_chan: IpcSender<TimerEventRequest>)
-> ActiveTimers {
ActiveTimers {
timer_event_chan: timer_event_chan,
scheduler_chan: scheduler_chan,
next_timer_handle: Cell::new(TimerHandle(1)),
timers: DOMRefCell::new(Vec::new()),
suspended_since: Cell::new(None),
suspension_offset: Cell::new(Length::new(0)),
expected_event_id: Cell::new(TimerEventId(0)),
nesting_level: Cell::new(0),
}
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
pub fn set_timeout_or_interval(&self,
callback: TimerCallback,
arguments: Vec<HandleValue>,
timeout: i32,
is_interval: IsInterval,
source: TimerSource)
-> i32 {
let callback = match callback {
TimerCallback::StringTimerCallback(code_str) =>
InternalTimerCallback::StringTimerCallback(code_str),
TimerCallback::FunctionTimerCallback(function) => {
// This is a bit complicated, but this ensures that the vector's
// buffer isn't reallocated (and moved) after setting the Heap values
let mut args = Vec::with_capacity(arguments.len());
for _ in 0..arguments.len() {
args.push(Heap::default());
}
for (i, item) in arguments.iter().enumerate() {
args.get_mut(i).unwrap().set(item.get());
}
InternalTimerCallback::FunctionTimerCallback(function, Rc::new(args))
}
};
let timeout = cmp::max(0, timeout);
// step 7
let duration = self.clamp_duration(Length::new(timeout as u64));
let TimerHandle(handle) = self.schedule_internal_callback(callback, duration, is_interval, source);
handle
}
pub fn schedule_callback(&self,
callback: Box<ScheduledCallback>,
duration: MsDuration,
source: TimerSource) -> TimerHandle {
self.schedule_internal_callback(InternalTimerCallback::InternalCallback(callback),
duration,
IsInterval::NonInterval,
source)
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
fn schedule_internal_callback(&self,
callback: InternalTimerCallback,
duration: MsDuration,
is_interval: IsInterval,
source: TimerSource) -> TimerHandle {
// step 3
let TimerHandle(new_handle) = self.next_timer_handle.get();
self.next_timer_handle.set(TimerHandle(new_handle + 1));
let next_call = self.base_time() + duration;
let timer = Timer {
handle: TimerHandle(new_handle),
source: source,
callback: callback,
is_interval: is_interval,
duration: duration,
// step 6
nesting_level: self.nesting_level.get() + 1,
next_call: next_call,
};
self.insert_timer(timer);
let TimerHandle(max_handle) = self.timers.borrow().last().unwrap().handle;
if max_handle == new_handle {
self.schedule_timer_call();
}
// step 10
TimerHandle(new_handle)
}
pub fn clear_timeout_or_interval(&self, handle: i32) {
self.unschedule_callback(TimerHandle(handle));
}
pub fn unschedule_callback(&self, handle: TimerHandle) {
let was_next = self.is_next_timer(handle);
self.timers.borrow_mut().retain(|t| t.handle!= handle);
if was_next {
self.invalidate_expected_event_id();
self.schedule_timer_call();
}
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
#[allow(unsafe_code)]
pub fn fire_timer<T: Reflectable>(&self, id: TimerEventId, this: &T) {
let expected_id = self.expected_event_id.get();
if expected_id!= id {
debug!("ignoring timer fire event {:?} (expected {:?}", id, expected_id);
return;
}
assert!(self.suspended_since.get().is_none());
let base_time = self.base_time();
// Since the event id was the expected one, at least one timer should be due.
assert!(base_time >= self.timers.borrow().last().unwrap().next_call);
// select timers to run to prevent firing timers
// that were installed during fire of another timer
let mut timers_to_run: Vec<Timer> = Vec::new();
loop {
let mut timers = self.timers.borrow_mut();
if timers.is_empty() || timers.last().unwrap().next_call > base_time {
break;
}
timers_to_run.push(timers.pop().unwrap());
}
for timer in timers_to_run {
let callback = timer.callback.clone();
// prep for step 6 in nested set_timeout_or_interval calls
self.nesting_level.set(timer.nesting_level);
// step 4.3
if timer.is_interval == IsInterval::Interval {
let mut timer = timer;
// step 7
timer.duration = self.clamp_duration(timer.duration);
// step 8, 9
timer.nesting_level += 1;
timer.next_call = base_time + timer.duration;
self.insert_timer(timer);
}
// step 14
match callback {
InternalTimerCallback::StringTimerCallback(code_str) => {
let cx = global_root_from_reflector(this).r().get_cx();
let mut rval = RootedValue::new(cx, UndefinedValue());
this.evaluate_js_on_global_with_result(&code_str, rval.handle_mut());
},
InternalTimerCallback::FunctionTimerCallback(function, arguments) => {
let arguments: Vec<JSVal> = arguments.iter().map(|arg| arg.get()).collect();
let arguments = arguments.iter().by_ref().map(|arg| unsafe {
HandleValue::from_marked_location(arg)
}).collect();
let _ = function.Call_(this, arguments, Report);
},
InternalTimerCallback::InternalCallback(callback) => {
callback.invoke();
},
};
self.nesting_level.set(0);
}
self.schedule_timer_call();
}
fn insert_timer(&self, timer: Timer) {
let mut timers = self.timers.borrow_mut();
let insertion_index = timers.binary_search(&timer).err().unwrap();
timers.insert(insertion_index, timer);
}
fn is_next_timer(&self, handle: TimerHandle) -> bool {
match self.timers.borrow().last() {
None => false,
Some(ref max_timer) => max_timer.handle == handle
}
}
fn schedule_timer_call(&self)
|
pub fn suspend(&self) {
assert!(self.suspended_since.get().is_none());
self.suspended_since.set(Some(precise_time_ms()));
self.invalidate_expected_event_id();
}
pub fn resume(&self) {
assert!(self.suspended_since.get().is_some());
let additional_offset = match self.suspended_since.get() {
Some(suspended_since) => precise_time_ms() - suspended_since,
None => panic!("Timers are not suspended.")
};
self.suspension_offset.set(self.suspension_offset.get() + additional_offset);
self.schedule_timer_call();
}
fn base_time(&self) -> MsDuration {
let offset = self.suspension_offset.get();
match self.suspended_since.get() {
Some(time) => time - offset,
None => precise_time_ms() - offset,
}
}
// see step 7 of https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
fn clamp_duration(&self, unclamped: MsDuration) -> MsDuration {
let ms = if self.nesting_level.get() > 5 {
4
} else {
0
};
cmp::max(Length::new(ms), unclamped)
}
fn invalidate_expected_event_id(&self) -> TimerEventId {
let TimerEventId(currently_expected) = self.expected_event_id.get();
let next_id = TimerEventId(currently_expected + 1);
debug!("invalidating expected timer (was {:?}, now {:?}", currently_expected, next_id);
self.expected_event_id.set(next_id);
next_id
}
}
|
{
if self.suspended_since.get().is_some() {
// The timer will be scheduled when the pipeline is thawed.
return;
}
let timers = self.timers.borrow();
if let Some(timer) = timers.last() {
let expected_event_id = self.invalidate_expected_event_id();
let delay = Length::new(timer.next_call.get().saturating_sub(precise_time_ms().get()));
let request = TimerEventRequest(self.timer_event_chan.clone(), timer.source,
expected_event_id, delay);
self.scheduler_chan.send(request).unwrap();
}
}
|
identifier_body
|
timers.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::callback::ExceptionHandling::Report;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::global::global_root_from_reflector;
use dom::bindings::reflector::Reflectable;
use dom::bindings::trace::JSTraceable;
use dom::window::ScriptHelpers;
use euclid::length::Length;
use ipc_channel::ipc::IpcSender;
use js::jsapi::{HandleValue, Heap, RootedValue};
use js::jsval::{JSVal, UndefinedValue};
use num::traits::Saturating;
use script_traits::{MsDuration, precise_time_ms};
use script_traits::{TimerEvent, TimerEventId, TimerEventRequest, TimerSource};
use std::cell::Cell;
use std::cmp::{self, Ord, Ordering};
use std::default::Default;
use std::rc::Rc;
use util::mem::HeapSizeOf;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Eq, Copy, Clone, HeapSizeOf, Hash, PartialOrd, Ord, Debug)]
pub struct TimerHandle(i32);
#[derive(JSTraceable, HeapSizeOf)]
#[privatize]
pub struct ActiveTimers {
#[ignore_heap_size_of = "Defined in std"]
timer_event_chan: IpcSender<TimerEvent>,
#[ignore_heap_size_of = "Defined in std"]
scheduler_chan: IpcSender<TimerEventRequest>,
next_timer_handle: Cell<TimerHandle>,
timers: DOMRefCell<Vec<Timer>>,
suspended_since: Cell<Option<MsDuration>>,
/// Initially 0, increased whenever the associated document is reactivated
/// by the amount of ms the document was inactive. The current time can be
/// offset back by this amount for a coherent time across document
/// activations.
suspension_offset: Cell<MsDuration>,
/// Calls to `fire_timer` with a different argument than this get ignored.
/// They were previously scheduled and got invalidated when
/// - timers were suspended,
/// - the timer it was scheduled for got canceled or
/// - a timer was added with an earlier callback time. In this case the
/// original timer is rescheduled when it is the next one to get called.
expected_event_id: Cell<TimerEventId>,
/// The nesting level of the currently executing timer task or 0.
nesting_level: Cell<u32>,
}
// Holder for the various JS values associated with setTimeout
// (ie. function value to invoke and all arguments to pass
// to the function when calling it)
// TODO: Handle rooting during fire_timer when movable GC is turned on
#[derive(JSTraceable, HeapSizeOf)]
#[privatize]
struct Timer {
handle: TimerHandle,
source: TimerSource,
callback: InternalTimerCallback,
is_interval: IsInterval,
nesting_level: u32,
duration: MsDuration,
next_call: MsDuration,
}
// Enum allowing more descriptive values for the is_interval field
#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf)]
pub enum IsInterval {
Interval,
NonInterval,
}
impl Ord for Timer {
fn cmp(&self, other: &Timer) -> Ordering {
match self.next_call.cmp(&other.next_call).reverse() {
Ordering::Equal => self.handle.cmp(&other.handle).reverse(),
res => res
}
}
}
impl PartialOrd for Timer {
fn partial_cmp(&self, other: &Timer) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for Timer {}
impl PartialEq for Timer {
fn eq(&self, other: &Timer) -> bool {
self as *const Timer == other as *const Timer
}
}
#[derive(Clone)]
pub enum TimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Rc<Function>),
}
#[derive(JSTraceable, Clone)]
enum InternalTimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Rc<Function>, Rc<Vec<Heap<JSVal>>>),
InternalCallback(Box<ScheduledCallback>),
}
impl HeapSizeOf for InternalTimerCallback {
fn heap_size_of_children(&self) -> usize {
// FIXME: Rc<T> isn't HeapSizeOf and we can't ignore it due to #6870 and #6871
0
}
}
pub trait ScheduledCallback: JSTraceable + HeapSizeOf {
fn invoke(self: Box<Self>);
fn box_clone(&self) -> Box<ScheduledCallback>;
}
impl Clone for Box<ScheduledCallback> {
fn clone(&self) -> Box<ScheduledCallback> {
self.box_clone()
}
}
impl ActiveTimers {
pub fn
|
(timer_event_chan: IpcSender<TimerEvent>,
scheduler_chan: IpcSender<TimerEventRequest>)
-> ActiveTimers {
ActiveTimers {
timer_event_chan: timer_event_chan,
scheduler_chan: scheduler_chan,
next_timer_handle: Cell::new(TimerHandle(1)),
timers: DOMRefCell::new(Vec::new()),
suspended_since: Cell::new(None),
suspension_offset: Cell::new(Length::new(0)),
expected_event_id: Cell::new(TimerEventId(0)),
nesting_level: Cell::new(0),
}
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
pub fn set_timeout_or_interval(&self,
callback: TimerCallback,
arguments: Vec<HandleValue>,
timeout: i32,
is_interval: IsInterval,
source: TimerSource)
-> i32 {
let callback = match callback {
TimerCallback::StringTimerCallback(code_str) =>
InternalTimerCallback::StringTimerCallback(code_str),
TimerCallback::FunctionTimerCallback(function) => {
// This is a bit complicated, but this ensures that the vector's
// buffer isn't reallocated (and moved) after setting the Heap values
let mut args = Vec::with_capacity(arguments.len());
for _ in 0..arguments.len() {
args.push(Heap::default());
}
for (i, item) in arguments.iter().enumerate() {
args.get_mut(i).unwrap().set(item.get());
}
InternalTimerCallback::FunctionTimerCallback(function, Rc::new(args))
}
};
let timeout = cmp::max(0, timeout);
// step 7
let duration = self.clamp_duration(Length::new(timeout as u64));
let TimerHandle(handle) = self.schedule_internal_callback(callback, duration, is_interval, source);
handle
}
pub fn schedule_callback(&self,
callback: Box<ScheduledCallback>,
duration: MsDuration,
source: TimerSource) -> TimerHandle {
self.schedule_internal_callback(InternalTimerCallback::InternalCallback(callback),
duration,
IsInterval::NonInterval,
source)
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
fn schedule_internal_callback(&self,
callback: InternalTimerCallback,
duration: MsDuration,
is_interval: IsInterval,
source: TimerSource) -> TimerHandle {
// step 3
let TimerHandle(new_handle) = self.next_timer_handle.get();
self.next_timer_handle.set(TimerHandle(new_handle + 1));
let next_call = self.base_time() + duration;
let timer = Timer {
handle: TimerHandle(new_handle),
source: source,
callback: callback,
is_interval: is_interval,
duration: duration,
// step 6
nesting_level: self.nesting_level.get() + 1,
next_call: next_call,
};
self.insert_timer(timer);
let TimerHandle(max_handle) = self.timers.borrow().last().unwrap().handle;
if max_handle == new_handle {
self.schedule_timer_call();
}
// step 10
TimerHandle(new_handle)
}
pub fn clear_timeout_or_interval(&self, handle: i32) {
self.unschedule_callback(TimerHandle(handle));
}
pub fn unschedule_callback(&self, handle: TimerHandle) {
let was_next = self.is_next_timer(handle);
self.timers.borrow_mut().retain(|t| t.handle!= handle);
if was_next {
self.invalidate_expected_event_id();
self.schedule_timer_call();
}
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
#[allow(unsafe_code)]
pub fn fire_timer<T: Reflectable>(&self, id: TimerEventId, this: &T) {
let expected_id = self.expected_event_id.get();
if expected_id!= id {
debug!("ignoring timer fire event {:?} (expected {:?}", id, expected_id);
return;
}
assert!(self.suspended_since.get().is_none());
let base_time = self.base_time();
// Since the event id was the expected one, at least one timer should be due.
assert!(base_time >= self.timers.borrow().last().unwrap().next_call);
// select timers to run to prevent firing timers
// that were installed during fire of another timer
let mut timers_to_run: Vec<Timer> = Vec::new();
loop {
let mut timers = self.timers.borrow_mut();
if timers.is_empty() || timers.last().unwrap().next_call > base_time {
break;
}
timers_to_run.push(timers.pop().unwrap());
}
for timer in timers_to_run {
let callback = timer.callback.clone();
// prep for step 6 in nested set_timeout_or_interval calls
self.nesting_level.set(timer.nesting_level);
// step 4.3
if timer.is_interval == IsInterval::Interval {
let mut timer = timer;
// step 7
timer.duration = self.clamp_duration(timer.duration);
// step 8, 9
timer.nesting_level += 1;
timer.next_call = base_time + timer.duration;
self.insert_timer(timer);
}
// step 14
match callback {
InternalTimerCallback::StringTimerCallback(code_str) => {
let cx = global_root_from_reflector(this).r().get_cx();
let mut rval = RootedValue::new(cx, UndefinedValue());
this.evaluate_js_on_global_with_result(&code_str, rval.handle_mut());
},
InternalTimerCallback::FunctionTimerCallback(function, arguments) => {
let arguments: Vec<JSVal> = arguments.iter().map(|arg| arg.get()).collect();
let arguments = arguments.iter().by_ref().map(|arg| unsafe {
HandleValue::from_marked_location(arg)
}).collect();
let _ = function.Call_(this, arguments, Report);
},
InternalTimerCallback::InternalCallback(callback) => {
callback.invoke();
},
};
self.nesting_level.set(0);
}
self.schedule_timer_call();
}
fn insert_timer(&self, timer: Timer) {
let mut timers = self.timers.borrow_mut();
let insertion_index = timers.binary_search(&timer).err().unwrap();
timers.insert(insertion_index, timer);
}
fn is_next_timer(&self, handle: TimerHandle) -> bool {
match self.timers.borrow().last() {
None => false,
Some(ref max_timer) => max_timer.handle == handle
}
}
fn schedule_timer_call(&self) {
if self.suspended_since.get().is_some() {
// The timer will be scheduled when the pipeline is thawed.
return;
}
let timers = self.timers.borrow();
if let Some(timer) = timers.last() {
let expected_event_id = self.invalidate_expected_event_id();
let delay = Length::new(timer.next_call.get().saturating_sub(precise_time_ms().get()));
let request = TimerEventRequest(self.timer_event_chan.clone(), timer.source,
expected_event_id, delay);
self.scheduler_chan.send(request).unwrap();
}
}
pub fn suspend(&self) {
assert!(self.suspended_since.get().is_none());
self.suspended_since.set(Some(precise_time_ms()));
self.invalidate_expected_event_id();
}
pub fn resume(&self) {
assert!(self.suspended_since.get().is_some());
let additional_offset = match self.suspended_since.get() {
Some(suspended_since) => precise_time_ms() - suspended_since,
None => panic!("Timers are not suspended.")
};
self.suspension_offset.set(self.suspension_offset.get() + additional_offset);
self.schedule_timer_call();
}
fn base_time(&self) -> MsDuration {
let offset = self.suspension_offset.get();
match self.suspended_since.get() {
Some(time) => time - offset,
None => precise_time_ms() - offset,
}
}
// see step 7 of https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
fn clamp_duration(&self, unclamped: MsDuration) -> MsDuration {
let ms = if self.nesting_level.get() > 5 {
4
} else {
0
};
cmp::max(Length::new(ms), unclamped)
}
fn invalidate_expected_event_id(&self) -> TimerEventId {
let TimerEventId(currently_expected) = self.expected_event_id.get();
let next_id = TimerEventId(currently_expected + 1);
debug!("invalidating expected timer (was {:?}, now {:?}", currently_expected, next_id);
self.expected_event_id.set(next_id);
next_id
}
}
|
new
|
identifier_name
|
timers.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::callback::ExceptionHandling::Report;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::global::global_root_from_reflector;
use dom::bindings::reflector::Reflectable;
use dom::bindings::trace::JSTraceable;
use dom::window::ScriptHelpers;
use euclid::length::Length;
use ipc_channel::ipc::IpcSender;
use js::jsapi::{HandleValue, Heap, RootedValue};
use js::jsval::{JSVal, UndefinedValue};
use num::traits::Saturating;
use script_traits::{MsDuration, precise_time_ms};
use script_traits::{TimerEvent, TimerEventId, TimerEventRequest, TimerSource};
use std::cell::Cell;
use std::cmp::{self, Ord, Ordering};
use std::default::Default;
use std::rc::Rc;
use util::mem::HeapSizeOf;
use util::str::DOMString;
#[derive(JSTraceable, PartialEq, Eq, Copy, Clone, HeapSizeOf, Hash, PartialOrd, Ord, Debug)]
pub struct TimerHandle(i32);
#[derive(JSTraceable, HeapSizeOf)]
#[privatize]
pub struct ActiveTimers {
#[ignore_heap_size_of = "Defined in std"]
timer_event_chan: IpcSender<TimerEvent>,
#[ignore_heap_size_of = "Defined in std"]
scheduler_chan: IpcSender<TimerEventRequest>,
next_timer_handle: Cell<TimerHandle>,
timers: DOMRefCell<Vec<Timer>>,
suspended_since: Cell<Option<MsDuration>>,
/// Initially 0, increased whenever the associated document is reactivated
/// by the amount of ms the document was inactive. The current time can be
/// offset back by this amount for a coherent time across document
/// activations.
suspension_offset: Cell<MsDuration>,
/// Calls to `fire_timer` with a different argument than this get ignored.
/// They were previously scheduled and got invalidated when
/// - timers were suspended,
/// - the timer it was scheduled for got canceled or
/// - a timer was added with an earlier callback time. In this case the
/// original timer is rescheduled when it is the next one to get called.
expected_event_id: Cell<TimerEventId>,
/// The nesting level of the currently executing timer task or 0.
nesting_level: Cell<u32>,
}
// Holder for the various JS values associated with setTimeout
// (ie. function value to invoke and all arguments to pass
// to the function when calling it)
// TODO: Handle rooting during fire_timer when movable GC is turned on
#[derive(JSTraceable, HeapSizeOf)]
#[privatize]
struct Timer {
handle: TimerHandle,
source: TimerSource,
callback: InternalTimerCallback,
is_interval: IsInterval,
nesting_level: u32,
duration: MsDuration,
next_call: MsDuration,
}
// Enum allowing more descriptive values for the is_interval field
#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf)]
pub enum IsInterval {
Interval,
NonInterval,
}
impl Ord for Timer {
fn cmp(&self, other: &Timer) -> Ordering {
match self.next_call.cmp(&other.next_call).reverse() {
Ordering::Equal => self.handle.cmp(&other.handle).reverse(),
res => res
}
}
}
impl PartialOrd for Timer {
fn partial_cmp(&self, other: &Timer) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for Timer {}
impl PartialEq for Timer {
fn eq(&self, other: &Timer) -> bool {
self as *const Timer == other as *const Timer
}
}
#[derive(Clone)]
pub enum TimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Rc<Function>),
}
#[derive(JSTraceable, Clone)]
enum InternalTimerCallback {
StringTimerCallback(DOMString),
FunctionTimerCallback(Rc<Function>, Rc<Vec<Heap<JSVal>>>),
InternalCallback(Box<ScheduledCallback>),
}
impl HeapSizeOf for InternalTimerCallback {
fn heap_size_of_children(&self) -> usize {
// FIXME: Rc<T> isn't HeapSizeOf and we can't ignore it due to #6870 and #6871
0
}
}
pub trait ScheduledCallback: JSTraceable + HeapSizeOf {
fn invoke(self: Box<Self>);
fn box_clone(&self) -> Box<ScheduledCallback>;
}
impl Clone for Box<ScheduledCallback> {
fn clone(&self) -> Box<ScheduledCallback> {
self.box_clone()
}
}
impl ActiveTimers {
pub fn new(timer_event_chan: IpcSender<TimerEvent>,
scheduler_chan: IpcSender<TimerEventRequest>)
-> ActiveTimers {
ActiveTimers {
timer_event_chan: timer_event_chan,
scheduler_chan: scheduler_chan,
next_timer_handle: Cell::new(TimerHandle(1)),
timers: DOMRefCell::new(Vec::new()),
suspended_since: Cell::new(None),
suspension_offset: Cell::new(Length::new(0)),
expected_event_id: Cell::new(TimerEventId(0)),
nesting_level: Cell::new(0),
}
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
pub fn set_timeout_or_interval(&self,
callback: TimerCallback,
arguments: Vec<HandleValue>,
timeout: i32,
is_interval: IsInterval,
source: TimerSource)
-> i32 {
let callback = match callback {
TimerCallback::StringTimerCallback(code_str) =>
InternalTimerCallback::StringTimerCallback(code_str),
TimerCallback::FunctionTimerCallback(function) => {
// This is a bit complicated, but this ensures that the vector's
// buffer isn't reallocated (and moved) after setting the Heap values
let mut args = Vec::with_capacity(arguments.len());
for _ in 0..arguments.len() {
args.push(Heap::default());
}
for (i, item) in arguments.iter().enumerate() {
args.get_mut(i).unwrap().set(item.get());
}
InternalTimerCallback::FunctionTimerCallback(function, Rc::new(args))
}
};
let timeout = cmp::max(0, timeout);
// step 7
let duration = self.clamp_duration(Length::new(timeout as u64));
let TimerHandle(handle) = self.schedule_internal_callback(callback, duration, is_interval, source);
handle
}
pub fn schedule_callback(&self,
callback: Box<ScheduledCallback>,
duration: MsDuration,
source: TimerSource) -> TimerHandle {
self.schedule_internal_callback(InternalTimerCallback::InternalCallback(callback),
duration,
IsInterval::NonInterval,
source)
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
fn schedule_internal_callback(&self,
callback: InternalTimerCallback,
duration: MsDuration,
is_interval: IsInterval,
source: TimerSource) -> TimerHandle {
// step 3
let TimerHandle(new_handle) = self.next_timer_handle.get();
self.next_timer_handle.set(TimerHandle(new_handle + 1));
let next_call = self.base_time() + duration;
let timer = Timer {
handle: TimerHandle(new_handle),
source: source,
callback: callback,
is_interval: is_interval,
duration: duration,
// step 6
nesting_level: self.nesting_level.get() + 1,
next_call: next_call,
};
self.insert_timer(timer);
let TimerHandle(max_handle) = self.timers.borrow().last().unwrap().handle;
if max_handle == new_handle {
self.schedule_timer_call();
}
// step 10
TimerHandle(new_handle)
}
pub fn clear_timeout_or_interval(&self, handle: i32) {
self.unschedule_callback(TimerHandle(handle));
}
pub fn unschedule_callback(&self, handle: TimerHandle) {
let was_next = self.is_next_timer(handle);
self.timers.borrow_mut().retain(|t| t.handle!= handle);
if was_next {
self.invalidate_expected_event_id();
self.schedule_timer_call();
}
}
// see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
#[allow(unsafe_code)]
|
pub fn fire_timer<T: Reflectable>(&self, id: TimerEventId, this: &T) {
let expected_id = self.expected_event_id.get();
if expected_id!= id {
debug!("ignoring timer fire event {:?} (expected {:?}", id, expected_id);
return;
}
assert!(self.suspended_since.get().is_none());
let base_time = self.base_time();
// Since the event id was the expected one, at least one timer should be due.
assert!(base_time >= self.timers.borrow().last().unwrap().next_call);
// select timers to run to prevent firing timers
// that were installed during fire of another timer
let mut timers_to_run: Vec<Timer> = Vec::new();
loop {
let mut timers = self.timers.borrow_mut();
if timers.is_empty() || timers.last().unwrap().next_call > base_time {
break;
}
timers_to_run.push(timers.pop().unwrap());
}
for timer in timers_to_run {
let callback = timer.callback.clone();
// prep for step 6 in nested set_timeout_or_interval calls
self.nesting_level.set(timer.nesting_level);
// step 4.3
if timer.is_interval == IsInterval::Interval {
let mut timer = timer;
// step 7
timer.duration = self.clamp_duration(timer.duration);
// step 8, 9
timer.nesting_level += 1;
timer.next_call = base_time + timer.duration;
self.insert_timer(timer);
}
// step 14
match callback {
InternalTimerCallback::StringTimerCallback(code_str) => {
let cx = global_root_from_reflector(this).r().get_cx();
let mut rval = RootedValue::new(cx, UndefinedValue());
this.evaluate_js_on_global_with_result(&code_str, rval.handle_mut());
},
InternalTimerCallback::FunctionTimerCallback(function, arguments) => {
let arguments: Vec<JSVal> = arguments.iter().map(|arg| arg.get()).collect();
let arguments = arguments.iter().by_ref().map(|arg| unsafe {
HandleValue::from_marked_location(arg)
}).collect();
let _ = function.Call_(this, arguments, Report);
},
InternalTimerCallback::InternalCallback(callback) => {
callback.invoke();
},
};
self.nesting_level.set(0);
}
self.schedule_timer_call();
}
fn insert_timer(&self, timer: Timer) {
let mut timers = self.timers.borrow_mut();
let insertion_index = timers.binary_search(&timer).err().unwrap();
timers.insert(insertion_index, timer);
}
fn is_next_timer(&self, handle: TimerHandle) -> bool {
match self.timers.borrow().last() {
None => false,
Some(ref max_timer) => max_timer.handle == handle
}
}
fn schedule_timer_call(&self) {
if self.suspended_since.get().is_some() {
// The timer will be scheduled when the pipeline is thawed.
return;
}
let timers = self.timers.borrow();
if let Some(timer) = timers.last() {
let expected_event_id = self.invalidate_expected_event_id();
let delay = Length::new(timer.next_call.get().saturating_sub(precise_time_ms().get()));
let request = TimerEventRequest(self.timer_event_chan.clone(), timer.source,
expected_event_id, delay);
self.scheduler_chan.send(request).unwrap();
}
}
pub fn suspend(&self) {
assert!(self.suspended_since.get().is_none());
self.suspended_since.set(Some(precise_time_ms()));
self.invalidate_expected_event_id();
}
pub fn resume(&self) {
assert!(self.suspended_since.get().is_some());
let additional_offset = match self.suspended_since.get() {
Some(suspended_since) => precise_time_ms() - suspended_since,
None => panic!("Timers are not suspended.")
};
self.suspension_offset.set(self.suspension_offset.get() + additional_offset);
self.schedule_timer_call();
}
fn base_time(&self) -> MsDuration {
let offset = self.suspension_offset.get();
match self.suspended_since.get() {
Some(time) => time - offset,
None => precise_time_ms() - offset,
}
}
// see step 7 of https://html.spec.whatwg.org/multipage/#timer-initialisation-steps
fn clamp_duration(&self, unclamped: MsDuration) -> MsDuration {
let ms = if self.nesting_level.get() > 5 {
4
} else {
0
};
cmp::max(Length::new(ms), unclamped)
}
fn invalidate_expected_event_id(&self) -> TimerEventId {
let TimerEventId(currently_expected) = self.expected_event_id.get();
let next_id = TimerEventId(currently_expected + 1);
debug!("invalidating expected timer (was {:?}, now {:?}", currently_expected, next_id);
self.expected_event_id.set(next_id);
next_id
}
}
|
random_line_split
|
|
list-all-function-runtimes.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region in which the client is created.
#[structopt(short, long)]
region: Option<String>,
/// Just show runtimes for indicated language.
/// dotnet, go, node, java, etc.
#[structopt(short, long)]
language: Option<String>,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
/// Lists the ARNs and runtimes of all Lambda functions in all Regions.
// snippet-start:[lambda.rust.list-all-function-runtimes]
async fn show_lambdas(verbose: bool, language: &str, reg: &'static str) {
let region_provider = RegionProviderChain::default_provider().or_else(reg);
let config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&config);
|
let max_functions = functions.len();
let mut num_functions = 0;
for function in functions {
let rt_str: String = String::from(function.runtime().unwrap().as_ref());
// If language is set (!= ""), show only those with that runtime.
let ok = rt_str
.to_ascii_lowercase()
.contains(&language.to_ascii_lowercase());
if ok || language.is_empty() {
println!(" ARN: {}", function.function_arn().unwrap());
println!(" Runtime: {}", rt_str);
println!();
num_functions += 1;
}
}
if num_functions > 0 || verbose {
println!(
"Found {} function(s) (out of {}) in {} region.",
num_functions, max_functions, reg
);
println!();
}
}
// snippet-end:[lambda.rust.list-all-function-runtimes]
/// Lists the ARNs and runtimes of your Lambda functions in all available regions.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
language,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", aws_sdk_ec2::PKG_VERSION);
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}
// Get list of available regions.
let shared_config = aws_config::from_env().region(region_provider).load().await;
let ec2_client = aws_sdk_ec2::Client::new(&shared_config);
let resp = ec2_client.describe_regions().send().await;
for region in resp.unwrap().regions.unwrap_or_default() {
let reg: &'static str = Box::leak(region.region_name.unwrap().into_boxed_str());
show_lambdas(verbose, language.as_deref().unwrap_or_default(), reg).await;
}
Ok(())
}
|
let resp = client.list_functions().send().await;
let functions = resp.unwrap().functions.unwrap_or_default();
|
random_line_split
|
list-all-function-runtimes.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region in which the client is created.
#[structopt(short, long)]
region: Option<String>,
/// Just show runtimes for indicated language.
/// dotnet, go, node, java, etc.
#[structopt(short, long)]
language: Option<String>,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
/// Lists the ARNs and runtimes of all Lambda functions in all Regions.
// snippet-start:[lambda.rust.list-all-function-runtimes]
async fn show_lambdas(verbose: bool, language: &str, reg: &'static str) {
let region_provider = RegionProviderChain::default_provider().or_else(reg);
let config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&config);
let resp = client.list_functions().send().await;
let functions = resp.unwrap().functions.unwrap_or_default();
let max_functions = functions.len();
let mut num_functions = 0;
for function in functions {
let rt_str: String = String::from(function.runtime().unwrap().as_ref());
// If language is set (!= ""), show only those with that runtime.
let ok = rt_str
.to_ascii_lowercase()
.contains(&language.to_ascii_lowercase());
if ok || language.is_empty() {
println!(" ARN: {}", function.function_arn().unwrap());
println!(" Runtime: {}", rt_str);
println!();
num_functions += 1;
}
}
if num_functions > 0 || verbose {
println!(
"Found {} function(s) (out of {}) in {} region.",
num_functions, max_functions, reg
);
println!();
}
}
// snippet-end:[lambda.rust.list-all-function-runtimes]
/// Lists the ARNs and runtimes of your Lambda functions in all available regions.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error>
|
);
println!();
}
// Get list of available regions.
let shared_config = aws_config::from_env().region(region_provider).load().await;
let ec2_client = aws_sdk_ec2::Client::new(&shared_config);
let resp = ec2_client.describe_regions().send().await;
for region in resp.unwrap().regions.unwrap_or_default() {
let reg: &'static str = Box::leak(region.region_name.unwrap().into_boxed_str());
show_lambdas(verbose, language.as_deref().unwrap_or_default(), reg).await;
}
Ok(())
}
|
{
tracing_subscriber::fmt::init();
let Opt {
language,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", aws_sdk_ec2::PKG_VERSION);
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
|
identifier_body
|
list-all-function-runtimes.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region in which the client is created.
#[structopt(short, long)]
region: Option<String>,
/// Just show runtimes for indicated language.
/// dotnet, go, node, java, etc.
#[structopt(short, long)]
language: Option<String>,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
/// Lists the ARNs and runtimes of all Lambda functions in all Regions.
// snippet-start:[lambda.rust.list-all-function-runtimes]
async fn
|
(verbose: bool, language: &str, reg: &'static str) {
let region_provider = RegionProviderChain::default_provider().or_else(reg);
let config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&config);
let resp = client.list_functions().send().await;
let functions = resp.unwrap().functions.unwrap_or_default();
let max_functions = functions.len();
let mut num_functions = 0;
for function in functions {
let rt_str: String = String::from(function.runtime().unwrap().as_ref());
// If language is set (!= ""), show only those with that runtime.
let ok = rt_str
.to_ascii_lowercase()
.contains(&language.to_ascii_lowercase());
if ok || language.is_empty() {
println!(" ARN: {}", function.function_arn().unwrap());
println!(" Runtime: {}", rt_str);
println!();
num_functions += 1;
}
}
if num_functions > 0 || verbose {
println!(
"Found {} function(s) (out of {}) in {} region.",
num_functions, max_functions, reg
);
println!();
}
}
// snippet-end:[lambda.rust.list-all-function-runtimes]
/// Lists the ARNs and runtimes of your Lambda functions in all available regions.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
language,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", aws_sdk_ec2::PKG_VERSION);
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}
// Get list of available regions.
let shared_config = aws_config::from_env().region(region_provider).load().await;
let ec2_client = aws_sdk_ec2::Client::new(&shared_config);
let resp = ec2_client.describe_regions().send().await;
for region in resp.unwrap().regions.unwrap_or_default() {
let reg: &'static str = Box::leak(region.region_name.unwrap().into_boxed_str());
show_lambdas(verbose, language.as_deref().unwrap_or_default(), reg).await;
}
Ok(())
}
|
show_lambdas
|
identifier_name
|
list-all-function-runtimes.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region in which the client is created.
#[structopt(short, long)]
region: Option<String>,
/// Just show runtimes for indicated language.
/// dotnet, go, node, java, etc.
#[structopt(short, long)]
language: Option<String>,
/// Whether to display additional runtime information.
#[structopt(short, long)]
verbose: bool,
}
/// Lists the ARNs and runtimes of all Lambda functions in all Regions.
// snippet-start:[lambda.rust.list-all-function-runtimes]
async fn show_lambdas(verbose: bool, language: &str, reg: &'static str) {
let region_provider = RegionProviderChain::default_provider().or_else(reg);
let config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&config);
let resp = client.list_functions().send().await;
let functions = resp.unwrap().functions.unwrap_or_default();
let max_functions = functions.len();
let mut num_functions = 0;
for function in functions {
let rt_str: String = String::from(function.runtime().unwrap().as_ref());
// If language is set (!= ""), show only those with that runtime.
let ok = rt_str
.to_ascii_lowercase()
.contains(&language.to_ascii_lowercase());
if ok || language.is_empty()
|
}
if num_functions > 0 || verbose {
println!(
"Found {} function(s) (out of {}) in {} region.",
num_functions, max_functions, reg
);
println!();
}
}
// snippet-end:[lambda.rust.list-all-function-runtimes]
/// Lists the ARNs and runtimes of your Lambda functions in all available regions.
/// # Arguments
///
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
language,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", aws_sdk_ec2::PKG_VERSION);
println!("Lambda client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}
// Get list of available regions.
let shared_config = aws_config::from_env().region(region_provider).load().await;
let ec2_client = aws_sdk_ec2::Client::new(&shared_config);
let resp = ec2_client.describe_regions().send().await;
for region in resp.unwrap().regions.unwrap_or_default() {
let reg: &'static str = Box::leak(region.region_name.unwrap().into_boxed_str());
show_lambdas(verbose, language.as_deref().unwrap_or_default(), reg).await;
}
Ok(())
}
|
{
println!(" ARN: {}", function.function_arn().unwrap());
println!(" Runtime: {}", rt_str);
println!();
num_functions += 1;
}
|
conditional_block
|
htmlfieldsetelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods;
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::js::{Root, RootedReference};
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmllegendelement::HTMLLegendElement;
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use util::str::{DOMString, StaticStringVec};
#[dom_struct]
pub struct HTMLFieldSetElement {
htmlelement: HTMLElement
}
impl HTMLFieldSetElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLFieldSetElement {
HTMLFieldSetElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFieldSetElement> {
let element = HTMLFieldSetElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap)
}
}
impl HTMLFieldSetElementMethods for HTMLFieldSetElement {
// https://html.spec.whatwg.org/multipage/#dom-fieldset-elements
fn Elements(&self) -> Root<HTMLCollection>
|
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLFieldSetElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
// Fieldset was already disabled before.
return;
},
AttributeMutation::Removed => false,
};
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
el.set_disabled_state(disabled_state);
el.set_enabled_state(!disabled_state);
let mut found_legend = false;
let children = node.children().filter(|node| {
if found_legend {
true
} else if node.is::<HTMLLegendElement>() {
found_legend = true;
false
} else {
true
}
});
let fields = children.flat_map(|child| {
child.traverse_preorder().filter(|descendant| {
match descendant.type_id() {
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTextAreaElement)) => {
true
},
_ => false,
}
})
});
if disabled_state {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.set_disabled_state(true);
el.set_enabled_state(false);
}
} else {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.check_disabled_attribute();
el.check_ancestors_disabled_state_for_form_control();
}
}
},
_ => {},
}
}
}
impl FormControl for HTMLFieldSetElement {}
|
{
#[derive(JSTraceable, HeapSizeOf)]
struct ElementsFilter;
impl CollectionFilter for ElementsFilter {
fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool {
static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input",
"keygen", "object", "output", "select", "textarea"];
TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name())
}
}
let filter = box ElementsFilter;
let window = window_from_node(self);
HTMLCollection::create(window.r(), self.upcast(), filter)
}
|
identifier_body
|
htmlfieldsetelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods;
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::js::{Root, RootedReference};
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmllegendelement::HTMLLegendElement;
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use util::str::{DOMString, StaticStringVec};
#[dom_struct]
pub struct HTMLFieldSetElement {
htmlelement: HTMLElement
}
impl HTMLFieldSetElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLFieldSetElement {
HTMLFieldSetElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFieldSetElement> {
let element = HTMLFieldSetElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap)
}
}
impl HTMLFieldSetElementMethods for HTMLFieldSetElement {
// https://html.spec.whatwg.org/multipage/#dom-fieldset-elements
fn Elements(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct ElementsFilter;
impl CollectionFilter for ElementsFilter {
fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool {
static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input",
"keygen", "object", "output", "select", "textarea"];
TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name())
}
}
let filter = box ElementsFilter;
let window = window_from_node(self);
HTMLCollection::create(window.r(), self.upcast(), filter)
}
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLFieldSetElement {
fn
|
(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
// Fieldset was already disabled before.
return;
},
AttributeMutation::Removed => false,
};
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
el.set_disabled_state(disabled_state);
el.set_enabled_state(!disabled_state);
let mut found_legend = false;
let children = node.children().filter(|node| {
if found_legend {
true
} else if node.is::<HTMLLegendElement>() {
found_legend = true;
false
} else {
true
}
});
let fields = children.flat_map(|child| {
child.traverse_preorder().filter(|descendant| {
match descendant.type_id() {
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTextAreaElement)) => {
true
},
_ => false,
}
})
});
if disabled_state {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.set_disabled_state(true);
el.set_enabled_state(false);
}
} else {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.check_disabled_attribute();
el.check_ancestors_disabled_state_for_form_control();
}
}
},
_ => {},
}
}
}
impl FormControl for HTMLFieldSetElement {}
|
super_type
|
identifier_name
|
htmlfieldsetelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods;
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::js::{Root, RootedReference};
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmllegendelement::HTMLLegendElement;
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use util::str::{DOMString, StaticStringVec};
#[dom_struct]
pub struct HTMLFieldSetElement {
htmlelement: HTMLElement
}
impl HTMLFieldSetElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLFieldSetElement {
HTMLFieldSetElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFieldSetElement> {
let element = HTMLFieldSetElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap)
}
}
impl HTMLFieldSetElementMethods for HTMLFieldSetElement {
// https://html.spec.whatwg.org/multipage/#dom-fieldset-elements
fn Elements(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct ElementsFilter;
impl CollectionFilter for ElementsFilter {
fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool {
static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input",
"keygen", "object", "output", "select", "textarea"];
TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name())
}
}
let filter = box ElementsFilter;
let window = window_from_node(self);
HTMLCollection::create(window.r(), self.upcast(), filter)
}
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLFieldSetElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
// Fieldset was already disabled before.
return;
},
AttributeMutation::Removed => false,
};
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
el.set_disabled_state(disabled_state);
el.set_enabled_state(!disabled_state);
let mut found_legend = false;
let children = node.children().filter(|node| {
if found_legend {
true
} else if node.is::<HTMLLegendElement>() {
found_legend = true;
false
} else {
true
}
});
let fields = children.flat_map(|child| {
child.traverse_preorder().filter(|descendant| {
match descendant.type_id() {
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLButtonElement)) |
|
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTextAreaElement)) => {
true
},
_ => false,
}
})
});
if disabled_state {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.set_disabled_state(true);
el.set_enabled_state(false);
}
} else {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.check_disabled_attribute();
el.check_ancestors_disabled_state_for_form_control();
}
}
},
_ => {},
}
}
}
impl FormControl for HTMLFieldSetElement {}
|
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLInputElement)) |
|
random_line_split
|
line.rs
|
use super::prelude::*;
use super::{BaseFloat, NumCast, Pnt2, Vec2};
#[derive(Copy, Clone, Debug)]
pub struct Line2<T: BaseFloat> {
pub origin: Pnt2<T>,
pub displace: Vec2<T>,
pub length: T,
}
impl<T: BaseFloat> Line2<T> {
pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> {
let length = displace.magnitude();
if length.abs() >= <T as NumCast>::from(1e-16).unwrap() {
Line2 {
origin,
displace: displace / length,
length,
}
} else {
Line2 {
origin,
displace: Vec2::zero(),
length: T::zero(),
}
}
}
pub fn from_two_points(origin: Pnt2<T>, towards: Pnt2<T>) -> Line2<T> {
Self::from_origin_and_displace(origin, towards - origin)
}
pub fn inverted_halfspaces(&self) -> Line2<T> {
Line2 {
origin: self.origin,
displace: -self.displace,
length: self.length,
}
}
pub fn signed_distance(&self, to: Pnt2<T>) -> T {
to.to_vec().perp_dot(self.displace) + self.displace.perp_dot(self.origin.to_vec())
}
pub fn segment_intersect_offset(&self, other: &Line2<T>) -> Option<T> {
self.intersect_offset(other).and_then(|offset| {
if offset < T::zero() || offset >= self.length {
return None;
}
let other_offset = other.offset_at(self.at_offset(offset));
if other_offset < T::zero() || other_offset >= other.length {
return None;
}
Some(offset)
})
}
pub fn offset_at(&self, point: Pnt2<T>) -> T {
if self.displace.x.abs() > self.displace.y.abs() {
(point.x - self.origin.x) / self.displace.x
} else {
(point.y - self.origin.y) / self.displace.y
}
}
pub fn intersect_offset(&self, other: &Line2<T>) -> Option<T> {
let denominator = self.displace.perp_dot(other.displace);
if denominator.abs() < <T as NumCast>::from(1e-16).unwrap() {
None
} else {
Some((other.origin - self.origin).perp_dot(other.displace) / denominator)
}
}
pub fn intersect_point(&self, other: &Line2<T>) -> Option<Pnt2<T>>
|
pub fn at_offset(&self, offset: T) -> Pnt2<T> {
self.origin + self.displace * offset
}
}
|
{
self.intersect_offset(other)
.map(|offset| self.at_offset(offset))
}
|
identifier_body
|
line.rs
|
use super::prelude::*;
use super::{BaseFloat, NumCast, Pnt2, Vec2};
#[derive(Copy, Clone, Debug)]
pub struct Line2<T: BaseFloat> {
pub origin: Pnt2<T>,
pub displace: Vec2<T>,
pub length: T,
}
impl<T: BaseFloat> Line2<T> {
pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> {
let length = displace.magnitude();
if length.abs() >= <T as NumCast>::from(1e-16).unwrap() {
Line2 {
origin,
displace: displace / length,
length,
}
} else {
Line2 {
origin,
displace: Vec2::zero(),
length: T::zero(),
}
}
}
pub fn from_two_points(origin: Pnt2<T>, towards: Pnt2<T>) -> Line2<T> {
Self::from_origin_and_displace(origin, towards - origin)
}
pub fn inverted_halfspaces(&self) -> Line2<T> {
Line2 {
origin: self.origin,
displace: -self.displace,
length: self.length,
}
}
pub fn signed_distance(&self, to: Pnt2<T>) -> T {
to.to_vec().perp_dot(self.displace) + self.displace.perp_dot(self.origin.to_vec())
}
pub fn segment_intersect_offset(&self, other: &Line2<T>) -> Option<T> {
self.intersect_offset(other).and_then(|offset| {
if offset < T::zero() || offset >= self.length {
return None;
}
let other_offset = other.offset_at(self.at_offset(offset));
if other_offset < T::zero() || other_offset >= other.length {
return None;
}
Some(offset)
})
}
pub fn offset_at(&self, point: Pnt2<T>) -> T {
if self.displace.x.abs() > self.displace.y.abs() {
(point.x - self.origin.x) / self.displace.x
} else {
(point.y - self.origin.y) / self.displace.y
}
}
pub fn intersect_offset(&self, other: &Line2<T>) -> Option<T> {
let denominator = self.displace.perp_dot(other.displace);
if denominator.abs() < <T as NumCast>::from(1e-16).unwrap() {
None
} else {
Some((other.origin - self.origin).perp_dot(other.displace) / denominator)
}
}
pub fn
|
(&self, other: &Line2<T>) -> Option<Pnt2<T>> {
self.intersect_offset(other)
.map(|offset| self.at_offset(offset))
}
pub fn at_offset(&self, offset: T) -> Pnt2<T> {
self.origin + self.displace * offset
}
}
|
intersect_point
|
identifier_name
|
line.rs
|
use super::prelude::*;
use super::{BaseFloat, NumCast, Pnt2, Vec2};
#[derive(Copy, Clone, Debug)]
pub struct Line2<T: BaseFloat> {
pub origin: Pnt2<T>,
pub displace: Vec2<T>,
pub length: T,
}
impl<T: BaseFloat> Line2<T> {
pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> {
let length = displace.magnitude();
if length.abs() >= <T as NumCast>::from(1e-16).unwrap() {
Line2 {
origin,
displace: displace / length,
length,
}
} else {
Line2 {
origin,
displace: Vec2::zero(),
length: T::zero(),
}
}
}
pub fn from_two_points(origin: Pnt2<T>, towards: Pnt2<T>) -> Line2<T> {
Self::from_origin_and_displace(origin, towards - origin)
}
pub fn inverted_halfspaces(&self) -> Line2<T> {
Line2 {
origin: self.origin,
displace: -self.displace,
length: self.length,
}
}
pub fn signed_distance(&self, to: Pnt2<T>) -> T {
to.to_vec().perp_dot(self.displace) + self.displace.perp_dot(self.origin.to_vec())
}
pub fn segment_intersect_offset(&self, other: &Line2<T>) -> Option<T> {
self.intersect_offset(other).and_then(|offset| {
if offset < T::zero() || offset >= self.length {
return None;
}
let other_offset = other.offset_at(self.at_offset(offset));
if other_offset < T::zero() || other_offset >= other.length {
return None;
}
Some(offset)
})
}
pub fn offset_at(&self, point: Pnt2<T>) -> T {
if self.displace.x.abs() > self.displace.y.abs() {
(point.x - self.origin.x) / self.displace.x
} else {
(point.y - self.origin.y) / self.displace.y
}
}
pub fn intersect_offset(&self, other: &Line2<T>) -> Option<T> {
let denominator = self.displace.perp_dot(other.displace);
if denominator.abs() < <T as NumCast>::from(1e-16).unwrap() {
None
|
}
}
pub fn intersect_point(&self, other: &Line2<T>) -> Option<Pnt2<T>> {
self.intersect_offset(other)
.map(|offset| self.at_offset(offset))
}
pub fn at_offset(&self, offset: T) -> Pnt2<T> {
self.origin + self.displace * offset
}
}
|
} else {
Some((other.origin - self.origin).perp_dot(other.displace) / denominator)
|
random_line_split
|
line.rs
|
use super::prelude::*;
use super::{BaseFloat, NumCast, Pnt2, Vec2};
#[derive(Copy, Clone, Debug)]
pub struct Line2<T: BaseFloat> {
pub origin: Pnt2<T>,
pub displace: Vec2<T>,
pub length: T,
}
impl<T: BaseFloat> Line2<T> {
pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> {
let length = displace.magnitude();
if length.abs() >= <T as NumCast>::from(1e-16).unwrap() {
Line2 {
origin,
displace: displace / length,
length,
}
} else {
Line2 {
origin,
displace: Vec2::zero(),
length: T::zero(),
}
}
}
pub fn from_two_points(origin: Pnt2<T>, towards: Pnt2<T>) -> Line2<T> {
Self::from_origin_and_displace(origin, towards - origin)
}
pub fn inverted_halfspaces(&self) -> Line2<T> {
Line2 {
origin: self.origin,
displace: -self.displace,
length: self.length,
}
}
pub fn signed_distance(&self, to: Pnt2<T>) -> T {
to.to_vec().perp_dot(self.displace) + self.displace.perp_dot(self.origin.to_vec())
}
pub fn segment_intersect_offset(&self, other: &Line2<T>) -> Option<T> {
self.intersect_offset(other).and_then(|offset| {
if offset < T::zero() || offset >= self.length {
return None;
}
let other_offset = other.offset_at(self.at_offset(offset));
if other_offset < T::zero() || other_offset >= other.length {
return None;
}
Some(offset)
})
}
pub fn offset_at(&self, point: Pnt2<T>) -> T {
if self.displace.x.abs() > self.displace.y.abs()
|
else {
(point.y - self.origin.y) / self.displace.y
}
}
pub fn intersect_offset(&self, other: &Line2<T>) -> Option<T> {
let denominator = self.displace.perp_dot(other.displace);
if denominator.abs() < <T as NumCast>::from(1e-16).unwrap() {
None
} else {
Some((other.origin - self.origin).perp_dot(other.displace) / denominator)
}
}
pub fn intersect_point(&self, other: &Line2<T>) -> Option<Pnt2<T>> {
self.intersect_offset(other)
.map(|offset| self.at_offset(offset))
}
pub fn at_offset(&self, offset: T) -> Pnt2<T> {
self.origin + self.displace * offset
}
}
|
{
(point.x - self.origin.x) / self.displace.x
}
|
conditional_block
|
struct-in-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print three_simple_structs
// check:$1 = {x = {x = 1}, y = {x = 2}, z = {x = 3}}
// debugger:print internal_padding_parent
// check:$2 = {x = {x = 4, y = 5}, y = {x = 6, y = 7}, z = {x = 8, y = 9}}
// debugger:print padding_at_end_parent
// check:$3 = {x = {x = 10, y = 11}, y = {x = 12, y = 13}, z = {x = 14, y = 15}}
#[allow(unused_variable)];
struct Simple {
x: i32
}
struct InternalPadding {
x: i32,
y: i64
}
struct PaddingAtEnd {
x: i64,
y: i32
}
struct ThreeSimpleStructs {
x: Simple,
y: Simple,
z: Simple
}
struct InternalPaddingParent {
x: InternalPadding,
y: InternalPadding,
z: InternalPadding
}
struct PaddingAtEndParent {
x: PaddingAtEnd,
y: PaddingAtEnd,
z: PaddingAtEnd
}
struct Mixed {
x: PaddingAtEnd,
y: InternalPadding,
z: Simple,
w: i16
}
struct Bag {
x: Simple
}
struct BagInBag {
x: Bag
}
struct ThatsJustOverkill {
x: BagInBag
}
struct Tree {
x: Simple,
y: InternalPaddingParent,
z: BagInBag
}
fn main() {
let three_simple_structs = ThreeSimpleStructs {
x: Simple { x: 1 },
y: Simple { x: 2 },
z: Simple { x: 3 }
};
let internal_padding_parent = InternalPaddingParent {
x: InternalPadding { x: 4, y: 5 },
y: InternalPadding { x: 6, y: 7 },
z: InternalPadding { x: 8, y: 9 }
};
let padding_at_end_parent = PaddingAtEndParent {
x: PaddingAtEnd { x: 10, y: 11 },
y: PaddingAtEnd { x: 12, y: 13 },
z: PaddingAtEnd { x: 14, y: 15 }
};
let mixed = Mixed {
x: PaddingAtEnd { x: 16, y: 17 },
y: InternalPadding { x: 18, y: 19 },
z: Simple { x: 20 },
w: 21
};
let bag = Bag { x: Simple { x: 22 } };
let bag_in_bag = BagInBag {
x: Bag {
x: Simple { x: 23 }
}
};
let tjo = ThatsJustOverkill {
x: BagInBag {
x: Bag {
x: Simple { x: 24 }
}
}
};
let tree = Tree {
x: Simple { x: 25 },
y: InternalPaddingParent {
x: InternalPadding { x: 26, y: 27 },
y: InternalPadding { x: 28, y: 29 },
z: InternalPadding { x: 30, y: 31 }
},
z: BagInBag {
x: Bag {
x: Simple { x: 32 }
}
|
};
zzz();
}
fn zzz() {()}
|
}
|
random_line_split
|
struct-in-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print three_simple_structs
// check:$1 = {x = {x = 1}, y = {x = 2}, z = {x = 3}}
// debugger:print internal_padding_parent
// check:$2 = {x = {x = 4, y = 5}, y = {x = 6, y = 7}, z = {x = 8, y = 9}}
// debugger:print padding_at_end_parent
// check:$3 = {x = {x = 10, y = 11}, y = {x = 12, y = 13}, z = {x = 14, y = 15}}
#[allow(unused_variable)];
struct Simple {
x: i32
}
struct InternalPadding {
x: i32,
y: i64
}
struct PaddingAtEnd {
x: i64,
y: i32
}
struct ThreeSimpleStructs {
x: Simple,
y: Simple,
z: Simple
}
struct
|
{
x: InternalPadding,
y: InternalPadding,
z: InternalPadding
}
struct PaddingAtEndParent {
x: PaddingAtEnd,
y: PaddingAtEnd,
z: PaddingAtEnd
}
struct Mixed {
x: PaddingAtEnd,
y: InternalPadding,
z: Simple,
w: i16
}
struct Bag {
x: Simple
}
struct BagInBag {
x: Bag
}
struct ThatsJustOverkill {
x: BagInBag
}
struct Tree {
x: Simple,
y: InternalPaddingParent,
z: BagInBag
}
fn main() {
let three_simple_structs = ThreeSimpleStructs {
x: Simple { x: 1 },
y: Simple { x: 2 },
z: Simple { x: 3 }
};
let internal_padding_parent = InternalPaddingParent {
x: InternalPadding { x: 4, y: 5 },
y: InternalPadding { x: 6, y: 7 },
z: InternalPadding { x: 8, y: 9 }
};
let padding_at_end_parent = PaddingAtEndParent {
x: PaddingAtEnd { x: 10, y: 11 },
y: PaddingAtEnd { x: 12, y: 13 },
z: PaddingAtEnd { x: 14, y: 15 }
};
let mixed = Mixed {
x: PaddingAtEnd { x: 16, y: 17 },
y: InternalPadding { x: 18, y: 19 },
z: Simple { x: 20 },
w: 21
};
let bag = Bag { x: Simple { x: 22 } };
let bag_in_bag = BagInBag {
x: Bag {
x: Simple { x: 23 }
}
};
let tjo = ThatsJustOverkill {
x: BagInBag {
x: Bag {
x: Simple { x: 24 }
}
}
};
let tree = Tree {
x: Simple { x: 25 },
y: InternalPaddingParent {
x: InternalPadding { x: 26, y: 27 },
y: InternalPadding { x: 28, y: 29 },
z: InternalPadding { x: 30, y: 31 }
},
z: BagInBag {
x: Bag {
x: Simple { x: 32 }
}
}
};
zzz();
}
fn zzz() {()}
|
InternalPaddingParent
|
identifier_name
|
slice-mut-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test mutability and slicing syntax.
fn
|
() {
let x: &[isize] = &[1, 2, 3, 4, 5];
// Can't mutably slice an immutable slice
let slice: &mut [isize] = &mut [0, 1];
let _ = &mut x[2..4]; //~ERROR cannot borrow immutable borrowed content `*x` as mutable
}
|
main
|
identifier_name
|
slice-mut-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test mutability and slicing syntax.
fn main()
|
{
let x: &[isize] = &[1, 2, 3, 4, 5];
// Can't mutably slice an immutable slice
let slice: &mut [isize] = &mut [0, 1];
let _ = &mut x[2..4]; //~ERROR cannot borrow immutable borrowed content `*x` as mutable
}
|
identifier_body
|
|
slice-mut-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test mutability and slicing syntax.
fn main() {
let x: &[isize] = &[1, 2, 3, 4, 5];
// Can't mutably slice an immutable slice
let slice: &mut [isize] = &mut [0, 1];
let _ = &mut x[2..4]; //~ERROR cannot borrow immutable borrowed content `*x` as mutable
}
|
// 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
|
random_line_split
|
authorization.rs
|
use std::any::Any;
use std::fmt::{self, Display};
use std::str::{FromStr, from_utf8};
use std::ops::{Deref, DerefMut};
use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline};
use header::{Header, HeaderFormat};
/// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.2)
///
/// The `Authorization` header field allows a user agent to authenticate
/// itself with an origin server -- usually, but not necessarily, after
/// receiving a 401 (Unauthorized) response. Its value consists of
/// credentials containing the authentication information of the user
/// agent for the realm of the resource being requested.
///
/// # ABNF
/// ```plain
/// Authorization = credentials
/// ```
///
/// # Example values
/// * `Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
/// * `Bearer fpKL54jvWmEGVoRdCNjG`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Authorization};
///
/// let mut headers = Headers::new();
/// headers.set(Authorization("let me in".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, Authorization, Basic};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Authorization(
/// Basic {
/// username: "Aladdin".to_owned(),
/// password: Some("open sesame".to_owned())
/// }
/// )
/// );
/// ```
/// ```
/// use hyper::header::{Headers, Authorization, Bearer};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Authorization(
/// Bearer {
/// token: "QWxhZGRpbjpvcGVuIHNlc2FtZQ".to_owned()
/// }
/// )
/// );
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct Authorization<S: Scheme>(pub S);
impl<S: Scheme> Deref for Authorization<S> {
type Target = S;
fn deref<'a>(&'a self) -> &'a S {
&self.0
}
}
impl<S: Scheme> DerefMut for Authorization<S> {
fn deref_mut<'a>(&'a mut self) -> &'a mut S {
&mut self.0
}
}
impl<S: Scheme + Any> Header for Authorization<S> where <S as FromStr>::Err:'static {
fn header_name() -> &'static str {
"Authorization"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<Authorization<S>> {
if raw.len()!= 1 {
return Err(::Error::Header);
}
let header = try!(from_utf8(unsafe { &raw.get_unchecked(0)[..] }));
return if let Some(scheme) = <S as Scheme>::scheme() {
if header.starts_with(scheme) && header.len() > scheme.len() + 1 {
match header[scheme.len() + 1..].parse::<S>().map(Authorization) {
Ok(h) => Ok(h),
Err(_) => Err(::Error::Header)
}
} else {
Err(::Error::Header)
}
} else {
match header.parse::<S>().map(Authorization) {
Ok(h) => Ok(h),
Err(_) => Err(::Error::Header)
}
}
}
}
impl<S: Scheme + Any> HeaderFormat for Authorization<S> where <S as FromStr>::Err:'static {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(scheme) = <S as Scheme>::scheme() {
try!(write!(f, "{} ", scheme))
};
self.0.fmt_scheme(f)
}
}
/// An Authorization scheme to be used in the header.
pub trait Scheme: FromStr + fmt::Debug + Clone + Send + Sync {
/// An optional Scheme name.
///
/// Will be replaced with an associated constant once available.
fn scheme() -> Option<&'static str>;
/// Format the Scheme data into a header value.
fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result;
}
impl Scheme for String {
|
None
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
/// Credential holder for Basic Authentication
#[derive(Clone, PartialEq, Debug)]
pub struct Basic {
/// The username as a possibly empty string
pub username: String,
/// The password. `None` if the `:` delimiter character was not
/// part of the parsed input.
pub password: Option<String>
}
impl Scheme for Basic {
fn scheme() -> Option<&'static str> {
Some("Basic")
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
//FIXME: serialize::base64 could use some Debug implementation, so
//that we don't have to allocate a new string here just to write it
//to the formatter.
let mut text = self.username.clone();
text.push(':');
if let Some(ref pass) = self.password {
text.push_str(&pass[..]);
}
f.write_str(&text.as_bytes().to_base64(Config {
char_set: Standard,
newline: Newline::CRLF,
pad: true,
line_length: None
})[..])
}
}
impl FromStr for Basic {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Basic> {
match s.from_base64() {
Ok(decoded) => match String::from_utf8(decoded) {
Ok(text) => {
let mut parts = &mut text.split(':');
let user = match parts.next() {
Some(part) => part.to_owned(),
None => return Err(::Error::Header)
};
let password = match parts.next() {
Some(part) => Some(part.to_owned()),
None => None
};
Ok(Basic {
username: user,
password: password
})
},
Err(e) => {
debug!("Basic::from_utf8 error={:?}", e);
Err(::Error::Header)
}
},
Err(e) => {
debug!("Basic::from_base64 error={:?}", e);
Err(::Error::Header)
}
}
}
}
#[derive(Clone, PartialEq, Debug)]
///Token holder for Bearer Authentication, most often seen with oauth
pub struct Bearer {
///Actual bearer token as a string
pub token: String
}
impl Scheme for Bearer {
fn scheme() -> Option<&'static str> {
Some("Bearer")
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.token)
}
}
impl FromStr for Bearer {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Bearer> {
Ok(Bearer { token: s.to_owned()})
}
}
#[cfg(test)]
mod tests {
use super::{Authorization, Basic, Bearer};
use super::super::super::{Headers, Header};
#[test]
fn test_raw_auth() {
let mut headers = Headers::new();
headers.set(Authorization("foo bar baz".to_owned()));
assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_owned());
}
#[test]
fn test_raw_auth_parse() {
let header: Authorization<String> = Header::parse_header(
&[b"foo bar baz".to_vec()]).unwrap();
assert_eq!(header.0, "foo bar baz");
}
#[test]
fn test_basic_auth() {
let mut headers = Headers::new();
headers.set(Authorization(
Basic { username: "Aladdin".to_owned(), password: Some("open sesame".to_owned()) }));
assert_eq!(
headers.to_string(),
"Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_owned());
}
#[test]
fn test_basic_auth_no_password() {
let mut headers = Headers::new();
headers.set(Authorization(Basic { username: "Aladdin".to_owned(), password: None }));
assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_owned());
}
#[test]
fn test_basic_auth_parse() {
let auth: Authorization<Basic> = Header::parse_header(
&[b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()]).unwrap();
assert_eq!(auth.0.username, "Aladdin");
assert_eq!(auth.0.password, Some("open sesame".to_owned()));
}
#[test]
fn test_basic_auth_parse_no_password() {
let auth: Authorization<Basic> = Header::parse_header(
&[b"Basic QWxhZGRpbjo=".to_vec()]).unwrap();
assert_eq!(auth.0.username, "Aladdin");
assert_eq!(auth.0.password, Some("".to_owned()));
}
#[test]
fn test_bearer_auth() {
let mut headers = Headers::new();
headers.set(Authorization(
Bearer { token: "fpKL54jvWmEGVoRdCNjG".to_owned() }));
assert_eq!(
headers.to_string(),
"Authorization: Bearer fpKL54jvWmEGVoRdCNjG\r\n".to_owned());
}
#[test]
fn test_bearer_auth_parse() {
let auth: Authorization<Bearer> = Header::parse_header(
&[b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()]).unwrap();
assert_eq!(auth.0.token, "fpKL54jvWmEGVoRdCNjG");
}
}
bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] });
bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpuIHNlc2FtZQ==".to_vec()] });
bench_header!(bearer, Authorization<Bearer>, { vec![b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()] });
|
fn scheme() -> Option<&'static str> {
|
random_line_split
|
authorization.rs
|
use std::any::Any;
use std::fmt::{self, Display};
use std::str::{FromStr, from_utf8};
use std::ops::{Deref, DerefMut};
use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline};
use header::{Header, HeaderFormat};
/// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.2)
///
/// The `Authorization` header field allows a user agent to authenticate
/// itself with an origin server -- usually, but not necessarily, after
/// receiving a 401 (Unauthorized) response. Its value consists of
/// credentials containing the authentication information of the user
/// agent for the realm of the resource being requested.
///
/// # ABNF
/// ```plain
/// Authorization = credentials
/// ```
///
/// # Example values
/// * `Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
/// * `Bearer fpKL54jvWmEGVoRdCNjG`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Authorization};
///
/// let mut headers = Headers::new();
/// headers.set(Authorization("let me in".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, Authorization, Basic};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Authorization(
/// Basic {
/// username: "Aladdin".to_owned(),
/// password: Some("open sesame".to_owned())
/// }
/// )
/// );
/// ```
/// ```
/// use hyper::header::{Headers, Authorization, Bearer};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Authorization(
/// Bearer {
/// token: "QWxhZGRpbjpvcGVuIHNlc2FtZQ".to_owned()
/// }
/// )
/// );
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct Authorization<S: Scheme>(pub S);
impl<S: Scheme> Deref for Authorization<S> {
type Target = S;
fn deref<'a>(&'a self) -> &'a S {
&self.0
}
}
impl<S: Scheme> DerefMut for Authorization<S> {
fn deref_mut<'a>(&'a mut self) -> &'a mut S {
&mut self.0
}
}
impl<S: Scheme + Any> Header for Authorization<S> where <S as FromStr>::Err:'static {
fn header_name() -> &'static str {
"Authorization"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<Authorization<S>> {
if raw.len()!= 1 {
return Err(::Error::Header);
}
let header = try!(from_utf8(unsafe { &raw.get_unchecked(0)[..] }));
return if let Some(scheme) = <S as Scheme>::scheme() {
if header.starts_with(scheme) && header.len() > scheme.len() + 1 {
match header[scheme.len() + 1..].parse::<S>().map(Authorization) {
Ok(h) => Ok(h),
Err(_) => Err(::Error::Header)
}
} else {
Err(::Error::Header)
}
} else {
match header.parse::<S>().map(Authorization) {
Ok(h) => Ok(h),
Err(_) => Err(::Error::Header)
}
}
}
}
impl<S: Scheme + Any> HeaderFormat for Authorization<S> where <S as FromStr>::Err:'static {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(scheme) = <S as Scheme>::scheme() {
try!(write!(f, "{} ", scheme))
};
self.0.fmt_scheme(f)
}
}
/// An Authorization scheme to be used in the header.
pub trait Scheme: FromStr + fmt::Debug + Clone + Send + Sync {
/// An optional Scheme name.
///
/// Will be replaced with an associated constant once available.
fn scheme() -> Option<&'static str>;
/// Format the Scheme data into a header value.
fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result;
}
impl Scheme for String {
fn scheme() -> Option<&'static str> {
None
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
/// Credential holder for Basic Authentication
#[derive(Clone, PartialEq, Debug)]
pub struct Basic {
/// The username as a possibly empty string
pub username: String,
/// The password. `None` if the `:` delimiter character was not
/// part of the parsed input.
pub password: Option<String>
}
impl Scheme for Basic {
fn scheme() -> Option<&'static str> {
Some("Basic")
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
//FIXME: serialize::base64 could use some Debug implementation, so
//that we don't have to allocate a new string here just to write it
//to the formatter.
let mut text = self.username.clone();
text.push(':');
if let Some(ref pass) = self.password {
text.push_str(&pass[..]);
}
f.write_str(&text.as_bytes().to_base64(Config {
char_set: Standard,
newline: Newline::CRLF,
pad: true,
line_length: None
})[..])
}
}
impl FromStr for Basic {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Basic> {
match s.from_base64() {
Ok(decoded) => match String::from_utf8(decoded) {
Ok(text) => {
let mut parts = &mut text.split(':');
let user = match parts.next() {
Some(part) => part.to_owned(),
None => return Err(::Error::Header)
};
let password = match parts.next() {
Some(part) => Some(part.to_owned()),
None => None
};
Ok(Basic {
username: user,
password: password
})
},
Err(e) => {
debug!("Basic::from_utf8 error={:?}", e);
Err(::Error::Header)
}
},
Err(e) => {
debug!("Basic::from_base64 error={:?}", e);
Err(::Error::Header)
}
}
}
}
#[derive(Clone, PartialEq, Debug)]
///Token holder for Bearer Authentication, most often seen with oauth
pub struct Bearer {
///Actual bearer token as a string
pub token: String
}
impl Scheme for Bearer {
fn scheme() -> Option<&'static str> {
Some("Bearer")
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.token)
}
}
impl FromStr for Bearer {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Bearer> {
Ok(Bearer { token: s.to_owned()})
}
}
#[cfg(test)]
mod tests {
use super::{Authorization, Basic, Bearer};
use super::super::super::{Headers, Header};
#[test]
fn test_raw_auth() {
let mut headers = Headers::new();
headers.set(Authorization("foo bar baz".to_owned()));
assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_owned());
}
#[test]
fn test_raw_auth_parse() {
let header: Authorization<String> = Header::parse_header(
&[b"foo bar baz".to_vec()]).unwrap();
assert_eq!(header.0, "foo bar baz");
}
#[test]
fn test_basic_auth() {
let mut headers = Headers::new();
headers.set(Authorization(
Basic { username: "Aladdin".to_owned(), password: Some("open sesame".to_owned()) }));
assert_eq!(
headers.to_string(),
"Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_owned());
}
#[test]
fn test_basic_auth_no_password()
|
#[test]
fn test_basic_auth_parse() {
let auth: Authorization<Basic> = Header::parse_header(
&[b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()]).unwrap();
assert_eq!(auth.0.username, "Aladdin");
assert_eq!(auth.0.password, Some("open sesame".to_owned()));
}
#[test]
fn test_basic_auth_parse_no_password() {
let auth: Authorization<Basic> = Header::parse_header(
&[b"Basic QWxhZGRpbjo=".to_vec()]).unwrap();
assert_eq!(auth.0.username, "Aladdin");
assert_eq!(auth.0.password, Some("".to_owned()));
}
#[test]
fn test_bearer_auth() {
let mut headers = Headers::new();
headers.set(Authorization(
Bearer { token: "fpKL54jvWmEGVoRdCNjG".to_owned() }));
assert_eq!(
headers.to_string(),
"Authorization: Bearer fpKL54jvWmEGVoRdCNjG\r\n".to_owned());
}
#[test]
fn test_bearer_auth_parse() {
let auth: Authorization<Bearer> = Header::parse_header(
&[b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()]).unwrap();
assert_eq!(auth.0.token, "fpKL54jvWmEGVoRdCNjG");
}
}
bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] });
bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpuIHNlc2FtZQ==".to_vec()] });
bench_header!(bearer, Authorization<Bearer>, { vec![b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()] });
|
{
let mut headers = Headers::new();
headers.set(Authorization(Basic { username: "Aladdin".to_owned(), password: None }));
assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_owned());
}
|
identifier_body
|
authorization.rs
|
use std::any::Any;
use std::fmt::{self, Display};
use std::str::{FromStr, from_utf8};
use std::ops::{Deref, DerefMut};
use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline};
use header::{Header, HeaderFormat};
/// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#section-4.2)
///
/// The `Authorization` header field allows a user agent to authenticate
/// itself with an origin server -- usually, but not necessarily, after
/// receiving a 401 (Unauthorized) response. Its value consists of
/// credentials containing the authentication information of the user
/// agent for the realm of the resource being requested.
///
/// # ABNF
/// ```plain
/// Authorization = credentials
/// ```
///
/// # Example values
/// * `Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==`
/// * `Bearer fpKL54jvWmEGVoRdCNjG`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, Authorization};
///
/// let mut headers = Headers::new();
/// headers.set(Authorization("let me in".to_owned()));
/// ```
/// ```
/// use hyper::header::{Headers, Authorization, Basic};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Authorization(
/// Basic {
/// username: "Aladdin".to_owned(),
/// password: Some("open sesame".to_owned())
/// }
/// )
/// );
/// ```
/// ```
/// use hyper::header::{Headers, Authorization, Bearer};
///
/// let mut headers = Headers::new();
/// headers.set(
/// Authorization(
/// Bearer {
/// token: "QWxhZGRpbjpvcGVuIHNlc2FtZQ".to_owned()
/// }
/// )
/// );
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct
|
<S: Scheme>(pub S);
impl<S: Scheme> Deref for Authorization<S> {
type Target = S;
fn deref<'a>(&'a self) -> &'a S {
&self.0
}
}
impl<S: Scheme> DerefMut for Authorization<S> {
fn deref_mut<'a>(&'a mut self) -> &'a mut S {
&mut self.0
}
}
impl<S: Scheme + Any> Header for Authorization<S> where <S as FromStr>::Err:'static {
fn header_name() -> &'static str {
"Authorization"
}
fn parse_header(raw: &[Vec<u8>]) -> ::Result<Authorization<S>> {
if raw.len()!= 1 {
return Err(::Error::Header);
}
let header = try!(from_utf8(unsafe { &raw.get_unchecked(0)[..] }));
return if let Some(scheme) = <S as Scheme>::scheme() {
if header.starts_with(scheme) && header.len() > scheme.len() + 1 {
match header[scheme.len() + 1..].parse::<S>().map(Authorization) {
Ok(h) => Ok(h),
Err(_) => Err(::Error::Header)
}
} else {
Err(::Error::Header)
}
} else {
match header.parse::<S>().map(Authorization) {
Ok(h) => Ok(h),
Err(_) => Err(::Error::Header)
}
}
}
}
impl<S: Scheme + Any> HeaderFormat for Authorization<S> where <S as FromStr>::Err:'static {
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(scheme) = <S as Scheme>::scheme() {
try!(write!(f, "{} ", scheme))
};
self.0.fmt_scheme(f)
}
}
/// An Authorization scheme to be used in the header.
pub trait Scheme: FromStr + fmt::Debug + Clone + Send + Sync {
/// An optional Scheme name.
///
/// Will be replaced with an associated constant once available.
fn scheme() -> Option<&'static str>;
/// Format the Scheme data into a header value.
fn fmt_scheme(&self, &mut fmt::Formatter) -> fmt::Result;
}
impl Scheme for String {
fn scheme() -> Option<&'static str> {
None
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
/// Credential holder for Basic Authentication
#[derive(Clone, PartialEq, Debug)]
pub struct Basic {
/// The username as a possibly empty string
pub username: String,
/// The password. `None` if the `:` delimiter character was not
/// part of the parsed input.
pub password: Option<String>
}
impl Scheme for Basic {
fn scheme() -> Option<&'static str> {
Some("Basic")
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
//FIXME: serialize::base64 could use some Debug implementation, so
//that we don't have to allocate a new string here just to write it
//to the formatter.
let mut text = self.username.clone();
text.push(':');
if let Some(ref pass) = self.password {
text.push_str(&pass[..]);
}
f.write_str(&text.as_bytes().to_base64(Config {
char_set: Standard,
newline: Newline::CRLF,
pad: true,
line_length: None
})[..])
}
}
impl FromStr for Basic {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Basic> {
match s.from_base64() {
Ok(decoded) => match String::from_utf8(decoded) {
Ok(text) => {
let mut parts = &mut text.split(':');
let user = match parts.next() {
Some(part) => part.to_owned(),
None => return Err(::Error::Header)
};
let password = match parts.next() {
Some(part) => Some(part.to_owned()),
None => None
};
Ok(Basic {
username: user,
password: password
})
},
Err(e) => {
debug!("Basic::from_utf8 error={:?}", e);
Err(::Error::Header)
}
},
Err(e) => {
debug!("Basic::from_base64 error={:?}", e);
Err(::Error::Header)
}
}
}
}
#[derive(Clone, PartialEq, Debug)]
///Token holder for Bearer Authentication, most often seen with oauth
pub struct Bearer {
///Actual bearer token as a string
pub token: String
}
impl Scheme for Bearer {
fn scheme() -> Option<&'static str> {
Some("Bearer")
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.token)
}
}
impl FromStr for Bearer {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Bearer> {
Ok(Bearer { token: s.to_owned()})
}
}
#[cfg(test)]
mod tests {
use super::{Authorization, Basic, Bearer};
use super::super::super::{Headers, Header};
#[test]
fn test_raw_auth() {
let mut headers = Headers::new();
headers.set(Authorization("foo bar baz".to_owned()));
assert_eq!(headers.to_string(), "Authorization: foo bar baz\r\n".to_owned());
}
#[test]
fn test_raw_auth_parse() {
let header: Authorization<String> = Header::parse_header(
&[b"foo bar baz".to_vec()]).unwrap();
assert_eq!(header.0, "foo bar baz");
}
#[test]
fn test_basic_auth() {
let mut headers = Headers::new();
headers.set(Authorization(
Basic { username: "Aladdin".to_owned(), password: Some("open sesame".to_owned()) }));
assert_eq!(
headers.to_string(),
"Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\r\n".to_owned());
}
#[test]
fn test_basic_auth_no_password() {
let mut headers = Headers::new();
headers.set(Authorization(Basic { username: "Aladdin".to_owned(), password: None }));
assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_owned());
}
#[test]
fn test_basic_auth_parse() {
let auth: Authorization<Basic> = Header::parse_header(
&[b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()]).unwrap();
assert_eq!(auth.0.username, "Aladdin");
assert_eq!(auth.0.password, Some("open sesame".to_owned()));
}
#[test]
fn test_basic_auth_parse_no_password() {
let auth: Authorization<Basic> = Header::parse_header(
&[b"Basic QWxhZGRpbjo=".to_vec()]).unwrap();
assert_eq!(auth.0.username, "Aladdin");
assert_eq!(auth.0.password, Some("".to_owned()));
}
#[test]
fn test_bearer_auth() {
let mut headers = Headers::new();
headers.set(Authorization(
Bearer { token: "fpKL54jvWmEGVoRdCNjG".to_owned() }));
assert_eq!(
headers.to_string(),
"Authorization: Bearer fpKL54jvWmEGVoRdCNjG\r\n".to_owned());
}
#[test]
fn test_bearer_auth_parse() {
let auth: Authorization<Bearer> = Header::parse_header(
&[b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()]).unwrap();
assert_eq!(auth.0.token, "fpKL54jvWmEGVoRdCNjG");
}
}
bench_header!(raw, Authorization<String>, { vec![b"foo bar baz".to_vec()] });
bench_header!(basic, Authorization<Basic>, { vec![b"Basic QWxhZGRpbjpuIHNlc2FtZQ==".to_vec()] });
bench_header!(bearer, Authorization<Bearer>, { vec![b"Bearer fpKL54jvWmEGVoRdCNjG".to_vec()] });
|
Authorization
|
identifier_name
|
mod.rs
|
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use std::collections::HashSet;
use crate::{
err::Result,
notes::{Note, NoteID},
notetype::NoteTypeID,
tags::{join_tags, split_tags},
timestamp::TimestampMillis,
};
use rusqlite::{params, Row, NO_PARAMS};
pub(crate) fn split_fields(fields: &str) -> Vec<String> {
fields.split('\x1f').map(Into::into).collect()
}
pub(crate) fn join_fields(fields: &[String]) -> String {
fields.join("\x1f")
}
fn row_to_note(row: &Row) -> Result<Note> {
Ok(Note {
id: row.get(0)?,
guid: row.get(1)?,
notetype_id: row.get(2)?,
mtime: row.get(3)?,
usn: row.get(4)?,
tags: split_tags(row.get_raw(5).as_str()?)
.map(Into::into)
.collect(),
fields: split_fields(row.get_raw(6).as_str()?),
sort_field: None,
checksum: None,
})
}
impl super::SqliteStorage {
pub fn get_note(&self, nid: NoteID) -> Result<Option<Note>> {
self.db
.prepare_cached(concat!(include_str!("get.sql"), " where id =?"))?
.query_and_then(params![nid], row_to_note)?
.next()
.transpose()
}
/// Caller must call note.prepare_for_update() prior to calling this.
pub(crate) fn update_note(&self, note: &Note) -> Result<()> {
assert!(note.id.0!= 0);
let mut stmt = self.db.prepare_cached(include_str!("update.sql"))?;
stmt.execute(params![
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
note.id
])?;
Ok(())
}
pub(crate) fn add_note(&self, note: &mut Note) -> Result<()> {
assert!(note.id.0 == 0);
let mut stmt = self.db.prepare_cached(include_str!("add.sql"))?;
stmt.execute(params![
TimestampMillis::now(),
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
note.id.0 = self.db.last_insert_rowid();
Ok(())
}
/// Add or update the provided note, preserving ID. Used by the syncing code.
pub(crate) fn add_or_update_note(&self, note: &Note) -> Result<()> {
let mut stmt = self.db.prepare_cached(include_str!("add_or_update.sql"))?;
stmt.execute(params![
note.id,
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
Ok(())
}
pub(crate) fn remove_note(&self, nid: NoteID) -> Result<()> {
self.db
.prepare_cached("delete from notes where id =?")?
.execute(&[nid])?;
Ok(())
}
pub(crate) fn note_is_orphaned(&self, nid: NoteID) -> Result<bool> {
self.db
.prepare_cached(include_str!("is_orphaned.sql"))?
.query_row(&[nid], |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn clear_pending_note_usns(&self) -> Result<()> {
self.db
.prepare("update notes set usn = 0 where usn = -1")?
.execute(NO_PARAMS)?;
Ok(())
}
pub(crate) fn fix_invalid_utf8_in_note(&self, nid: NoteID) -> Result<()> {
self.db
.query_row(
"select cast(flds as blob) from notes where id=?",
&[nid],
|row| {
let fixed_flds: Vec<u8> = row.get(0)?;
let fixed_str = String::from_utf8_lossy(&fixed_flds);
self.db.execute(
"update notes set flds =? where id =?",
params![fixed_str, nid],
)
},
)
.map_err(Into::into)
.map(|_| ())
}
/// Returns [(nid, field 0)] of notes with the same checksum.
/// The caller should strip the fields and compare to see if they actually
/// match.
pub(crate) fn note_fields_by_checksum(
&self,
ntid: NoteTypeID,
csum: u32,
) -> Result<Vec<(NoteID, String)>> {
self.db
.prepare("select id, field_at_index(flds, 0) from notes where csum=? and mid=?")?
.query_and_then(params![csum, ntid], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect()
}
/// Return total number of notes. Slow.
pub(crate) fn total_notes(&self) -> Result<u32> {
self.db
.prepare("select count() from notes")?
.query_row(NO_PARAMS, |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn all_tags_in_notes(&self) -> Result<HashSet<String>>
|
pub(crate) fn for_each_note_tags<F>(&self, mut func: F) -> Result<()>
where
F: FnMut(NoteID, String) -> Result<()>,
{
let mut stmt = self.db.prepare_cached("select id, tags from notes")?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(row) = rows.next()? {
let id: NoteID = row.get(0)?;
let tags: String = row.get(1)?;
func(id, tags)?
}
Ok(())
}
}
|
{
let mut stmt = self
.db
.prepare_cached("select tags from notes where tags != ''")?;
let mut query = stmt.query(NO_PARAMS)?;
let mut seen: HashSet<String> = HashSet::new();
while let Some(rows) = query.next()? {
for tag in split_tags(rows.get_raw(0).as_str()?) {
if !seen.contains(tag) {
seen.insert(tag.to_string());
}
}
}
Ok(seen)
}
|
identifier_body
|
mod.rs
|
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use std::collections::HashSet;
use crate::{
err::Result,
notes::{Note, NoteID},
notetype::NoteTypeID,
tags::{join_tags, split_tags},
timestamp::TimestampMillis,
};
use rusqlite::{params, Row, NO_PARAMS};
pub(crate) fn split_fields(fields: &str) -> Vec<String> {
fields.split('\x1f').map(Into::into).collect()
}
pub(crate) fn join_fields(fields: &[String]) -> String {
fields.join("\x1f")
}
fn
|
(row: &Row) -> Result<Note> {
Ok(Note {
id: row.get(0)?,
guid: row.get(1)?,
notetype_id: row.get(2)?,
mtime: row.get(3)?,
usn: row.get(4)?,
tags: split_tags(row.get_raw(5).as_str()?)
.map(Into::into)
.collect(),
fields: split_fields(row.get_raw(6).as_str()?),
sort_field: None,
checksum: None,
})
}
impl super::SqliteStorage {
pub fn get_note(&self, nid: NoteID) -> Result<Option<Note>> {
self.db
.prepare_cached(concat!(include_str!("get.sql"), " where id =?"))?
.query_and_then(params![nid], row_to_note)?
.next()
.transpose()
}
/// Caller must call note.prepare_for_update() prior to calling this.
pub(crate) fn update_note(&self, note: &Note) -> Result<()> {
assert!(note.id.0!= 0);
let mut stmt = self.db.prepare_cached(include_str!("update.sql"))?;
stmt.execute(params![
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
note.id
])?;
Ok(())
}
pub(crate) fn add_note(&self, note: &mut Note) -> Result<()> {
assert!(note.id.0 == 0);
let mut stmt = self.db.prepare_cached(include_str!("add.sql"))?;
stmt.execute(params![
TimestampMillis::now(),
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
note.id.0 = self.db.last_insert_rowid();
Ok(())
}
/// Add or update the provided note, preserving ID. Used by the syncing code.
pub(crate) fn add_or_update_note(&self, note: &Note) -> Result<()> {
let mut stmt = self.db.prepare_cached(include_str!("add_or_update.sql"))?;
stmt.execute(params![
note.id,
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
Ok(())
}
pub(crate) fn remove_note(&self, nid: NoteID) -> Result<()> {
self.db
.prepare_cached("delete from notes where id =?")?
.execute(&[nid])?;
Ok(())
}
pub(crate) fn note_is_orphaned(&self, nid: NoteID) -> Result<bool> {
self.db
.prepare_cached(include_str!("is_orphaned.sql"))?
.query_row(&[nid], |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn clear_pending_note_usns(&self) -> Result<()> {
self.db
.prepare("update notes set usn = 0 where usn = -1")?
.execute(NO_PARAMS)?;
Ok(())
}
pub(crate) fn fix_invalid_utf8_in_note(&self, nid: NoteID) -> Result<()> {
self.db
.query_row(
"select cast(flds as blob) from notes where id=?",
&[nid],
|row| {
let fixed_flds: Vec<u8> = row.get(0)?;
let fixed_str = String::from_utf8_lossy(&fixed_flds);
self.db.execute(
"update notes set flds =? where id =?",
params![fixed_str, nid],
)
},
)
.map_err(Into::into)
.map(|_| ())
}
/// Returns [(nid, field 0)] of notes with the same checksum.
/// The caller should strip the fields and compare to see if they actually
/// match.
pub(crate) fn note_fields_by_checksum(
&self,
ntid: NoteTypeID,
csum: u32,
) -> Result<Vec<(NoteID, String)>> {
self.db
.prepare("select id, field_at_index(flds, 0) from notes where csum=? and mid=?")?
.query_and_then(params![csum, ntid], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect()
}
/// Return total number of notes. Slow.
pub(crate) fn total_notes(&self) -> Result<u32> {
self.db
.prepare("select count() from notes")?
.query_row(NO_PARAMS, |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn all_tags_in_notes(&self) -> Result<HashSet<String>> {
let mut stmt = self
.db
.prepare_cached("select tags from notes where tags!= ''")?;
let mut query = stmt.query(NO_PARAMS)?;
let mut seen: HashSet<String> = HashSet::new();
while let Some(rows) = query.next()? {
for tag in split_tags(rows.get_raw(0).as_str()?) {
if!seen.contains(tag) {
seen.insert(tag.to_string());
}
}
}
Ok(seen)
}
pub(crate) fn for_each_note_tags<F>(&self, mut func: F) -> Result<()>
where
F: FnMut(NoteID, String) -> Result<()>,
{
let mut stmt = self.db.prepare_cached("select id, tags from notes")?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(row) = rows.next()? {
let id: NoteID = row.get(0)?;
let tags: String = row.get(1)?;
func(id, tags)?
}
Ok(())
}
}
|
row_to_note
|
identifier_name
|
mod.rs
|
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use std::collections::HashSet;
use crate::{
err::Result,
notes::{Note, NoteID},
notetype::NoteTypeID,
tags::{join_tags, split_tags},
timestamp::TimestampMillis,
};
use rusqlite::{params, Row, NO_PARAMS};
pub(crate) fn split_fields(fields: &str) -> Vec<String> {
fields.split('\x1f').map(Into::into).collect()
}
pub(crate) fn join_fields(fields: &[String]) -> String {
fields.join("\x1f")
}
fn row_to_note(row: &Row) -> Result<Note> {
Ok(Note {
id: row.get(0)?,
guid: row.get(1)?,
notetype_id: row.get(2)?,
mtime: row.get(3)?,
usn: row.get(4)?,
tags: split_tags(row.get_raw(5).as_str()?)
.map(Into::into)
.collect(),
fields: split_fields(row.get_raw(6).as_str()?),
sort_field: None,
checksum: None,
})
}
impl super::SqliteStorage {
pub fn get_note(&self, nid: NoteID) -> Result<Option<Note>> {
self.db
.prepare_cached(concat!(include_str!("get.sql"), " where id =?"))?
.query_and_then(params![nid], row_to_note)?
.next()
.transpose()
}
/// Caller must call note.prepare_for_update() prior to calling this.
pub(crate) fn update_note(&self, note: &Note) -> Result<()> {
assert!(note.id.0!= 0);
let mut stmt = self.db.prepare_cached(include_str!("update.sql"))?;
stmt.execute(params![
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
note.id
])?;
Ok(())
}
pub(crate) fn add_note(&self, note: &mut Note) -> Result<()> {
assert!(note.id.0 == 0);
let mut stmt = self.db.prepare_cached(include_str!("add.sql"))?;
stmt.execute(params![
TimestampMillis::now(),
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
note.id.0 = self.db.last_insert_rowid();
Ok(())
}
/// Add or update the provided note, preserving ID. Used by the syncing code.
pub(crate) fn add_or_update_note(&self, note: &Note) -> Result<()> {
let mut stmt = self.db.prepare_cached(include_str!("add_or_update.sql"))?;
stmt.execute(params![
note.id,
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
Ok(())
}
pub(crate) fn remove_note(&self, nid: NoteID) -> Result<()> {
self.db
.prepare_cached("delete from notes where id =?")?
.execute(&[nid])?;
Ok(())
}
pub(crate) fn note_is_orphaned(&self, nid: NoteID) -> Result<bool> {
self.db
.prepare_cached(include_str!("is_orphaned.sql"))?
.query_row(&[nid], |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn clear_pending_note_usns(&self) -> Result<()> {
self.db
.prepare("update notes set usn = 0 where usn = -1")?
.execute(NO_PARAMS)?;
Ok(())
}
pub(crate) fn fix_invalid_utf8_in_note(&self, nid: NoteID) -> Result<()> {
self.db
.query_row(
"select cast(flds as blob) from notes where id=?",
&[nid],
|row| {
let fixed_flds: Vec<u8> = row.get(0)?;
let fixed_str = String::from_utf8_lossy(&fixed_flds);
self.db.execute(
"update notes set flds =? where id =?",
params![fixed_str, nid],
)
},
)
.map_err(Into::into)
.map(|_| ())
}
/// Returns [(nid, field 0)] of notes with the same checksum.
/// The caller should strip the fields and compare to see if they actually
/// match.
pub(crate) fn note_fields_by_checksum(
&self,
ntid: NoteTypeID,
csum: u32,
) -> Result<Vec<(NoteID, String)>> {
self.db
.prepare("select id, field_at_index(flds, 0) from notes where csum=? and mid=?")?
.query_and_then(params![csum, ntid], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect()
}
/// Return total number of notes. Slow.
pub(crate) fn total_notes(&self) -> Result<u32> {
self.db
.prepare("select count() from notes")?
.query_row(NO_PARAMS, |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn all_tags_in_notes(&self) -> Result<HashSet<String>> {
let mut stmt = self
.db
.prepare_cached("select tags from notes where tags!= ''")?;
let mut query = stmt.query(NO_PARAMS)?;
let mut seen: HashSet<String> = HashSet::new();
while let Some(rows) = query.next()? {
for tag in split_tags(rows.get_raw(0).as_str()?) {
if!seen.contains(tag)
|
}
}
Ok(seen)
}
pub(crate) fn for_each_note_tags<F>(&self, mut func: F) -> Result<()>
where
F: FnMut(NoteID, String) -> Result<()>,
{
let mut stmt = self.db.prepare_cached("select id, tags from notes")?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(row) = rows.next()? {
let id: NoteID = row.get(0)?;
let tags: String = row.get(1)?;
func(id, tags)?
}
Ok(())
}
}
|
{
seen.insert(tag.to_string());
}
|
conditional_block
|
mod.rs
|
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
use std::collections::HashSet;
use crate::{
err::Result,
notes::{Note, NoteID},
notetype::NoteTypeID,
tags::{join_tags, split_tags},
timestamp::TimestampMillis,
};
use rusqlite::{params, Row, NO_PARAMS};
pub(crate) fn split_fields(fields: &str) -> Vec<String> {
fields.split('\x1f').map(Into::into).collect()
}
pub(crate) fn join_fields(fields: &[String]) -> String {
fields.join("\x1f")
}
fn row_to_note(row: &Row) -> Result<Note> {
Ok(Note {
id: row.get(0)?,
guid: row.get(1)?,
notetype_id: row.get(2)?,
mtime: row.get(3)?,
usn: row.get(4)?,
tags: split_tags(row.get_raw(5).as_str()?)
.map(Into::into)
.collect(),
fields: split_fields(row.get_raw(6).as_str()?),
sort_field: None,
checksum: None,
})
}
impl super::SqliteStorage {
pub fn get_note(&self, nid: NoteID) -> Result<Option<Note>> {
self.db
.prepare_cached(concat!(include_str!("get.sql"), " where id =?"))?
.query_and_then(params![nid], row_to_note)?
.next()
.transpose()
}
/// Caller must call note.prepare_for_update() prior to calling this.
pub(crate) fn update_note(&self, note: &Note) -> Result<()> {
assert!(note.id.0!= 0);
let mut stmt = self.db.prepare_cached(include_str!("update.sql"))?;
stmt.execute(params![
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
note.id
])?;
Ok(())
}
pub(crate) fn add_note(&self, note: &mut Note) -> Result<()> {
assert!(note.id.0 == 0);
let mut stmt = self.db.prepare_cached(include_str!("add.sql"))?;
stmt.execute(params![
TimestampMillis::now(),
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
note.id.0 = self.db.last_insert_rowid();
Ok(())
}
/// Add or update the provided note, preserving ID. Used by the syncing code.
pub(crate) fn add_or_update_note(&self, note: &Note) -> Result<()> {
let mut stmt = self.db.prepare_cached(include_str!("add_or_update.sql"))?;
stmt.execute(params![
note.id,
note.guid,
note.notetype_id,
note.mtime,
note.usn,
join_tags(¬e.tags),
join_fields(¬e.fields()),
note.sort_field.as_ref().unwrap(),
note.checksum.unwrap(),
])?;
Ok(())
}
pub(crate) fn remove_note(&self, nid: NoteID) -> Result<()> {
self.db
.prepare_cached("delete from notes where id =?")?
.execute(&[nid])?;
Ok(())
}
pub(crate) fn note_is_orphaned(&self, nid: NoteID) -> Result<bool> {
self.db
.prepare_cached(include_str!("is_orphaned.sql"))?
.query_row(&[nid], |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn clear_pending_note_usns(&self) -> Result<()> {
self.db
.prepare("update notes set usn = 0 where usn = -1")?
.execute(NO_PARAMS)?;
Ok(())
}
pub(crate) fn fix_invalid_utf8_in_note(&self, nid: NoteID) -> Result<()> {
self.db
.query_row(
"select cast(flds as blob) from notes where id=?",
&[nid],
|row| {
let fixed_flds: Vec<u8> = row.get(0)?;
let fixed_str = String::from_utf8_lossy(&fixed_flds);
self.db.execute(
"update notes set flds =? where id =?",
params![fixed_str, nid],
)
},
)
.map_err(Into::into)
.map(|_| ())
}
/// Returns [(nid, field 0)] of notes with the same checksum.
/// The caller should strip the fields and compare to see if they actually
/// match.
pub(crate) fn note_fields_by_checksum(
&self,
ntid: NoteTypeID,
csum: u32,
) -> Result<Vec<(NoteID, String)>> {
self.db
.prepare("select id, field_at_index(flds, 0) from notes where csum=? and mid=?")?
.query_and_then(params![csum, ntid], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect()
}
/// Return total number of notes. Slow.
pub(crate) fn total_notes(&self) -> Result<u32> {
|
.prepare("select count() from notes")?
.query_row(NO_PARAMS, |r| r.get(0))
.map_err(Into::into)
}
pub(crate) fn all_tags_in_notes(&self) -> Result<HashSet<String>> {
let mut stmt = self
.db
.prepare_cached("select tags from notes where tags!= ''")?;
let mut query = stmt.query(NO_PARAMS)?;
let mut seen: HashSet<String> = HashSet::new();
while let Some(rows) = query.next()? {
for tag in split_tags(rows.get_raw(0).as_str()?) {
if!seen.contains(tag) {
seen.insert(tag.to_string());
}
}
}
Ok(seen)
}
pub(crate) fn for_each_note_tags<F>(&self, mut func: F) -> Result<()>
where
F: FnMut(NoteID, String) -> Result<()>,
{
let mut stmt = self.db.prepare_cached("select id, tags from notes")?;
let mut rows = stmt.query(NO_PARAMS)?;
while let Some(row) = rows.next()? {
let id: NoteID = row.get(0)?;
let tags: String = row.get(1)?;
func(id, tags)?
}
Ok(())
}
}
|
self.db
|
random_line_split
|
lib.rs
|
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_codegen;
#[macro_use]
extern crate serde_json;
#[macro_export]
macro_rules! get_pg_connection {
($db_context:expr) => (&*$db_context.postgres_connection_pool.get().expect("Failed to get connection from postgres pool"));
}
extern crate iron;
extern crate bodyparser;
extern crate serde_cbor;
extern crate base64;
extern crate crypto;
extern crate unicase;
extern crate chrono;
extern crate env_logger;
extern crate r2d2;
extern crate r2d2_diesel;
extern crate r2d2_redis;
extern crate redis;
extern crate rand;
extern crate serde;
use std::env;
use iron::Iron;
pub mod common {
pub type Pubkey = Vec<u8>;
}
pub mod db;
mod api;
fn get_server_port() -> u16
|
pub fn start() {
env_logger::init().unwrap();
info!("starting spotlease...");
let api = api::ApiHandler::new();
Iron::new(api).http(("0.0.0.0", get_server_port())).unwrap();
}
|
{
let port_str = env::var("PORT").unwrap_or(String::new());
port_str.parse().unwrap_or(8080)
}
|
identifier_body
|
lib.rs
|
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_codegen;
#[macro_use]
extern crate serde_json;
#[macro_export]
macro_rules! get_pg_connection {
($db_context:expr) => (&*$db_context.postgres_connection_pool.get().expect("Failed to get connection from postgres pool"));
}
extern crate iron;
extern crate bodyparser;
extern crate serde_cbor;
extern crate base64;
extern crate crypto;
extern crate unicase;
extern crate chrono;
extern crate env_logger;
extern crate r2d2;
extern crate r2d2_diesel;
extern crate r2d2_redis;
extern crate redis;
extern crate rand;
extern crate serde;
use std::env;
use iron::Iron;
pub mod common {
pub type Pubkey = Vec<u8>;
}
pub mod db;
mod api;
fn
|
() -> u16 {
let port_str = env::var("PORT").unwrap_or(String::new());
port_str.parse().unwrap_or(8080)
}
pub fn start() {
env_logger::init().unwrap();
info!("starting spotlease...");
let api = api::ApiHandler::new();
Iron::new(api).http(("0.0.0.0", get_server_port())).unwrap();
}
|
get_server_port
|
identifier_name
|
lib.rs
|
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate diesel_codegen;
#[macro_use]
extern crate serde_json;
|
#[macro_export]
macro_rules! get_pg_connection {
($db_context:expr) => (&*$db_context.postgres_connection_pool.get().expect("Failed to get connection from postgres pool"));
}
extern crate iron;
extern crate bodyparser;
extern crate serde_cbor;
extern crate base64;
extern crate crypto;
extern crate unicase;
extern crate chrono;
extern crate env_logger;
extern crate r2d2;
extern crate r2d2_diesel;
extern crate r2d2_redis;
extern crate redis;
extern crate rand;
extern crate serde;
use std::env;
use iron::Iron;
pub mod common {
pub type Pubkey = Vec<u8>;
}
pub mod db;
mod api;
fn get_server_port() -> u16 {
let port_str = env::var("PORT").unwrap_or(String::new());
port_str.parse().unwrap_or(8080)
}
pub fn start() {
env_logger::init().unwrap();
info!("starting spotlease...");
let api = api::ApiHandler::new();
Iron::new(api).http(("0.0.0.0", get_server_port())).unwrap();
}
|
random_line_split
|
|
menu.rs
|
use std::default::Default;
use util;
use util::rect::Rect;
use super::common::Canceled;
use super::input::Input;
use super::widget::Widget;
use super::view::HexEditActions;
use super::super::frontend::{Frontend, Style, KeyPress};
pub enum MenuActions {
Key(char),
Back,
Cancel,
ToggleHelp,
}
pub enum MenuEntry<'a, T> where T: 'a {
SubEntries(char, &'a str, &'a [MenuEntry<'a, T>]),
CommandEntry(char, &'a str, T)
}
pub type MenuState<T> = &'static [MenuEntry<'static, T>];
signal_decl!{MenuSelected(HexEditActions)}
pub struct OverlayMenu {
root_menu: MenuState<HexEditActions>,
menu_stack: Vec<&'static MenuEntry<'static, HexEditActions>>,
show_help: bool,
pub on_cancel: Canceled,
pub on_selected: MenuSelected,
}
impl OverlayMenu {
pub fn with_menu(root_menu: MenuState<HexEditActions>) -> OverlayMenu {
OverlayMenu {
root_menu: root_menu,
menu_stack: vec![],
show_help: false,
on_cancel: Default::default(),
on_selected: Default::default(),
}
}
fn menu_act_key(&mut self, c: char) -> bool {
for entry in self.current_menu().iter() {
|
self.on_selected.signal(command);
return true;
}
&MenuEntry::SubEntries(key, _, _) if key == c => {
self.menu_stack.push(&entry);
return true;
}
_ => ()
}
}
return false;
}
fn current_menu(&self) -> MenuState<HexEditActions> {
match self.menu_stack.last() {
Some(&&MenuEntry::SubEntries(_, _, entries)) => entries,
Some(&&MenuEntry::CommandEntry(_, _, _)) => panic!("Got a non menu entry in my menu stack!"),
None => &self.root_menu,
}
}
fn menu_back(&mut self) {
self.menu_stack.pop();
}
fn draw_menu_location(&mut self, rb: &Frontend, x: isize, y: isize) {
let mut x_pos = 0;
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > ");
x_pos += 3;
for location_entry in self.menu_stack.iter() {
let name = match **location_entry {
MenuEntry::SubEntries(_, name, _) => name,
_ => panic!("Got a non menu entry in my menu stack!")
};
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, name);
x_pos += name.len() as isize;
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > ");
x_pos += 3;
}
}
}
impl Widget for OverlayMenu {
fn input(&mut self, input: &Input, key: KeyPress) -> bool {
let action = if let Some(action) = input.menu_input(key) { action } else {
return false;
};
match action {
MenuActions::Back => self.menu_back(),
MenuActions::Key(c) => { return self.menu_act_key(c); }
MenuActions::Cancel => self.on_cancel.signal(None),
MenuActions::ToggleHelp => self.show_help =!self.show_help,
};
return true;
}
fn draw(&mut self, rb: &mut Frontend, area: Rect<isize>, _: bool) {
let clear_line = util::string_with_repeat(' ', area.width as usize);
if!self.show_help {
let hint_msg = "Use? to show/hide the menu help";
rb.print_style(area.left as usize, (area.bottom() - 1) as usize, Style::Default, &clear_line);
rb.print_style(area.right() as usize - hint_msg.len(), (area.bottom() - 1) as usize,
Style::Hint, hint_msg);
self.draw_menu_location(rb, area.left, area.bottom() - 1);
return;
}
for i in 0..(area.height as usize) {
rb.print_style(area.left as usize, area.top as usize + i, Style::Default, &clear_line);
}
self.draw_menu_location(rb, area.left, area.top);
for (i, entry) in self.current_menu().iter().enumerate() {
let (key, name, is_title, style) = match entry {
&MenuEntry::CommandEntry(key, name, _) => (key, name, false, Style::MenuEntry),
&MenuEntry::SubEntries(key, name, _) => (key, name, true, Style::MenuTitle),
};
rb.print_slice_style(10 + area.left as usize, area.top as usize + i + 1, Style::MenuShortcut, &[key,'']);
rb.print_style(10 + area.left as usize + 2, area.top as usize + i + 1, style, name);
if is_title {
rb.print_style(10 + area.left as usize + 2 + name.len() + 1, area.top as usize + i + 1, style, "->");
}
}
rb.set_cursor(-1, -1);
}
}
|
match entry {
&MenuEntry::CommandEntry(key, _, command) if key == c => {
|
random_line_split
|
menu.rs
|
use std::default::Default;
use util;
use util::rect::Rect;
use super::common::Canceled;
use super::input::Input;
use super::widget::Widget;
use super::view::HexEditActions;
use super::super::frontend::{Frontend, Style, KeyPress};
pub enum MenuActions {
Key(char),
Back,
Cancel,
ToggleHelp,
}
pub enum MenuEntry<'a, T> where T: 'a {
SubEntries(char, &'a str, &'a [MenuEntry<'a, T>]),
CommandEntry(char, &'a str, T)
}
pub type MenuState<T> = &'static [MenuEntry<'static, T>];
signal_decl!{MenuSelected(HexEditActions)}
pub struct OverlayMenu {
root_menu: MenuState<HexEditActions>,
menu_stack: Vec<&'static MenuEntry<'static, HexEditActions>>,
show_help: bool,
pub on_cancel: Canceled,
pub on_selected: MenuSelected,
}
impl OverlayMenu {
pub fn with_menu(root_menu: MenuState<HexEditActions>) -> OverlayMenu
|
fn menu_act_key(&mut self, c: char) -> bool {
for entry in self.current_menu().iter() {
match entry {
&MenuEntry::CommandEntry(key, _, command) if key == c => {
self.on_selected.signal(command);
return true;
}
&MenuEntry::SubEntries(key, _, _) if key == c => {
self.menu_stack.push(&entry);
return true;
}
_ => ()
}
}
return false;
}
fn current_menu(&self) -> MenuState<HexEditActions> {
match self.menu_stack.last() {
Some(&&MenuEntry::SubEntries(_, _, entries)) => entries,
Some(&&MenuEntry::CommandEntry(_, _, _)) => panic!("Got a non menu entry in my menu stack!"),
None => &self.root_menu,
}
}
fn menu_back(&mut self) {
self.menu_stack.pop();
}
fn draw_menu_location(&mut self, rb: &Frontend, x: isize, y: isize) {
let mut x_pos = 0;
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > ");
x_pos += 3;
for location_entry in self.menu_stack.iter() {
let name = match **location_entry {
MenuEntry::SubEntries(_, name, _) => name,
_ => panic!("Got a non menu entry in my menu stack!")
};
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, name);
x_pos += name.len() as isize;
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > ");
x_pos += 3;
}
}
}
impl Widget for OverlayMenu {
fn input(&mut self, input: &Input, key: KeyPress) -> bool {
let action = if let Some(action) = input.menu_input(key) { action } else {
return false;
};
match action {
MenuActions::Back => self.menu_back(),
MenuActions::Key(c) => { return self.menu_act_key(c); }
MenuActions::Cancel => self.on_cancel.signal(None),
MenuActions::ToggleHelp => self.show_help =!self.show_help,
};
return true;
}
fn draw(&mut self, rb: &mut Frontend, area: Rect<isize>, _: bool) {
let clear_line = util::string_with_repeat(' ', area.width as usize);
if!self.show_help {
let hint_msg = "Use? to show/hide the menu help";
rb.print_style(area.left as usize, (area.bottom() - 1) as usize, Style::Default, &clear_line);
rb.print_style(area.right() as usize - hint_msg.len(), (area.bottom() - 1) as usize,
Style::Hint, hint_msg);
self.draw_menu_location(rb, area.left, area.bottom() - 1);
return;
}
for i in 0..(area.height as usize) {
rb.print_style(area.left as usize, area.top as usize + i, Style::Default, &clear_line);
}
self.draw_menu_location(rb, area.left, area.top);
for (i, entry) in self.current_menu().iter().enumerate() {
let (key, name, is_title, style) = match entry {
&MenuEntry::CommandEntry(key, name, _) => (key, name, false, Style::MenuEntry),
&MenuEntry::SubEntries(key, name, _) => (key, name, true, Style::MenuTitle),
};
rb.print_slice_style(10 + area.left as usize, area.top as usize + i + 1, Style::MenuShortcut, &[key,'']);
rb.print_style(10 + area.left as usize + 2, area.top as usize + i + 1, style, name);
if is_title {
rb.print_style(10 + area.left as usize + 2 + name.len() + 1, area.top as usize + i + 1, style, "->");
}
}
rb.set_cursor(-1, -1);
}
}
|
{
OverlayMenu {
root_menu: root_menu,
menu_stack: vec![],
show_help: false,
on_cancel: Default::default(),
on_selected: Default::default(),
}
}
|
identifier_body
|
menu.rs
|
use std::default::Default;
use util;
use util::rect::Rect;
use super::common::Canceled;
use super::input::Input;
use super::widget::Widget;
use super::view::HexEditActions;
use super::super::frontend::{Frontend, Style, KeyPress};
pub enum MenuActions {
Key(char),
Back,
Cancel,
ToggleHelp,
}
pub enum MenuEntry<'a, T> where T: 'a {
SubEntries(char, &'a str, &'a [MenuEntry<'a, T>]),
CommandEntry(char, &'a str, T)
}
pub type MenuState<T> = &'static [MenuEntry<'static, T>];
signal_decl!{MenuSelected(HexEditActions)}
pub struct OverlayMenu {
root_menu: MenuState<HexEditActions>,
menu_stack: Vec<&'static MenuEntry<'static, HexEditActions>>,
show_help: bool,
pub on_cancel: Canceled,
pub on_selected: MenuSelected,
}
impl OverlayMenu {
pub fn with_menu(root_menu: MenuState<HexEditActions>) -> OverlayMenu {
OverlayMenu {
root_menu: root_menu,
menu_stack: vec![],
show_help: false,
on_cancel: Default::default(),
on_selected: Default::default(),
}
}
fn menu_act_key(&mut self, c: char) -> bool {
for entry in self.current_menu().iter() {
match entry {
&MenuEntry::CommandEntry(key, _, command) if key == c => {
self.on_selected.signal(command);
return true;
}
&MenuEntry::SubEntries(key, _, _) if key == c => {
self.menu_stack.push(&entry);
return true;
}
_ => ()
}
}
return false;
}
fn current_menu(&self) -> MenuState<HexEditActions> {
match self.menu_stack.last() {
Some(&&MenuEntry::SubEntries(_, _, entries)) => entries,
Some(&&MenuEntry::CommandEntry(_, _, _)) => panic!("Got a non menu entry in my menu stack!"),
None => &self.root_menu,
}
}
fn menu_back(&mut self) {
self.menu_stack.pop();
}
fn
|
(&mut self, rb: &Frontend, x: isize, y: isize) {
let mut x_pos = 0;
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > ");
x_pos += 3;
for location_entry in self.menu_stack.iter() {
let name = match **location_entry {
MenuEntry::SubEntries(_, name, _) => name,
_ => panic!("Got a non menu entry in my menu stack!")
};
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, name);
x_pos += name.len() as isize;
rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > ");
x_pos += 3;
}
}
}
impl Widget for OverlayMenu {
fn input(&mut self, input: &Input, key: KeyPress) -> bool {
let action = if let Some(action) = input.menu_input(key) { action } else {
return false;
};
match action {
MenuActions::Back => self.menu_back(),
MenuActions::Key(c) => { return self.menu_act_key(c); }
MenuActions::Cancel => self.on_cancel.signal(None),
MenuActions::ToggleHelp => self.show_help =!self.show_help,
};
return true;
}
fn draw(&mut self, rb: &mut Frontend, area: Rect<isize>, _: bool) {
let clear_line = util::string_with_repeat(' ', area.width as usize);
if!self.show_help {
let hint_msg = "Use? to show/hide the menu help";
rb.print_style(area.left as usize, (area.bottom() - 1) as usize, Style::Default, &clear_line);
rb.print_style(area.right() as usize - hint_msg.len(), (area.bottom() - 1) as usize,
Style::Hint, hint_msg);
self.draw_menu_location(rb, area.left, area.bottom() - 1);
return;
}
for i in 0..(area.height as usize) {
rb.print_style(area.left as usize, area.top as usize + i, Style::Default, &clear_line);
}
self.draw_menu_location(rb, area.left, area.top);
for (i, entry) in self.current_menu().iter().enumerate() {
let (key, name, is_title, style) = match entry {
&MenuEntry::CommandEntry(key, name, _) => (key, name, false, Style::MenuEntry),
&MenuEntry::SubEntries(key, name, _) => (key, name, true, Style::MenuTitle),
};
rb.print_slice_style(10 + area.left as usize, area.top as usize + i + 1, Style::MenuShortcut, &[key,'']);
rb.print_style(10 + area.left as usize + 2, area.top as usize + i + 1, style, name);
if is_title {
rb.print_style(10 + area.left as usize + 2 + name.len() + 1, area.top as usize + i + 1, style, "->");
}
}
rb.set_cursor(-1, -1);
}
}
|
draw_menu_location
|
identifier_name
|
item_state.rs
|
use pango::{self, LayoutExt, Layout};
use cairo_sys;
use pangocairo::CairoContextExt;
use bar_properties::BarProperties;
use xcb::{self, Window, Screen, Visualtype, Pixmap, Connection};
use cairo::{Context, Surface};
use std::rc::Rc;
use error::Result;
pub struct ItemState {
bar_props: Rc<BarProperties>,
conn: Rc<Connection>,
content_width: u16,
id: usize,
pixmap: Pixmap,
screen_number: usize,
state: String,
surface: Option<Surface>,
surface_width: u16,
visualtype: Visualtype,
window: Window,
}
impl ItemState {
pub fn new(
id: usize,
bar_props: Rc<BarProperties>,
screen_number: usize,
visualtype: Visualtype,
conn: Rc<Connection>,
window: Window,
) -> ItemState {
let pixmap = conn.generate_id();
ItemState {
bar_props,
conn,
content_width: 1,
id,
pixmap,
screen_number: screen_number,
state: String::new(),
surface: None,
surface_width: 0,
visualtype,
window,
}
}
#[inline]
pub fn is_ready(&self) -> bool {
self.surface.is_some()
}
#[inline]
pub fn get_content_width(&self) -> u16 {
self.content_width
}
#[inline]
pub fn get_pixmap(&self) -> Pixmap {
self.pixmap
}
#[inline]
pub fn get_id(&self) -> usize {
self.id
}
#[inline]
fn get_screen(&self) -> Screen {
let setup = self.conn.get_setup();
setup.roots().nth(self.screen_number).unwrap()
}
fn update_surface(&mut self) -> Result<()> {
let width = self.content_width;
if width > self.surface_width || width < (self.surface_width / 10) * 6 ||
self.surface.is_none()
{
self.surface_width = (width / 10) * 13 + 1;
xcb::free_pixmap(&self.conn, self.pixmap);
self.pixmap = self.conn.generate_id();
try_xcb!(
xcb::create_pixmap_checked,
"failed to create pixmap",
&self.conn,
self.get_screen().root_depth(),
self.pixmap,
self.window,
self.surface_width as u16,
self.bar_props.area.height()
);
self.surface = Some(unsafe {
Surface::from_raw_full(cairo_sys::cairo_xcb_surface_create(
(self.conn.get_raw_conn() as *mut cairo_sys::xcb_connection_t),
//self.get_screen().ptr as *mut cairo_sys::xcb_screen_t,
self.pixmap,
(&mut self.visualtype.base as *mut xcb::ffi::xcb_visualtype_t) as
*mut cairo_sys::xcb_visualtype_t,
self.surface_width as i32,
self.bar_props.area.height() as i32,
))
});
}
Ok(())
}
fn create_layout(&self, ctx: &Context) -> Layout {
let layout = ctx.create_pango_layout();
layout.set_font_description(Some(&self.bar_props.font));
layout.set_markup(self.state.as_str(), self.state.len() as i32);
ctx.update_pango_layout(&layout);
layout
}
pub fn update_size(&mut self) -> Result<()> {
self.update_surface()?;
let surface = match self.surface {
Some(ref surface) => surface,
None => return Err("no surface".into()),
};
let ctx = Context::new(&surface);
let layout = self.create_layout(&ctx);
|
}
pub fn update(&mut self, update: String) -> Result<()> {
if update!= self.state {
self.state = update;
self.update_size()?;
self.paint()?;
}
Ok(())
}
pub fn paint(&mut self) -> Result<()> {
self.update_surface()?;
let surface = match self.surface {
Some(ref surface) => surface,
None => return Err("no surface".into()),
};
let ctx = Context::new(&surface);
let layout = self.create_layout(&ctx);
ctx.set_source_rgb(
self.bar_props.bg_color.red,
self.bar_props.bg_color.green,
self.bar_props.bg_color.blue,
);
ctx.paint();
ctx.set_source_rgb(
self.bar_props.fg_color.red,
self.bar_props.fg_color.green,
self.bar_props.fg_color.blue,
);
let text_height = self.bar_props.font.get_size() as f64 / pango::SCALE as f64;
let baseline = self.bar_props.area.height() as f64 / 2. + (text_height / 2.) -
(layout.get_baseline() as f64 / pango::SCALE as f64);
ctx.move_to(0., baseline.floor() - 1.);
ctx.update_pango_layout(&layout);
ctx.show_pango_layout(&layout);
self.conn.flush();
Ok(())
}
}
|
self.content_width = layout.get_pixel_size().0 as u16;
Ok(())
|
random_line_split
|
item_state.rs
|
use pango::{self, LayoutExt, Layout};
use cairo_sys;
use pangocairo::CairoContextExt;
use bar_properties::BarProperties;
use xcb::{self, Window, Screen, Visualtype, Pixmap, Connection};
use cairo::{Context, Surface};
use std::rc::Rc;
use error::Result;
pub struct ItemState {
bar_props: Rc<BarProperties>,
conn: Rc<Connection>,
content_width: u16,
id: usize,
pixmap: Pixmap,
screen_number: usize,
state: String,
surface: Option<Surface>,
surface_width: u16,
visualtype: Visualtype,
window: Window,
}
impl ItemState {
pub fn new(
id: usize,
bar_props: Rc<BarProperties>,
screen_number: usize,
visualtype: Visualtype,
conn: Rc<Connection>,
window: Window,
) -> ItemState {
let pixmap = conn.generate_id();
ItemState {
bar_props,
conn,
content_width: 1,
id,
pixmap,
screen_number: screen_number,
state: String::new(),
surface: None,
surface_width: 0,
visualtype,
window,
}
}
#[inline]
pub fn is_ready(&self) -> bool {
self.surface.is_some()
}
#[inline]
pub fn get_content_width(&self) -> u16 {
self.content_width
}
#[inline]
pub fn get_pixmap(&self) -> Pixmap {
self.pixmap
}
#[inline]
pub fn get_id(&self) -> usize {
self.id
}
#[inline]
fn get_screen(&self) -> Screen {
let setup = self.conn.get_setup();
setup.roots().nth(self.screen_number).unwrap()
}
fn update_surface(&mut self) -> Result<()> {
let width = self.content_width;
if width > self.surface_width || width < (self.surface_width / 10) * 6 ||
self.surface.is_none()
{
self.surface_width = (width / 10) * 13 + 1;
xcb::free_pixmap(&self.conn, self.pixmap);
self.pixmap = self.conn.generate_id();
try_xcb!(
xcb::create_pixmap_checked,
"failed to create pixmap",
&self.conn,
self.get_screen().root_depth(),
self.pixmap,
self.window,
self.surface_width as u16,
self.bar_props.area.height()
);
self.surface = Some(unsafe {
Surface::from_raw_full(cairo_sys::cairo_xcb_surface_create(
(self.conn.get_raw_conn() as *mut cairo_sys::xcb_connection_t),
//self.get_screen().ptr as *mut cairo_sys::xcb_screen_t,
self.pixmap,
(&mut self.visualtype.base as *mut xcb::ffi::xcb_visualtype_t) as
*mut cairo_sys::xcb_visualtype_t,
self.surface_width as i32,
self.bar_props.area.height() as i32,
))
});
}
Ok(())
}
fn create_layout(&self, ctx: &Context) -> Layout {
let layout = ctx.create_pango_layout();
layout.set_font_description(Some(&self.bar_props.font));
layout.set_markup(self.state.as_str(), self.state.len() as i32);
ctx.update_pango_layout(&layout);
layout
}
pub fn update_size(&mut self) -> Result<()> {
self.update_surface()?;
let surface = match self.surface {
Some(ref surface) => surface,
None => return Err("no surface".into()),
};
let ctx = Context::new(&surface);
let layout = self.create_layout(&ctx);
self.content_width = layout.get_pixel_size().0 as u16;
Ok(())
}
pub fn update(&mut self, update: String) -> Result<()>
|
pub fn paint(&mut self) -> Result<()> {
self.update_surface()?;
let surface = match self.surface {
Some(ref surface) => surface,
None => return Err("no surface".into()),
};
let ctx = Context::new(&surface);
let layout = self.create_layout(&ctx);
ctx.set_source_rgb(
self.bar_props.bg_color.red,
self.bar_props.bg_color.green,
self.bar_props.bg_color.blue,
);
ctx.paint();
ctx.set_source_rgb(
self.bar_props.fg_color.red,
self.bar_props.fg_color.green,
self.bar_props.fg_color.blue,
);
let text_height = self.bar_props.font.get_size() as f64 / pango::SCALE as f64;
let baseline = self.bar_props.area.height() as f64 / 2. + (text_height / 2.) -
(layout.get_baseline() as f64 / pango::SCALE as f64);
ctx.move_to(0., baseline.floor() - 1.);
ctx.update_pango_layout(&layout);
ctx.show_pango_layout(&layout);
self.conn.flush();
Ok(())
}
}
|
{
if update != self.state {
self.state = update;
self.update_size()?;
self.paint()?;
}
Ok(())
}
|
identifier_body
|
item_state.rs
|
use pango::{self, LayoutExt, Layout};
use cairo_sys;
use pangocairo::CairoContextExt;
use bar_properties::BarProperties;
use xcb::{self, Window, Screen, Visualtype, Pixmap, Connection};
use cairo::{Context, Surface};
use std::rc::Rc;
use error::Result;
pub struct ItemState {
bar_props: Rc<BarProperties>,
conn: Rc<Connection>,
content_width: u16,
id: usize,
pixmap: Pixmap,
screen_number: usize,
state: String,
surface: Option<Surface>,
surface_width: u16,
visualtype: Visualtype,
window: Window,
}
impl ItemState {
pub fn new(
id: usize,
bar_props: Rc<BarProperties>,
screen_number: usize,
visualtype: Visualtype,
conn: Rc<Connection>,
window: Window,
) -> ItemState {
let pixmap = conn.generate_id();
ItemState {
bar_props,
conn,
content_width: 1,
id,
pixmap,
screen_number: screen_number,
state: String::new(),
surface: None,
surface_width: 0,
visualtype,
window,
}
}
#[inline]
pub fn is_ready(&self) -> bool {
self.surface.is_some()
}
#[inline]
pub fn get_content_width(&self) -> u16 {
self.content_width
}
#[inline]
pub fn get_pixmap(&self) -> Pixmap {
self.pixmap
}
#[inline]
pub fn get_id(&self) -> usize {
self.id
}
#[inline]
fn
|
(&self) -> Screen {
let setup = self.conn.get_setup();
setup.roots().nth(self.screen_number).unwrap()
}
fn update_surface(&mut self) -> Result<()> {
let width = self.content_width;
if width > self.surface_width || width < (self.surface_width / 10) * 6 ||
self.surface.is_none()
{
self.surface_width = (width / 10) * 13 + 1;
xcb::free_pixmap(&self.conn, self.pixmap);
self.pixmap = self.conn.generate_id();
try_xcb!(
xcb::create_pixmap_checked,
"failed to create pixmap",
&self.conn,
self.get_screen().root_depth(),
self.pixmap,
self.window,
self.surface_width as u16,
self.bar_props.area.height()
);
self.surface = Some(unsafe {
Surface::from_raw_full(cairo_sys::cairo_xcb_surface_create(
(self.conn.get_raw_conn() as *mut cairo_sys::xcb_connection_t),
//self.get_screen().ptr as *mut cairo_sys::xcb_screen_t,
self.pixmap,
(&mut self.visualtype.base as *mut xcb::ffi::xcb_visualtype_t) as
*mut cairo_sys::xcb_visualtype_t,
self.surface_width as i32,
self.bar_props.area.height() as i32,
))
});
}
Ok(())
}
fn create_layout(&self, ctx: &Context) -> Layout {
let layout = ctx.create_pango_layout();
layout.set_font_description(Some(&self.bar_props.font));
layout.set_markup(self.state.as_str(), self.state.len() as i32);
ctx.update_pango_layout(&layout);
layout
}
pub fn update_size(&mut self) -> Result<()> {
self.update_surface()?;
let surface = match self.surface {
Some(ref surface) => surface,
None => return Err("no surface".into()),
};
let ctx = Context::new(&surface);
let layout = self.create_layout(&ctx);
self.content_width = layout.get_pixel_size().0 as u16;
Ok(())
}
pub fn update(&mut self, update: String) -> Result<()> {
if update!= self.state {
self.state = update;
self.update_size()?;
self.paint()?;
}
Ok(())
}
pub fn paint(&mut self) -> Result<()> {
self.update_surface()?;
let surface = match self.surface {
Some(ref surface) => surface,
None => return Err("no surface".into()),
};
let ctx = Context::new(&surface);
let layout = self.create_layout(&ctx);
ctx.set_source_rgb(
self.bar_props.bg_color.red,
self.bar_props.bg_color.green,
self.bar_props.bg_color.blue,
);
ctx.paint();
ctx.set_source_rgb(
self.bar_props.fg_color.red,
self.bar_props.fg_color.green,
self.bar_props.fg_color.blue,
);
let text_height = self.bar_props.font.get_size() as f64 / pango::SCALE as f64;
let baseline = self.bar_props.area.height() as f64 / 2. + (text_height / 2.) -
(layout.get_baseline() as f64 / pango::SCALE as f64);
ctx.move_to(0., baseline.floor() - 1.);
ctx.update_pango_layout(&layout);
ctx.show_pango_layout(&layout);
self.conn.flush();
Ok(())
}
}
|
get_screen
|
identifier_name
|
mod.rs
|
/* Periodically crawl web pages and alert the user of changes
* Copyright (C) 2016 Owen Stenson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* More information in the enclosed `LICENSE' file
*/
/* BS:
* The biggest thing that a Command object needs to do is, given its
* internal data and the current time, return the next time it should run.
* There seem to be two ways of approaching this.
* 1. each vector of Values is consolidated into a hash set of valid times:
* this would be slightly costly in terms of initial construction and
* memory usage, but fetching the 'next' valid value would be very fast.
* 5 hash tables large enough to store `*****` is 263 bytes (134 u8s)
* 2. fetch the 'next' valid value for each Value in the vector. that would
* require implementing 'next' for Asterisk, Range, Constant, and Skip.
* This would require less memory but maybe a little more cpu to find
* 'next' an arbitrary (though effectively like 1 or 2) number of times.
* It might be in our best interest to consolidate values also (e.g.
* `2,1-3` and `1-3,3-4` are redundant), but I'm not sure how I'd do that.
* (1) would probably be simpler, cleaner, and less interesting.
* In hindsight, (1) involved a lot of redundant checks, so it is
* certainly not an optimal use of cpu. It also makes spaghetti code
* because the Gregorian calendar is awful. (2) is not an optimal use of
* ram, but firing an event requires calling.contains() on a BTreeSet
* of u8s instead of calling.next() on an arbitrary number of values.
* 3. Populate (2)'s set of valid options and check once per minute.
* Checks frequently, but there's not a lot there to mess up.
* Negligibly more expensive than (2), and probably more reliable.
|
*/
/* mod.rs
* This file will eventually house framework to tie in functionality for
* Calendar and Action and maybe Schedule. It shouldn't be hefty.
*/
pub mod value_itr;
pub mod calendar;
|
* It should probably have a test suite anyway, though smaller than what
* (2) would require (and WAY smaller than what (1) would require).
|
random_line_split
|
main.rs
|
#[macro_use]
extern crate lazy_static;
extern crate termc_model;
extern crate termc_ui;
extern crate serde_json;
extern crate regex;
mod command_library;
use std::env;
use std::path::Path;
use termc_model::get_result;
use termc_model::math_context::MathContext;
use termc_model::math_result::MathResult;
use termc_ui::{TerminalUI, TerminalMode};
use command_library::{CommandType, check_for_command};
/// The main entry point.
pub fn main() {
let mut args = get_arguments();
// If there are command line arguments given, start in call mode.
// Otherwise start in interactive mode.
if args.len() > 1 {
start_call(& mut args);
}
else {
let path = args.pop().unwrap(); // get path of this executable
start_interactive(path);
}
}
/// Returns the math expression command line arguments.
fn get_arguments() -> Vec<String> {
let args_it = env::args();
args_it.collect()
}
fn
|
(exe_path: &str) -> String {
let default_fd = Path::new(exe_path).parent().unwrap(); // remove termc executable name
let default_fn = Path::new("termc_context.json"); // define default file name
default_fd.join(default_fn).to_str().unwrap().to_string() // join current path and default file name
}
/// Starts termc in command line call mode.
/// Prints a ';'-separated list with the results of the specified mathematical expressions.
fn start_call(args: & mut Vec<String>) {
// compute default file-path for the serialization file
let mut iter = args.iter();
let path_str : String = iter.next().unwrap().to_string(); // get path of this executable
let default_file = build_default_ser_path(&path_str);
// create terminal handle
let mut terminal = TerminalUI::new(TerminalMode::Call);
let mut results : Vec<MathResult> = Vec::new();
let mut context = MathContext::new();
// for each argument given, evaluate it and store the results
// if an error occurs for any of the given arguments, the evaluation of all arguments will be aborted
for (i, arg) in iter.enumerate() {
match check_for_command(arg, &mut context, &mut terminal, default_file.clone()) {
Ok(k) => {
match k {
Some(command_type) => {
match command_type {
CommandType::Exit => break,
_ => ()
}
},
None => {
match get_result(arg.trim(), & mut context) {
Ok(result) => {
match result {
Some(y) => results.push(y),
None => ()
}
},
Err(err) => {
terminal.print(&format!("In input {0}:\n", i+1));
terminal.print_error(err);
break;
}
}
}
}
},
Err(e) => terminal.print_error(e)
}
}
terminal.print_results(&results);
}
/// Starts termc in command line interactive mode.
fn start_interactive(path_str: String) {
// compute default file-path for the serialization file
let default_file = build_default_ser_path(&path_str);
// create terminal handle
let mut terminal = TerminalUI::new(TerminalMode::Interactive);
// terminal.init();
let mut context = MathContext::new();
// REPL: take user input, evaluate it and print results / errors
loop {
let user_input = terminal.get_user_input();
let user_input = user_input.trim();
if user_input.len() == 0 {
continue;
}
match check_for_command(user_input, &mut context, &mut terminal, default_file.clone()) {
Ok(k) => {
match k {
Some(command_type) => {
match command_type {
CommandType::Exit => break,
_ => terminal.print_cmd_ack()
}
},
None => {
match get_result(& user_input, & mut context) {
Ok(result) => {
match result {
Some(y) => terminal.print_result(&y),
None => ()
}
},
Err(err) => {
terminal.print_error(err);
}
}
}
}
},
Err(e) => terminal.print_error(e)
}
}
match terminal.save_history_file() {
Ok(_) => (),
Err(e) => terminal.print_error(e)
}
}
|
build_default_ser_path
|
identifier_name
|
main.rs
|
#[macro_use]
extern crate lazy_static;
extern crate termc_model;
extern crate termc_ui;
extern crate serde_json;
extern crate regex;
mod command_library;
use std::env;
use std::path::Path;
use termc_model::get_result;
use termc_model::math_context::MathContext;
use termc_model::math_result::MathResult;
use termc_ui::{TerminalUI, TerminalMode};
use command_library::{CommandType, check_for_command};
/// The main entry point.
pub fn main() {
let mut args = get_arguments();
// If there are command line arguments given, start in call mode.
// Otherwise start in interactive mode.
if args.len() > 1 {
start_call(& mut args);
}
else {
let path = args.pop().unwrap(); // get path of this executable
start_interactive(path);
}
}
/// Returns the math expression command line arguments.
fn get_arguments() -> Vec<String> {
let args_it = env::args();
args_it.collect()
}
fn build_default_ser_path(exe_path: &str) -> String {
let default_fd = Path::new(exe_path).parent().unwrap(); // remove termc executable name
let default_fn = Path::new("termc_context.json"); // define default file name
default_fd.join(default_fn).to_str().unwrap().to_string() // join current path and default file name
}
/// Starts termc in command line call mode.
/// Prints a ';'-separated list with the results of the specified mathematical expressions.
fn start_call(args: & mut Vec<String>) {
// compute default file-path for the serialization file
let mut iter = args.iter();
let path_str : String = iter.next().unwrap().to_string(); // get path of this executable
let default_file = build_default_ser_path(&path_str);
// create terminal handle
let mut terminal = TerminalUI::new(TerminalMode::Call);
let mut results : Vec<MathResult> = Vec::new();
let mut context = MathContext::new();
// for each argument given, evaluate it and store the results
// if an error occurs for any of the given arguments, the evaluation of all arguments will be aborted
for (i, arg) in iter.enumerate() {
match check_for_command(arg, &mut context, &mut terminal, default_file.clone()) {
|
_ => ()
}
},
None => {
match get_result(arg.trim(), & mut context) {
Ok(result) => {
match result {
Some(y) => results.push(y),
None => ()
}
},
Err(err) => {
terminal.print(&format!("In input {0}:\n", i+1));
terminal.print_error(err);
break;
}
}
}
}
},
Err(e) => terminal.print_error(e)
}
}
terminal.print_results(&results);
}
/// Starts termc in command line interactive mode.
fn start_interactive(path_str: String) {
// compute default file-path for the serialization file
let default_file = build_default_ser_path(&path_str);
// create terminal handle
let mut terminal = TerminalUI::new(TerminalMode::Interactive);
// terminal.init();
let mut context = MathContext::new();
// REPL: take user input, evaluate it and print results / errors
loop {
let user_input = terminal.get_user_input();
let user_input = user_input.trim();
if user_input.len() == 0 {
continue;
}
match check_for_command(user_input, &mut context, &mut terminal, default_file.clone()) {
Ok(k) => {
match k {
Some(command_type) => {
match command_type {
CommandType::Exit => break,
_ => terminal.print_cmd_ack()
}
},
None => {
match get_result(& user_input, & mut context) {
Ok(result) => {
match result {
Some(y) => terminal.print_result(&y),
None => ()
}
},
Err(err) => {
terminal.print_error(err);
}
}
}
}
},
Err(e) => terminal.print_error(e)
}
}
match terminal.save_history_file() {
Ok(_) => (),
Err(e) => terminal.print_error(e)
}
}
|
Ok(k) => {
match k {
Some(command_type) => {
match command_type {
CommandType::Exit => break,
|
random_line_split
|
main.rs
|
#[macro_use]
extern crate lazy_static;
extern crate termc_model;
extern crate termc_ui;
extern crate serde_json;
extern crate regex;
mod command_library;
use std::env;
use std::path::Path;
use termc_model::get_result;
use termc_model::math_context::MathContext;
use termc_model::math_result::MathResult;
use termc_ui::{TerminalUI, TerminalMode};
use command_library::{CommandType, check_for_command};
/// The main entry point.
pub fn main() {
let mut args = get_arguments();
// If there are command line arguments given, start in call mode.
// Otherwise start in interactive mode.
if args.len() > 1 {
start_call(& mut args);
}
else {
let path = args.pop().unwrap(); // get path of this executable
start_interactive(path);
}
}
/// Returns the math expression command line arguments.
fn get_arguments() -> Vec<String> {
let args_it = env::args();
args_it.collect()
}
fn build_default_ser_path(exe_path: &str) -> String
|
/// Starts termc in command line call mode.
/// Prints a ';'-separated list with the results of the specified mathematical expressions.
fn start_call(args: & mut Vec<String>) {
// compute default file-path for the serialization file
let mut iter = args.iter();
let path_str : String = iter.next().unwrap().to_string(); // get path of this executable
let default_file = build_default_ser_path(&path_str);
// create terminal handle
let mut terminal = TerminalUI::new(TerminalMode::Call);
let mut results : Vec<MathResult> = Vec::new();
let mut context = MathContext::new();
// for each argument given, evaluate it and store the results
// if an error occurs for any of the given arguments, the evaluation of all arguments will be aborted
for (i, arg) in iter.enumerate() {
match check_for_command(arg, &mut context, &mut terminal, default_file.clone()) {
Ok(k) => {
match k {
Some(command_type) => {
match command_type {
CommandType::Exit => break,
_ => ()
}
},
None => {
match get_result(arg.trim(), & mut context) {
Ok(result) => {
match result {
Some(y) => results.push(y),
None => ()
}
},
Err(err) => {
terminal.print(&format!("In input {0}:\n", i+1));
terminal.print_error(err);
break;
}
}
}
}
},
Err(e) => terminal.print_error(e)
}
}
terminal.print_results(&results);
}
/// Starts termc in command line interactive mode.
fn start_interactive(path_str: String) {
// compute default file-path for the serialization file
let default_file = build_default_ser_path(&path_str);
// create terminal handle
let mut terminal = TerminalUI::new(TerminalMode::Interactive);
// terminal.init();
let mut context = MathContext::new();
// REPL: take user input, evaluate it and print results / errors
loop {
let user_input = terminal.get_user_input();
let user_input = user_input.trim();
if user_input.len() == 0 {
continue;
}
match check_for_command(user_input, &mut context, &mut terminal, default_file.clone()) {
Ok(k) => {
match k {
Some(command_type) => {
match command_type {
CommandType::Exit => break,
_ => terminal.print_cmd_ack()
}
},
None => {
match get_result(& user_input, & mut context) {
Ok(result) => {
match result {
Some(y) => terminal.print_result(&y),
None => ()
}
},
Err(err) => {
terminal.print_error(err);
}
}
}
}
},
Err(e) => terminal.print_error(e)
}
}
match terminal.save_history_file() {
Ok(_) => (),
Err(e) => terminal.print_error(e)
}
}
|
{
let default_fd = Path::new(exe_path).parent().unwrap(); // remove termc executable name
let default_fn = Path::new("termc_context.json"); // define default file name
default_fd.join(default_fn).to_str().unwrap().to_string() // join current path and default file name
}
|
identifier_body
|
settings.rs
|
extern crate serde;
extern crate serde_json;
include!(concat!(env!("OUT_DIR"), "\\serde_types.rs"));
use std::io::prelude::*;
use std::fs::File;
use std::process::exit;
pub trait Settings {
fn get_socket_port(&self) -> u16;
}
pub struct SettingsImpl {
pub settings_file_path:String,
pub settings_data: SettingsData,
}
impl SettingsImpl {
pub fn
|
(&mut self) {
let mut file: File = match File::open(&self.settings_file_path) {
Err(e) => {
println!("Error: {0}. couldn't find file at location: {1}", e, self.settings_file_path);
exit(1); // TODO: should probably return false, and then have process exit with one on context init failure
},
Ok(f) => f,
};
let mut json_string = String::new();
match file.read_to_string(&mut json_string) {
Err(e) => println!("Error: {0}. couldn't read from file at location: {1}", e, self.settings_file_path),
Ok(bytes) => println!("bytes_read: {0}, string read:\n{1}", bytes, json_string),
}
let loaded_settings_data: SettingsData = match serde_json::from_str(json_string.as_ref()) {
Err(e) => {
println!("Error {0}, problem serializing into SettingsData from:\n{1}", e, json_string);
return;
},
Ok(s) => s,
};
self.settings_data = loaded_settings_data;
}
}
impl Settings for SettingsImpl {
fn get_socket_port(&self) -> u16 {
return self.settings_data.socket_port;
}
}
|
init
|
identifier_name
|
settings.rs
|
extern crate serde;
extern crate serde_json;
include!(concat!(env!("OUT_DIR"), "\\serde_types.rs"));
use std::io::prelude::*;
use std::fs::File;
use std::process::exit;
pub trait Settings {
fn get_socket_port(&self) -> u16;
}
pub struct SettingsImpl {
pub settings_file_path:String,
pub settings_data: SettingsData,
}
impl SettingsImpl {
pub fn init(&mut self) {
let mut file: File = match File::open(&self.settings_file_path) {
Err(e) => {
println!("Error: {0}. couldn't find file at location: {1}", e, self.settings_file_path);
exit(1); // TODO: should probably return false, and then have process exit with one on context init failure
},
Ok(f) => f,
};
let mut json_string = String::new();
match file.read_to_string(&mut json_string) {
Err(e) => println!("Error: {0}. couldn't read from file at location: {1}", e, self.settings_file_path),
Ok(bytes) => println!("bytes_read: {0}, string read:\n{1}", bytes, json_string),
}
let loaded_settings_data: SettingsData = match serde_json::from_str(json_string.as_ref()) {
Err(e) => {
|
self.settings_data = loaded_settings_data;
}
}
impl Settings for SettingsImpl {
fn get_socket_port(&self) -> u16 {
return self.settings_data.socket_port;
}
}
|
println!("Error {0}, problem serializing into SettingsData from:\n{1}", e, json_string);
return;
},
Ok(s) => s,
};
|
random_line_split
|
font_chooser_dialog.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widget!(FontChooserDialog);
impl FontChooserDialog {
pub fn new(title: &str, parent: Option<&::Window>) -> Option<FontChooserDialog>
|
}
impl_drop!(FontChooserDialog);
impl_TraitWidget!(FontChooserDialog);
impl ::ContainerTrait for FontChooserDialog {}
impl ::BinTrait for FontChooserDialog {}
impl ::WindowTrait for FontChooserDialog {}
impl ::DialogTrait for FontChooserDialog {}
impl ::FontChooserTrait for FontChooserDialog {}
|
{
let tmp = unsafe {
ffi::gtk_font_chooser_dialog_new(title.to_glib_none().0,
match parent {
Some(ref p) => GTK_WINDOW(p.unwrap_widget()),
None => GTK_WINDOW(::std::ptr::null_mut())
}
)
};
if tmp.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp))
}
}
|
identifier_body
|
font_chooser_dialog.rs
|
// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use FFIWidget;
use cast::{GTK_WINDOW};
use glib::translate::ToGlibPtr;
struct_Widget!(FontChooserDialog);
impl FontChooserDialog {
pub fn
|
(title: &str, parent: Option<&::Window>) -> Option<FontChooserDialog> {
let tmp = unsafe {
ffi::gtk_font_chooser_dialog_new(title.to_glib_none().0,
match parent {
Some(ref p) => GTK_WINDOW(p.unwrap_widget()),
None => GTK_WINDOW(::std::ptr::null_mut())
}
)
};
if tmp.is_null() {
None
} else {
Some(::FFIWidget::wrap_widget(tmp))
}
}
}
impl_drop!(FontChooserDialog);
impl_TraitWidget!(FontChooserDialog);
impl ::ContainerTrait for FontChooserDialog {}
impl ::BinTrait for FontChooserDialog {}
impl ::WindowTrait for FontChooserDialog {}
impl ::DialogTrait for FontChooserDialog {}
impl ::FontChooserTrait for FontChooserDialog {}
|
new
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.