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 |
---|---|---|---|---|
dom_html_html_element.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct DOMHTMLHtmlElement(Object<ffi::WebKitDOMHTMLHtmlElement, ffi::WebKitDOMHTMLHtmlElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
type_ => || ffi::webkit_dom_html_html_element_get_type(),
}
}
pub const NONE_DOMHTML_HTML_ELEMENT: Option<&DOMHTMLHtmlElement> = None;
pub trait DOMHTMLHtmlElementExt:'static {
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_get_version")]
fn version(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_set_version")]
fn set_version(&self, value: &str);
fn connect_property_version_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLHtmlElement>> DOMHTMLHtmlElementExt for O {
fn version(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_html_html_element_get_version(
self.as_ref().to_glib_none().0,
))
}
}
fn set_version(&self, value: &str) {
unsafe {
ffi::webkit_dom_html_html_element_set_version(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn connect_property_version_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_version_trampoline<P, F: Fn(&P) +'static>(
this: *mut ffi::WebKitDOMHTMLHtmlElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLHtmlElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLHtmlElement::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::version\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_version_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMHTMLHtmlElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
f.write_str("DOMHTMLHtmlElement")
}
}
|
random_line_split
|
|
dom_html_html_element.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct DOMHTMLHtmlElement(Object<ffi::WebKitDOMHTMLHtmlElement, ffi::WebKitDOMHTMLHtmlElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
type_ => || ffi::webkit_dom_html_html_element_get_type(),
}
}
pub const NONE_DOMHTML_HTML_ELEMENT: Option<&DOMHTMLHtmlElement> = None;
pub trait DOMHTMLHtmlElementExt:'static {
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_get_version")]
fn version(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_set_version")]
fn set_version(&self, value: &str);
fn connect_property_version_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLHtmlElement>> DOMHTMLHtmlElementExt for O {
fn version(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_html_html_element_get_version(
self.as_ref().to_glib_none().0,
))
}
}
fn set_version(&self, value: &str) {
unsafe {
ffi::webkit_dom_html_html_element_set_version(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn connect_property_version_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn
|
<P, F: Fn(&P) +'static>(
this: *mut ffi::WebKitDOMHTMLHtmlElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLHtmlElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLHtmlElement::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::version\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_version_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMHTMLHtmlElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DOMHTMLHtmlElement")
}
}
|
notify_version_trampoline
|
identifier_name
|
dom_html_html_element.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct DOMHTMLHtmlElement(Object<ffi::WebKitDOMHTMLHtmlElement, ffi::WebKitDOMHTMLHtmlElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
type_ => || ffi::webkit_dom_html_html_element_get_type(),
}
}
pub const NONE_DOMHTML_HTML_ELEMENT: Option<&DOMHTMLHtmlElement> = None;
pub trait DOMHTMLHtmlElementExt:'static {
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_get_version")]
fn version(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_set_version")]
fn set_version(&self, value: &str);
fn connect_property_version_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLHtmlElement>> DOMHTMLHtmlElementExt for O {
fn version(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_html_html_element_get_version(
self.as_ref().to_glib_none().0,
))
}
}
fn set_version(&self, value: &str) {
unsafe {
ffi::webkit_dom_html_html_element_set_version(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn connect_property_version_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId
|
)
}
}
}
impl fmt::Display for DOMHTMLHtmlElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DOMHTMLHtmlElement")
}
}
|
{
unsafe extern "C" fn notify_version_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMHTMLHtmlElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLHtmlElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLHtmlElement::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::version\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_version_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
|
identifier_body
|
armv7s_apple_ios.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.
use target::{Target, TargetOptions};
use super::apple_ios_base::{opts, Arch};
pub fn
|
() -> Target {
Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: TargetOptions {
features: "+v7,+vfp4,+neon".to_string(),
.. opts(Arch::Armv7s)
}
}
}
|
target
|
identifier_name
|
armv7s_apple_ios.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.
use target::{Target, TargetOptions};
use super::apple_ios_base::{opts, Arch};
pub fn target() -> Target
|
{
Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: TargetOptions {
features: "+v7,+vfp4,+neon".to_string(),
.. opts(Arch::Armv7s)
}
}
}
|
identifier_body
|
|
armv7s_apple_ios.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.
use target::{Target, TargetOptions};
|
Target {
llvm_target: "armv7s-apple-ios".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
arch: "arm".to_string(),
target_os: "ios".to_string(),
target_env: "".to_string(),
options: TargetOptions {
features: "+v7,+vfp4,+neon".to_string(),
.. opts(Arch::Armv7s)
}
}
}
|
use super::apple_ios_base::{opts, Arch};
pub fn target() -> Target {
|
random_line_split
|
mod.rs
|
use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer;
pub use read_write::Metadata;
const TERRAIN_FRAGMENT_SHADER: &str = include_str!("../../shaders/terrain.fs");
const TERRAIN_VERTEX_SHADER: &str = include_str!("../../shaders/terrain.vs");
const TERRAIN_GEOMETRY_SHADER: &str = include_str!("../../shaders/terrain.gs");
const GRID_SIZE: u32 = 1023;
pub struct TerrainRenderer {
program: GlProgram,
u_transform: GlUniform<Matrix4<f64>>,
vertex_array: GlVertexArray,
#[allow(dead_code)]
buffer_position: GlBuffer,
#[allow(dead_code)]
buffer_indices: GlBuffer,
num_indices: usize,
terrain_layers: Vec<TerrainLayer>,
}
impl TerrainRenderer {
pub fn new<I>(gl: Rc<opengl::Gl>, terrain_paths: I) -> Self
where
I: Iterator,
|
.geometry_shader(TERRAIN_GEOMETRY_SHADER)
.fragment_shader(TERRAIN_FRAGMENT_SHADER)
.build();
// TODO(nnmm): If our initial position as returned by local_from_global is very different
// from (0, 0, 0), the first call to camera_changed() will be very resource intensive
let u_transform = GlUniform::new(&program, "world_to_gl", Matrix4::identity());
let vertex_array = GlVertexArray::new(Rc::clone(&gl));
let (buffer_position, buffer_indices, num_indices) =
Self::create_mesh(&program, &vertex_array, Rc::clone(&gl));
let terrain_layers = terrain_paths
.map(|p| TerrainLayer::new(&program, p, GRID_SIZE + 1).unwrap())
.collect();
Self {
program,
u_transform,
vertex_array,
buffer_position,
buffer_indices,
num_indices,
terrain_layers,
}
}
fn create_mesh(
program: &GlProgram,
vertex_array: &GlVertexArray,
gl: Rc<opengl::Gl>,
) -> (GlBuffer, GlBuffer, usize) {
let num_vertices = (GRID_SIZE + 1) * (GRID_SIZE + 1) * 3;
let mut vertices: Vec<i32> = Vec::with_capacity(num_vertices as usize);
for iy in 0..=GRID_SIZE as i32 {
for ix in 0..=GRID_SIZE as i32 {
vertices.push(ix);
vertices.push(iy);
vertices.push(0);
}
}
let flat_ix = |x: GLuint, y: GLuint| y * (GRID_SIZE + 1) as GLuint + x;
let num_indices = GRID_SIZE * GRID_SIZE * 3 * 2;
let mut indices: Vec<GLuint> = Vec::with_capacity(num_indices as usize);
for iy in 0..GRID_SIZE as GLuint {
for ix in 0..GRID_SIZE as GLuint {
// Two triangles = one quad
indices.push(flat_ix(ix, iy));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy + 1));
}
}
// See https://learnopengl.com/Getting-started/Hello-Triangle, section
// "Vertex Array Object" for background on buffers and vertex array objects
vertex_array.bind();
let buffer_position = GlBuffer::new_array_buffer(Rc::clone(&gl));
let buffer_indices = GlBuffer::new_element_array_buffer(Rc::clone(&gl));
buffer_position.bind();
unsafe {
program.gl.BufferData(
opengl::ARRAY_BUFFER,
(vertices.len() * mem::size_of::<i32>()) as GLsizeiptr,
vertices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
let pos_attr = gl.GetAttribLocation(program.id, c_str!("aPos")) as GLuint;
gl.EnableVertexAttribArray(pos_attr);
// aPos is an ivec3. If we wanted, we could make it an ivec2 or a single index.
gl.VertexAttribIPointer(
pos_attr,
3,
opengl::INT,
3 * mem::size_of::<i32>() as i32,
std::ptr::null(), // no offset
);
}
buffer_indices.bind();
unsafe {
program.gl.BufferData(
opengl::ELEMENT_ARRAY_BUFFER,
(indices.len() * mem::size_of::<GLuint>()) as GLsizeiptr,
indices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
}
(buffer_position, buffer_indices, indices.len())
}
pub fn camera_changed(&mut self, world_to_gl: &Matrix4<f64>, camera_to_world: &Isometry3<f64>) {
let camera_pos = Point3::from(camera_to_world.translation.vector);
self.terrain_layers
.iter_mut()
.for_each(|layer| layer.update(camera_pos));
self.u_transform.value = *world_to_gl;
}
pub fn draw(&mut self) {
if self.terrain_layers.is_empty() {
return;
}
unsafe {
self.vertex_array.bind();
// Switch from the point cloud rendering shader to terrain shader
self.program.gl.UseProgram(self.program.id);
// Activate wireframe mode
self.program
.gl
.PolygonMode(opengl::FRONT_AND_BACK, opengl::LINE);
self.u_transform.submit();
// If you want the terrain to have alpha < 1, put this before
// the DrawElements call:
// self.program.gl.Enable(opengl::BLEND);
// self.program
// .gl
// .BlendFunc(opengl::SRC_ALPHA, opengl::ONE_MINUS_SRC_ALPHA);
// And after:
// self.program.gl.Disable(opengl::BLEND);
for layer in self.terrain_layers.iter() {
// Set the terrain to be used with the next draw call
layer.submit();
// Draw the mesh using the current terrain data
self.program.gl.DrawElements(
opengl::TRIANGLES,
self.num_indices as i32,
opengl::UNSIGNED_INT,
std::ptr::null(), // no offset
);
}
}
}
pub fn local_from_global(&self) -> Option<Isometry3<f64>> {
self.terrain_layers
.first()
.map(|layer| *layer.terrain_from_world())
}
}
|
I::Item: AsRef<std::path::Path>,
{
let program =
GlProgramBuilder::new_with_vertex_shader(Rc::clone(&gl), TERRAIN_VERTEX_SHADER)
|
random_line_split
|
mod.rs
|
use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer;
pub use read_write::Metadata;
const TERRAIN_FRAGMENT_SHADER: &str = include_str!("../../shaders/terrain.fs");
const TERRAIN_VERTEX_SHADER: &str = include_str!("../../shaders/terrain.vs");
const TERRAIN_GEOMETRY_SHADER: &str = include_str!("../../shaders/terrain.gs");
const GRID_SIZE: u32 = 1023;
pub struct TerrainRenderer {
program: GlProgram,
u_transform: GlUniform<Matrix4<f64>>,
vertex_array: GlVertexArray,
#[allow(dead_code)]
buffer_position: GlBuffer,
#[allow(dead_code)]
buffer_indices: GlBuffer,
num_indices: usize,
terrain_layers: Vec<TerrainLayer>,
}
impl TerrainRenderer {
pub fn new<I>(gl: Rc<opengl::Gl>, terrain_paths: I) -> Self
where
I: Iterator,
I::Item: AsRef<std::path::Path>,
{
let program =
GlProgramBuilder::new_with_vertex_shader(Rc::clone(&gl), TERRAIN_VERTEX_SHADER)
.geometry_shader(TERRAIN_GEOMETRY_SHADER)
.fragment_shader(TERRAIN_FRAGMENT_SHADER)
.build();
// TODO(nnmm): If our initial position as returned by local_from_global is very different
// from (0, 0, 0), the first call to camera_changed() will be very resource intensive
let u_transform = GlUniform::new(&program, "world_to_gl", Matrix4::identity());
let vertex_array = GlVertexArray::new(Rc::clone(&gl));
let (buffer_position, buffer_indices, num_indices) =
Self::create_mesh(&program, &vertex_array, Rc::clone(&gl));
let terrain_layers = terrain_paths
.map(|p| TerrainLayer::new(&program, p, GRID_SIZE + 1).unwrap())
.collect();
Self {
program,
u_transform,
vertex_array,
buffer_position,
buffer_indices,
num_indices,
terrain_layers,
}
}
fn
|
(
program: &GlProgram,
vertex_array: &GlVertexArray,
gl: Rc<opengl::Gl>,
) -> (GlBuffer, GlBuffer, usize) {
let num_vertices = (GRID_SIZE + 1) * (GRID_SIZE + 1) * 3;
let mut vertices: Vec<i32> = Vec::with_capacity(num_vertices as usize);
for iy in 0..=GRID_SIZE as i32 {
for ix in 0..=GRID_SIZE as i32 {
vertices.push(ix);
vertices.push(iy);
vertices.push(0);
}
}
let flat_ix = |x: GLuint, y: GLuint| y * (GRID_SIZE + 1) as GLuint + x;
let num_indices = GRID_SIZE * GRID_SIZE * 3 * 2;
let mut indices: Vec<GLuint> = Vec::with_capacity(num_indices as usize);
for iy in 0..GRID_SIZE as GLuint {
for ix in 0..GRID_SIZE as GLuint {
// Two triangles = one quad
indices.push(flat_ix(ix, iy));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy + 1));
}
}
// See https://learnopengl.com/Getting-started/Hello-Triangle, section
// "Vertex Array Object" for background on buffers and vertex array objects
vertex_array.bind();
let buffer_position = GlBuffer::new_array_buffer(Rc::clone(&gl));
let buffer_indices = GlBuffer::new_element_array_buffer(Rc::clone(&gl));
buffer_position.bind();
unsafe {
program.gl.BufferData(
opengl::ARRAY_BUFFER,
(vertices.len() * mem::size_of::<i32>()) as GLsizeiptr,
vertices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
let pos_attr = gl.GetAttribLocation(program.id, c_str!("aPos")) as GLuint;
gl.EnableVertexAttribArray(pos_attr);
// aPos is an ivec3. If we wanted, we could make it an ivec2 or a single index.
gl.VertexAttribIPointer(
pos_attr,
3,
opengl::INT,
3 * mem::size_of::<i32>() as i32,
std::ptr::null(), // no offset
);
}
buffer_indices.bind();
unsafe {
program.gl.BufferData(
opengl::ELEMENT_ARRAY_BUFFER,
(indices.len() * mem::size_of::<GLuint>()) as GLsizeiptr,
indices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
}
(buffer_position, buffer_indices, indices.len())
}
pub fn camera_changed(&mut self, world_to_gl: &Matrix4<f64>, camera_to_world: &Isometry3<f64>) {
let camera_pos = Point3::from(camera_to_world.translation.vector);
self.terrain_layers
.iter_mut()
.for_each(|layer| layer.update(camera_pos));
self.u_transform.value = *world_to_gl;
}
pub fn draw(&mut self) {
if self.terrain_layers.is_empty() {
return;
}
unsafe {
self.vertex_array.bind();
// Switch from the point cloud rendering shader to terrain shader
self.program.gl.UseProgram(self.program.id);
// Activate wireframe mode
self.program
.gl
.PolygonMode(opengl::FRONT_AND_BACK, opengl::LINE);
self.u_transform.submit();
// If you want the terrain to have alpha < 1, put this before
// the DrawElements call:
// self.program.gl.Enable(opengl::BLEND);
// self.program
// .gl
// .BlendFunc(opengl::SRC_ALPHA, opengl::ONE_MINUS_SRC_ALPHA);
// And after:
// self.program.gl.Disable(opengl::BLEND);
for layer in self.terrain_layers.iter() {
// Set the terrain to be used with the next draw call
layer.submit();
// Draw the mesh using the current terrain data
self.program.gl.DrawElements(
opengl::TRIANGLES,
self.num_indices as i32,
opengl::UNSIGNED_INT,
std::ptr::null(), // no offset
);
}
}
}
pub fn local_from_global(&self) -> Option<Isometry3<f64>> {
self.terrain_layers
.first()
.map(|layer| *layer.terrain_from_world())
}
}
|
create_mesh
|
identifier_name
|
mod.rs
|
use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer;
pub use read_write::Metadata;
const TERRAIN_FRAGMENT_SHADER: &str = include_str!("../../shaders/terrain.fs");
const TERRAIN_VERTEX_SHADER: &str = include_str!("../../shaders/terrain.vs");
const TERRAIN_GEOMETRY_SHADER: &str = include_str!("../../shaders/terrain.gs");
const GRID_SIZE: u32 = 1023;
pub struct TerrainRenderer {
program: GlProgram,
u_transform: GlUniform<Matrix4<f64>>,
vertex_array: GlVertexArray,
#[allow(dead_code)]
buffer_position: GlBuffer,
#[allow(dead_code)]
buffer_indices: GlBuffer,
num_indices: usize,
terrain_layers: Vec<TerrainLayer>,
}
impl TerrainRenderer {
pub fn new<I>(gl: Rc<opengl::Gl>, terrain_paths: I) -> Self
where
I: Iterator,
I::Item: AsRef<std::path::Path>,
{
let program =
GlProgramBuilder::new_with_vertex_shader(Rc::clone(&gl), TERRAIN_VERTEX_SHADER)
.geometry_shader(TERRAIN_GEOMETRY_SHADER)
.fragment_shader(TERRAIN_FRAGMENT_SHADER)
.build();
// TODO(nnmm): If our initial position as returned by local_from_global is very different
// from (0, 0, 0), the first call to camera_changed() will be very resource intensive
let u_transform = GlUniform::new(&program, "world_to_gl", Matrix4::identity());
let vertex_array = GlVertexArray::new(Rc::clone(&gl));
let (buffer_position, buffer_indices, num_indices) =
Self::create_mesh(&program, &vertex_array, Rc::clone(&gl));
let terrain_layers = terrain_paths
.map(|p| TerrainLayer::new(&program, p, GRID_SIZE + 1).unwrap())
.collect();
Self {
program,
u_transform,
vertex_array,
buffer_position,
buffer_indices,
num_indices,
terrain_layers,
}
}
fn create_mesh(
program: &GlProgram,
vertex_array: &GlVertexArray,
gl: Rc<opengl::Gl>,
) -> (GlBuffer, GlBuffer, usize)
|
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy + 1));
}
}
// See https://learnopengl.com/Getting-started/Hello-Triangle, section
// "Vertex Array Object" for background on buffers and vertex array objects
vertex_array.bind();
let buffer_position = GlBuffer::new_array_buffer(Rc::clone(&gl));
let buffer_indices = GlBuffer::new_element_array_buffer(Rc::clone(&gl));
buffer_position.bind();
unsafe {
program.gl.BufferData(
opengl::ARRAY_BUFFER,
(vertices.len() * mem::size_of::<i32>()) as GLsizeiptr,
vertices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
let pos_attr = gl.GetAttribLocation(program.id, c_str!("aPos")) as GLuint;
gl.EnableVertexAttribArray(pos_attr);
// aPos is an ivec3. If we wanted, we could make it an ivec2 or a single index.
gl.VertexAttribIPointer(
pos_attr,
3,
opengl::INT,
3 * mem::size_of::<i32>() as i32,
std::ptr::null(), // no offset
);
}
buffer_indices.bind();
unsafe {
program.gl.BufferData(
opengl::ELEMENT_ARRAY_BUFFER,
(indices.len() * mem::size_of::<GLuint>()) as GLsizeiptr,
indices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
}
(buffer_position, buffer_indices, indices.len())
}
pub fn camera_changed(&mut self, world_to_gl: &Matrix4<f64>, camera_to_world: &Isometry3<f64>) {
let camera_pos = Point3::from(camera_to_world.translation.vector);
self.terrain_layers
.iter_mut()
.for_each(|layer| layer.update(camera_pos));
self.u_transform.value = *world_to_gl;
}
pub fn draw(&mut self) {
if self.terrain_layers.is_empty() {
return;
}
unsafe {
self.vertex_array.bind();
// Switch from the point cloud rendering shader to terrain shader
self.program.gl.UseProgram(self.program.id);
// Activate wireframe mode
self.program
.gl
.PolygonMode(opengl::FRONT_AND_BACK, opengl::LINE);
self.u_transform.submit();
// If you want the terrain to have alpha < 1, put this before
// the DrawElements call:
// self.program.gl.Enable(opengl::BLEND);
// self.program
// .gl
// .BlendFunc(opengl::SRC_ALPHA, opengl::ONE_MINUS_SRC_ALPHA);
// And after:
// self.program.gl.Disable(opengl::BLEND);
for layer in self.terrain_layers.iter() {
// Set the terrain to be used with the next draw call
layer.submit();
// Draw the mesh using the current terrain data
self.program.gl.DrawElements(
opengl::TRIANGLES,
self.num_indices as i32,
opengl::UNSIGNED_INT,
std::ptr::null(), // no offset
);
}
}
}
pub fn local_from_global(&self) -> Option<Isometry3<f64>> {
self.terrain_layers
.first()
.map(|layer| *layer.terrain_from_world())
}
}
|
{
let num_vertices = (GRID_SIZE + 1) * (GRID_SIZE + 1) * 3;
let mut vertices: Vec<i32> = Vec::with_capacity(num_vertices as usize);
for iy in 0..=GRID_SIZE as i32 {
for ix in 0..=GRID_SIZE as i32 {
vertices.push(ix);
vertices.push(iy);
vertices.push(0);
}
}
let flat_ix = |x: GLuint, y: GLuint| y * (GRID_SIZE + 1) as GLuint + x;
let num_indices = GRID_SIZE * GRID_SIZE * 3 * 2;
let mut indices: Vec<GLuint> = Vec::with_capacity(num_indices as usize);
for iy in 0..GRID_SIZE as GLuint {
for ix in 0..GRID_SIZE as GLuint {
// Two triangles = one quad
indices.push(flat_ix(ix, iy));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
|
identifier_body
|
mod.rs
|
use crate::c_str;
use crate::graphic::{GlBuffer, GlProgram, GlProgramBuilder, GlUniform, GlVertexArray};
use crate::opengl;
use nalgebra::{Isometry3, Matrix4, Point3};
use opengl::types::{GLsizeiptr, GLuint};
use std::ffi::c_void;
use std::mem;
use std::rc::Rc;
mod layer;
mod read_write;
pub use layer::TerrainLayer;
pub use read_write::Metadata;
const TERRAIN_FRAGMENT_SHADER: &str = include_str!("../../shaders/terrain.fs");
const TERRAIN_VERTEX_SHADER: &str = include_str!("../../shaders/terrain.vs");
const TERRAIN_GEOMETRY_SHADER: &str = include_str!("../../shaders/terrain.gs");
const GRID_SIZE: u32 = 1023;
pub struct TerrainRenderer {
program: GlProgram,
u_transform: GlUniform<Matrix4<f64>>,
vertex_array: GlVertexArray,
#[allow(dead_code)]
buffer_position: GlBuffer,
#[allow(dead_code)]
buffer_indices: GlBuffer,
num_indices: usize,
terrain_layers: Vec<TerrainLayer>,
}
impl TerrainRenderer {
pub fn new<I>(gl: Rc<opengl::Gl>, terrain_paths: I) -> Self
where
I: Iterator,
I::Item: AsRef<std::path::Path>,
{
let program =
GlProgramBuilder::new_with_vertex_shader(Rc::clone(&gl), TERRAIN_VERTEX_SHADER)
.geometry_shader(TERRAIN_GEOMETRY_SHADER)
.fragment_shader(TERRAIN_FRAGMENT_SHADER)
.build();
// TODO(nnmm): If our initial position as returned by local_from_global is very different
// from (0, 0, 0), the first call to camera_changed() will be very resource intensive
let u_transform = GlUniform::new(&program, "world_to_gl", Matrix4::identity());
let vertex_array = GlVertexArray::new(Rc::clone(&gl));
let (buffer_position, buffer_indices, num_indices) =
Self::create_mesh(&program, &vertex_array, Rc::clone(&gl));
let terrain_layers = terrain_paths
.map(|p| TerrainLayer::new(&program, p, GRID_SIZE + 1).unwrap())
.collect();
Self {
program,
u_transform,
vertex_array,
buffer_position,
buffer_indices,
num_indices,
terrain_layers,
}
}
fn create_mesh(
program: &GlProgram,
vertex_array: &GlVertexArray,
gl: Rc<opengl::Gl>,
) -> (GlBuffer, GlBuffer, usize) {
let num_vertices = (GRID_SIZE + 1) * (GRID_SIZE + 1) * 3;
let mut vertices: Vec<i32> = Vec::with_capacity(num_vertices as usize);
for iy in 0..=GRID_SIZE as i32 {
for ix in 0..=GRID_SIZE as i32 {
vertices.push(ix);
vertices.push(iy);
vertices.push(0);
}
}
let flat_ix = |x: GLuint, y: GLuint| y * (GRID_SIZE + 1) as GLuint + x;
let num_indices = GRID_SIZE * GRID_SIZE * 3 * 2;
let mut indices: Vec<GLuint> = Vec::with_capacity(num_indices as usize);
for iy in 0..GRID_SIZE as GLuint {
for ix in 0..GRID_SIZE as GLuint {
// Two triangles = one quad
indices.push(flat_ix(ix, iy));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy));
indices.push(flat_ix(ix, iy + 1));
indices.push(flat_ix(ix + 1, iy + 1));
}
}
// See https://learnopengl.com/Getting-started/Hello-Triangle, section
// "Vertex Array Object" for background on buffers and vertex array objects
vertex_array.bind();
let buffer_position = GlBuffer::new_array_buffer(Rc::clone(&gl));
let buffer_indices = GlBuffer::new_element_array_buffer(Rc::clone(&gl));
buffer_position.bind();
unsafe {
program.gl.BufferData(
opengl::ARRAY_BUFFER,
(vertices.len() * mem::size_of::<i32>()) as GLsizeiptr,
vertices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
let pos_attr = gl.GetAttribLocation(program.id, c_str!("aPos")) as GLuint;
gl.EnableVertexAttribArray(pos_attr);
// aPos is an ivec3. If we wanted, we could make it an ivec2 or a single index.
gl.VertexAttribIPointer(
pos_attr,
3,
opengl::INT,
3 * mem::size_of::<i32>() as i32,
std::ptr::null(), // no offset
);
}
buffer_indices.bind();
unsafe {
program.gl.BufferData(
opengl::ELEMENT_ARRAY_BUFFER,
(indices.len() * mem::size_of::<GLuint>()) as GLsizeiptr,
indices.as_ptr() as *const c_void,
opengl::STATIC_DRAW,
);
}
(buffer_position, buffer_indices, indices.len())
}
pub fn camera_changed(&mut self, world_to_gl: &Matrix4<f64>, camera_to_world: &Isometry3<f64>) {
let camera_pos = Point3::from(camera_to_world.translation.vector);
self.terrain_layers
.iter_mut()
.for_each(|layer| layer.update(camera_pos));
self.u_transform.value = *world_to_gl;
}
pub fn draw(&mut self) {
if self.terrain_layers.is_empty()
|
unsafe {
self.vertex_array.bind();
// Switch from the point cloud rendering shader to terrain shader
self.program.gl.UseProgram(self.program.id);
// Activate wireframe mode
self.program
.gl
.PolygonMode(opengl::FRONT_AND_BACK, opengl::LINE);
self.u_transform.submit();
// If you want the terrain to have alpha < 1, put this before
// the DrawElements call:
// self.program.gl.Enable(opengl::BLEND);
// self.program
// .gl
// .BlendFunc(opengl::SRC_ALPHA, opengl::ONE_MINUS_SRC_ALPHA);
// And after:
// self.program.gl.Disable(opengl::BLEND);
for layer in self.terrain_layers.iter() {
// Set the terrain to be used with the next draw call
layer.submit();
// Draw the mesh using the current terrain data
self.program.gl.DrawElements(
opengl::TRIANGLES,
self.num_indices as i32,
opengl::UNSIGNED_INT,
std::ptr::null(), // no offset
);
}
}
}
pub fn local_from_global(&self) -> Option<Isometry3<f64>> {
self.terrain_layers
.first()
.map(|layer| *layer.terrain_from_world())
}
}
|
{
return;
}
|
conditional_block
|
stop.rs
|
use async_trait::async_trait;
use cucumber::given;
use mimir::adapters::secondary::elasticsearch::remote::connection_test_pool;
use mimir::domain::ports::secondary::remote::Remote;
use snafu::ResultExt;
use crate::error::{self, Error};
use crate::state::{GlobalState, State, Step, StepStatus};
use crate::steps::admin::IndexCosmogony;
use crate::steps::download::download_ntfs;
use mimir::adapters::secondary::elasticsearch::ElasticsearchStorageConfig;
use tests::ntfs;
#[given(regex = r"ntfs file has been indexed for ([^\s]+) as ([^\s]+)$")]
async fn index_ntfs(state: &mut GlobalState, region: String, dataset: String) {
state
.execute(IndexNTFS { region, dataset })
.await
.expect("failed to index NTFS file");
}
#[given(regex = r"stops have been indexed for ([^\s]+) as ([^\s]+)$")]
async fn stops_available(state: &mut GlobalState, region: String, dataset: String) {
download_ntfs(state, region.clone()).await;
index_ntfs(state, region, dataset).await;
}
/// Index an NTFS file for a given region into Elasticsearch.
///
/// This will require to import admins first.
#[derive(Debug, PartialEq)]
pub struct
|
{
pub region: String,
pub dataset: String,
}
#[async_trait(?Send)]
impl Step for IndexNTFS {
async fn execute(&mut self, state: &State) -> Result<StepStatus, Error> {
let Self { region, dataset } = self;
let client = connection_test_pool()
.conn(ElasticsearchStorageConfig::default_testing())
.await
.expect("Could not establish connection to Elasticsearch");
state
.status_of(&IndexCosmogony {
region: region.to_string(),
dataset: dataset.to_string(),
})
.expect("You must index admins before indexing stops");
ntfs::index_stops(&client, region, dataset, false)
.await
.map(|status| status.into())
.context(error::IndexNTFSSnafu)
}
}
|
IndexNTFS
|
identifier_name
|
stop.rs
|
use async_trait::async_trait;
use cucumber::given;
use mimir::adapters::secondary::elasticsearch::remote::connection_test_pool;
use mimir::domain::ports::secondary::remote::Remote;
use snafu::ResultExt;
use crate::error::{self, Error};
use crate::state::{GlobalState, State, Step, StepStatus};
use crate::steps::admin::IndexCosmogony;
use crate::steps::download::download_ntfs;
use mimir::adapters::secondary::elasticsearch::ElasticsearchStorageConfig;
use tests::ntfs;
#[given(regex = r"ntfs file has been indexed for ([^\s]+) as ([^\s]+)$")]
async fn index_ntfs(state: &mut GlobalState, region: String, dataset: String) {
state
.execute(IndexNTFS { region, dataset })
.await
.expect("failed to index NTFS file");
}
#[given(regex = r"stops have been indexed for ([^\s]+) as ([^\s]+)$")]
async fn stops_available(state: &mut GlobalState, region: String, dataset: String) {
download_ntfs(state, region.clone()).await;
index_ntfs(state, region, dataset).await;
}
/// Index an NTFS file for a given region into Elasticsearch.
///
/// This will require to import admins first.
#[derive(Debug, PartialEq)]
|
#[async_trait(?Send)]
impl Step for IndexNTFS {
async fn execute(&mut self, state: &State) -> Result<StepStatus, Error> {
let Self { region, dataset } = self;
let client = connection_test_pool()
.conn(ElasticsearchStorageConfig::default_testing())
.await
.expect("Could not establish connection to Elasticsearch");
state
.status_of(&IndexCosmogony {
region: region.to_string(),
dataset: dataset.to_string(),
})
.expect("You must index admins before indexing stops");
ntfs::index_stops(&client, region, dataset, false)
.await
.map(|status| status.into())
.context(error::IndexNTFSSnafu)
}
}
|
pub struct IndexNTFS {
pub region: String,
pub dataset: String,
}
|
random_line_split
|
core.rs
|
/* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// This file exposes items from the core "C" code to Rust.
use std;
use crate::filecontainer::*;
/// Opaque C types.
pub enum DetectEngineState {}
pub enum AppLayerDecoderEvents {}
pub enum AppLayerParserState {}
// From app-layer-events.h
pub type AppLayerEventType = std::os::raw::c_int;
pub const APP_LAYER_EVENT_TYPE_TRANSACTION : i32 = 1;
pub const APP_LAYER_EVENT_TYPE_PACKET : i32 = 2;
// From stream.h.
pub const STREAM_START: u8 = 0x01;
pub const STREAM_EOF: u8 = 0x02;
pub const STREAM_TOSERVER: u8 = 0x04;
pub const STREAM_TOCLIENT: u8 = 0x08;
pub const STREAM_GAP: u8 = 0x10;
pub const STREAM_DEPTH: u8 = 0x20;
pub const STREAM_MIDSTREAM:u8 = 0x40;
// Application layer protocol identifiers (app-layer-protos.h)
pub type AppProto = std::os::raw::c_int;
pub const ALPROTO_UNKNOWN : AppProto = 0;
pub static mut ALPROTO_FAILED : AppProto = 0; // updated during init
pub const IPPROTO_TCP : i32 = 6;
pub const IPPROTO_UDP : i32 = 17;
macro_rules!BIT_U32 {
($x:expr) => (1 << $x);
}
macro_rules!BIT_U64 {
($x:expr) => (1 << $x);
}
// Defined in app-layer-protos.h
extern {
pub fn StringToAppProto(proto_name: *const u8) -> AppProto;
}
//
// Function types for calls into C.
//
#[allow(non_snake_case)]
pub type SCLogMessageFunc =
extern "C" fn(level: std::os::raw::c_int,
filename: *const std::os::raw::c_char,
line: std::os::raw::c_uint,
function: *const std::os::raw::c_char,
code: std::os::raw::c_int,
message: *const std::os::raw::c_char) -> std::os::raw::c_int;
pub type DetectEngineStateFreeFunc =
extern "C" fn(state: *mut DetectEngineState);
pub type AppLayerDecoderEventsSetEventRawFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents,
event: u8);
pub type AppLayerDecoderEventsFreeEventsFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents);
pub enum SuricataStreamingBufferConfig {}
pub type SCFileOpenFileWithId = extern "C" fn (
file_container: &FileContainer,
sbcfg: &SuricataStreamingBufferConfig,
track_id: u32,
name: *const u8, name_len: u16,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileCloseFileById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileAppendDataById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFileAppendGAPById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFilePrune = extern "C" fn (
file_container: &FileContainer);
pub type SCFileContainerRecycle = extern "C" fn (
file_container: &FileContainer);
pub type SCFileSetTx = extern "C" fn (
file: &FileContainer,
tx_id: u64);
// A Suricata context that is passed in from C. This is alternative to
// using functions from Suricata directly, so they can be wrapped so
// Rust unit tests will still compile when they are not linked
// directly to the real function.
//
// This might add a little too much complexity to keep pure Rust test
// cases working.
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataContext {
pub SCLogMessage: SCLogMessageFunc,
DetectEngineStateFree: DetectEngineStateFreeFunc,
AppLayerDecoderEventsSetEventRaw: AppLayerDecoderEventsSetEventRawFunc,
AppLayerDecoderEventsFreeEvents: AppLayerDecoderEventsFreeEventsFunc,
pub FileOpenFile: SCFileOpenFileWithId,
pub FileCloseFile: SCFileCloseFileById,
pub FileAppendData: SCFileAppendDataById,
pub FileAppendGAP: SCFileAppendGAPById,
pub FileContainerRecycle: SCFileContainerRecycle,
pub FilePrune: SCFilePrune,
pub FileSetTx: SCFileSetTx,
}
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataFileContext {
pub files_sbcfg: &'static SuricataStreamingBufferConfig,
}
extern {
pub fn SCGetContext() -> &'static mut SuricataContext;
pub fn SCLogGetLogLevel() -> i32;
}
pub static mut SC: Option<&'static SuricataContext> = None;
pub fn init_ffi(context: &'static mut SuricataContext)
{
unsafe {
SC = Some(context);
ALPROTO_FAILED = StringToAppProto("failed\0".as_ptr());
}
}
#[no_mangle]
pub extern "C" fn rs_init(context: &'static mut SuricataContext)
{
init_ffi(context);
}
/// DetectEngineStateFree wrapper.
pub fn sc_detect_engine_state_free(state: *mut DetectEngineState)
{
unsafe {
if let Some(c) = SC {
(c.DetectEngineStateFree)(state);
}
}
}
/// AppLayerDecoderEventsSetEventRaw wrapper.
pub fn sc_app_layer_decoder_events_set_event_raw(
events: *mut *mut AppLayerDecoderEvents, event: u8)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsSetEventRaw)(events, event);
}
}
}
/// AppLayerDecoderEventsFreeEvents wrapper.
pub fn sc_app_layer_decoder_events_free_events(
events: *mut *mut AppLayerDecoderEvents)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsFreeEvents)(events);
}
}
}
/// Opaque flow type (defined in C)
pub enum
|
{}
/// Extern functions operating on Flow.
extern {
pub fn FlowGetLastTimeAsParts(flow: &Flow, secs: *mut u64, usecs: *mut u64);
}
/// Rust implementation of Flow.
impl Flow {
/// Return the time of the last flow update as a `Duration`
/// since the epoch.
pub fn get_last_time(&mut self) -> std::time::Duration {
unsafe {
let mut secs: u64 = 0;
let mut usecs: u64 = 0;
FlowGetLastTimeAsParts(self, &mut secs, &mut usecs);
std::time::Duration::new(secs, usecs as u32 * 1000)
}
}
}
|
Flow
|
identifier_name
|
core.rs
|
/* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// This file exposes items from the core "C" code to Rust.
use std;
use crate::filecontainer::*;
/// Opaque C types.
pub enum DetectEngineState {}
pub enum AppLayerDecoderEvents {}
pub enum AppLayerParserState {}
// From app-layer-events.h
pub type AppLayerEventType = std::os::raw::c_int;
pub const APP_LAYER_EVENT_TYPE_TRANSACTION : i32 = 1;
pub const APP_LAYER_EVENT_TYPE_PACKET : i32 = 2;
// From stream.h.
pub const STREAM_START: u8 = 0x01;
pub const STREAM_EOF: u8 = 0x02;
pub const STREAM_TOSERVER: u8 = 0x04;
pub const STREAM_TOCLIENT: u8 = 0x08;
pub const STREAM_GAP: u8 = 0x10;
pub const STREAM_DEPTH: u8 = 0x20;
pub const STREAM_MIDSTREAM:u8 = 0x40;
// Application layer protocol identifiers (app-layer-protos.h)
pub type AppProto = std::os::raw::c_int;
pub const ALPROTO_UNKNOWN : AppProto = 0;
pub static mut ALPROTO_FAILED : AppProto = 0; // updated during init
pub const IPPROTO_TCP : i32 = 6;
pub const IPPROTO_UDP : i32 = 17;
macro_rules!BIT_U32 {
($x:expr) => (1 << $x);
}
macro_rules!BIT_U64 {
($x:expr) => (1 << $x);
}
// Defined in app-layer-protos.h
extern {
pub fn StringToAppProto(proto_name: *const u8) -> AppProto;
}
//
// Function types for calls into C.
//
#[allow(non_snake_case)]
pub type SCLogMessageFunc =
extern "C" fn(level: std::os::raw::c_int,
filename: *const std::os::raw::c_char,
line: std::os::raw::c_uint,
function: *const std::os::raw::c_char,
code: std::os::raw::c_int,
message: *const std::os::raw::c_char) -> std::os::raw::c_int;
pub type DetectEngineStateFreeFunc =
extern "C" fn(state: *mut DetectEngineState);
pub type AppLayerDecoderEventsSetEventRawFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents,
event: u8);
pub type AppLayerDecoderEventsFreeEventsFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents);
pub enum SuricataStreamingBufferConfig {}
pub type SCFileOpenFileWithId = extern "C" fn (
file_container: &FileContainer,
sbcfg: &SuricataStreamingBufferConfig,
track_id: u32,
name: *const u8, name_len: u16,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileCloseFileById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileAppendDataById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFileAppendGAPById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFilePrune = extern "C" fn (
file_container: &FileContainer);
pub type SCFileContainerRecycle = extern "C" fn (
file_container: &FileContainer);
pub type SCFileSetTx = extern "C" fn (
file: &FileContainer,
tx_id: u64);
// A Suricata context that is passed in from C. This is alternative to
// using functions from Suricata directly, so they can be wrapped so
// Rust unit tests will still compile when they are not linked
// directly to the real function.
//
// This might add a little too much complexity to keep pure Rust test
// cases working.
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataContext {
pub SCLogMessage: SCLogMessageFunc,
DetectEngineStateFree: DetectEngineStateFreeFunc,
AppLayerDecoderEventsSetEventRaw: AppLayerDecoderEventsSetEventRawFunc,
AppLayerDecoderEventsFreeEvents: AppLayerDecoderEventsFreeEventsFunc,
pub FileOpenFile: SCFileOpenFileWithId,
pub FileCloseFile: SCFileCloseFileById,
pub FileAppendData: SCFileAppendDataById,
pub FileAppendGAP: SCFileAppendGAPById,
pub FileContainerRecycle: SCFileContainerRecycle,
pub FilePrune: SCFilePrune,
pub FileSetTx: SCFileSetTx,
}
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataFileContext {
pub files_sbcfg: &'static SuricataStreamingBufferConfig,
}
extern {
pub fn SCGetContext() -> &'static mut SuricataContext;
pub fn SCLogGetLogLevel() -> i32;
}
pub static mut SC: Option<&'static SuricataContext> = None;
pub fn init_ffi(context: &'static mut SuricataContext)
{
unsafe {
SC = Some(context);
ALPROTO_FAILED = StringToAppProto("failed\0".as_ptr());
}
}
#[no_mangle]
pub extern "C" fn rs_init(context: &'static mut SuricataContext)
{
init_ffi(context);
}
/// DetectEngineStateFree wrapper.
pub fn sc_detect_engine_state_free(state: *mut DetectEngineState)
{
unsafe {
if let Some(c) = SC
|
}
}
/// AppLayerDecoderEventsSetEventRaw wrapper.
pub fn sc_app_layer_decoder_events_set_event_raw(
events: *mut *mut AppLayerDecoderEvents, event: u8)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsSetEventRaw)(events, event);
}
}
}
/// AppLayerDecoderEventsFreeEvents wrapper.
pub fn sc_app_layer_decoder_events_free_events(
events: *mut *mut AppLayerDecoderEvents)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsFreeEvents)(events);
}
}
}
/// Opaque flow type (defined in C)
pub enum Flow {}
/// Extern functions operating on Flow.
extern {
pub fn FlowGetLastTimeAsParts(flow: &Flow, secs: *mut u64, usecs: *mut u64);
}
/// Rust implementation of Flow.
impl Flow {
/// Return the time of the last flow update as a `Duration`
/// since the epoch.
pub fn get_last_time(&mut self) -> std::time::Duration {
unsafe {
let mut secs: u64 = 0;
let mut usecs: u64 = 0;
FlowGetLastTimeAsParts(self, &mut secs, &mut usecs);
std::time::Duration::new(secs, usecs as u32 * 1000)
}
}
}
|
{
(c.DetectEngineStateFree)(state);
}
|
conditional_block
|
core.rs
|
/* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// This file exposes items from the core "C" code to Rust.
use std;
use crate::filecontainer::*;
/// Opaque C types.
pub enum DetectEngineState {}
pub enum AppLayerDecoderEvents {}
pub enum AppLayerParserState {}
// From app-layer-events.h
pub type AppLayerEventType = std::os::raw::c_int;
pub const APP_LAYER_EVENT_TYPE_TRANSACTION : i32 = 1;
pub const APP_LAYER_EVENT_TYPE_PACKET : i32 = 2;
// From stream.h.
pub const STREAM_START: u8 = 0x01;
pub const STREAM_EOF: u8 = 0x02;
pub const STREAM_TOSERVER: u8 = 0x04;
pub const STREAM_TOCLIENT: u8 = 0x08;
pub const STREAM_GAP: u8 = 0x10;
pub const STREAM_DEPTH: u8 = 0x20;
pub const STREAM_MIDSTREAM:u8 = 0x40;
// Application layer protocol identifiers (app-layer-protos.h)
pub type AppProto = std::os::raw::c_int;
pub const ALPROTO_UNKNOWN : AppProto = 0;
pub static mut ALPROTO_FAILED : AppProto = 0; // updated during init
pub const IPPROTO_TCP : i32 = 6;
pub const IPPROTO_UDP : i32 = 17;
macro_rules!BIT_U32 {
($x:expr) => (1 << $x);
}
macro_rules!BIT_U64 {
($x:expr) => (1 << $x);
}
// Defined in app-layer-protos.h
extern {
pub fn StringToAppProto(proto_name: *const u8) -> AppProto;
}
//
// Function types for calls into C.
//
#[allow(non_snake_case)]
pub type SCLogMessageFunc =
extern "C" fn(level: std::os::raw::c_int,
filename: *const std::os::raw::c_char,
line: std::os::raw::c_uint,
function: *const std::os::raw::c_char,
code: std::os::raw::c_int,
message: *const std::os::raw::c_char) -> std::os::raw::c_int;
pub type DetectEngineStateFreeFunc =
extern "C" fn(state: *mut DetectEngineState);
pub type AppLayerDecoderEventsSetEventRawFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents,
event: u8);
pub type AppLayerDecoderEventsFreeEventsFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents);
pub enum SuricataStreamingBufferConfig {}
pub type SCFileOpenFileWithId = extern "C" fn (
file_container: &FileContainer,
sbcfg: &SuricataStreamingBufferConfig,
track_id: u32,
name: *const u8, name_len: u16,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileCloseFileById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileAppendDataById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFileAppendGAPById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFilePrune = extern "C" fn (
file_container: &FileContainer);
pub type SCFileContainerRecycle = extern "C" fn (
file_container: &FileContainer);
pub type SCFileSetTx = extern "C" fn (
file: &FileContainer,
tx_id: u64);
// A Suricata context that is passed in from C. This is alternative to
// using functions from Suricata directly, so they can be wrapped so
// Rust unit tests will still compile when they are not linked
// directly to the real function.
//
// This might add a little too much complexity to keep pure Rust test
// cases working.
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataContext {
pub SCLogMessage: SCLogMessageFunc,
DetectEngineStateFree: DetectEngineStateFreeFunc,
AppLayerDecoderEventsSetEventRaw: AppLayerDecoderEventsSetEventRawFunc,
AppLayerDecoderEventsFreeEvents: AppLayerDecoderEventsFreeEventsFunc,
pub FileOpenFile: SCFileOpenFileWithId,
pub FileCloseFile: SCFileCloseFileById,
pub FileAppendData: SCFileAppendDataById,
pub FileAppendGAP: SCFileAppendGAPById,
pub FileContainerRecycle: SCFileContainerRecycle,
pub FilePrune: SCFilePrune,
pub FileSetTx: SCFileSetTx,
}
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataFileContext {
pub files_sbcfg: &'static SuricataStreamingBufferConfig,
}
extern {
pub fn SCGetContext() -> &'static mut SuricataContext;
pub fn SCLogGetLogLevel() -> i32;
}
pub static mut SC: Option<&'static SuricataContext> = None;
pub fn init_ffi(context: &'static mut SuricataContext)
{
unsafe {
SC = Some(context);
ALPROTO_FAILED = StringToAppProto("failed\0".as_ptr());
}
}
#[no_mangle]
pub extern "C" fn rs_init(context: &'static mut SuricataContext)
{
init_ffi(context);
}
/// DetectEngineStateFree wrapper.
pub fn sc_detect_engine_state_free(state: *mut DetectEngineState)
{
unsafe {
if let Some(c) = SC {
(c.DetectEngineStateFree)(state);
}
}
}
/// AppLayerDecoderEventsSetEventRaw wrapper.
pub fn sc_app_layer_decoder_events_set_event_raw(
events: *mut *mut AppLayerDecoderEvents, event: u8)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsSetEventRaw)(events, event);
}
}
}
/// AppLayerDecoderEventsFreeEvents wrapper.
pub fn sc_app_layer_decoder_events_free_events(
events: *mut *mut AppLayerDecoderEvents)
|
/// Opaque flow type (defined in C)
pub enum Flow {}
/// Extern functions operating on Flow.
extern {
pub fn FlowGetLastTimeAsParts(flow: &Flow, secs: *mut u64, usecs: *mut u64);
}
/// Rust implementation of Flow.
impl Flow {
/// Return the time of the last flow update as a `Duration`
/// since the epoch.
pub fn get_last_time(&mut self) -> std::time::Duration {
unsafe {
let mut secs: u64 = 0;
let mut usecs: u64 = 0;
FlowGetLastTimeAsParts(self, &mut secs, &mut usecs);
std::time::Duration::new(secs, usecs as u32 * 1000)
}
}
}
|
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsFreeEvents)(events);
}
}
}
|
identifier_body
|
core.rs
|
/* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// This file exposes items from the core "C" code to Rust.
use std;
use crate::filecontainer::*;
/// Opaque C types.
pub enum DetectEngineState {}
pub enum AppLayerDecoderEvents {}
pub enum AppLayerParserState {}
// From app-layer-events.h
pub type AppLayerEventType = std::os::raw::c_int;
pub const APP_LAYER_EVENT_TYPE_TRANSACTION : i32 = 1;
pub const APP_LAYER_EVENT_TYPE_PACKET : i32 = 2;
// From stream.h.
pub const STREAM_START: u8 = 0x01;
pub const STREAM_EOF: u8 = 0x02;
pub const STREAM_TOSERVER: u8 = 0x04;
pub const STREAM_TOCLIENT: u8 = 0x08;
pub const STREAM_GAP: u8 = 0x10;
pub const STREAM_DEPTH: u8 = 0x20;
pub const STREAM_MIDSTREAM:u8 = 0x40;
// Application layer protocol identifiers (app-layer-protos.h)
pub type AppProto = std::os::raw::c_int;
pub const ALPROTO_UNKNOWN : AppProto = 0;
pub static mut ALPROTO_FAILED : AppProto = 0; // updated during init
pub const IPPROTO_TCP : i32 = 6;
pub const IPPROTO_UDP : i32 = 17;
macro_rules!BIT_U32 {
($x:expr) => (1 << $x);
}
macro_rules!BIT_U64 {
($x:expr) => (1 << $x);
}
// Defined in app-layer-protos.h
extern {
pub fn StringToAppProto(proto_name: *const u8) -> AppProto;
|
//
// Function types for calls into C.
//
#[allow(non_snake_case)]
pub type SCLogMessageFunc =
extern "C" fn(level: std::os::raw::c_int,
filename: *const std::os::raw::c_char,
line: std::os::raw::c_uint,
function: *const std::os::raw::c_char,
code: std::os::raw::c_int,
message: *const std::os::raw::c_char) -> std::os::raw::c_int;
pub type DetectEngineStateFreeFunc =
extern "C" fn(state: *mut DetectEngineState);
pub type AppLayerDecoderEventsSetEventRawFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents,
event: u8);
pub type AppLayerDecoderEventsFreeEventsFunc =
extern "C" fn (events: *mut *mut AppLayerDecoderEvents);
pub enum SuricataStreamingBufferConfig {}
pub type SCFileOpenFileWithId = extern "C" fn (
file_container: &FileContainer,
sbcfg: &SuricataStreamingBufferConfig,
track_id: u32,
name: *const u8, name_len: u16,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileCloseFileById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32,
flags: u16) -> i32;
pub type SCFileAppendDataById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFileAppendGAPById = extern "C" fn (
file_container: &FileContainer,
track_id: u32,
data: *const u8, data_len: u32) -> i32;
pub type SCFilePrune = extern "C" fn (
file_container: &FileContainer);
pub type SCFileContainerRecycle = extern "C" fn (
file_container: &FileContainer);
pub type SCFileSetTx = extern "C" fn (
file: &FileContainer,
tx_id: u64);
// A Suricata context that is passed in from C. This is alternative to
// using functions from Suricata directly, so they can be wrapped so
// Rust unit tests will still compile when they are not linked
// directly to the real function.
//
// This might add a little too much complexity to keep pure Rust test
// cases working.
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataContext {
pub SCLogMessage: SCLogMessageFunc,
DetectEngineStateFree: DetectEngineStateFreeFunc,
AppLayerDecoderEventsSetEventRaw: AppLayerDecoderEventsSetEventRawFunc,
AppLayerDecoderEventsFreeEvents: AppLayerDecoderEventsFreeEventsFunc,
pub FileOpenFile: SCFileOpenFileWithId,
pub FileCloseFile: SCFileCloseFileById,
pub FileAppendData: SCFileAppendDataById,
pub FileAppendGAP: SCFileAppendGAPById,
pub FileContainerRecycle: SCFileContainerRecycle,
pub FilePrune: SCFilePrune,
pub FileSetTx: SCFileSetTx,
}
#[allow(non_snake_case)]
#[repr(C)]
pub struct SuricataFileContext {
pub files_sbcfg: &'static SuricataStreamingBufferConfig,
}
extern {
pub fn SCGetContext() -> &'static mut SuricataContext;
pub fn SCLogGetLogLevel() -> i32;
}
pub static mut SC: Option<&'static SuricataContext> = None;
pub fn init_ffi(context: &'static mut SuricataContext)
{
unsafe {
SC = Some(context);
ALPROTO_FAILED = StringToAppProto("failed\0".as_ptr());
}
}
#[no_mangle]
pub extern "C" fn rs_init(context: &'static mut SuricataContext)
{
init_ffi(context);
}
/// DetectEngineStateFree wrapper.
pub fn sc_detect_engine_state_free(state: *mut DetectEngineState)
{
unsafe {
if let Some(c) = SC {
(c.DetectEngineStateFree)(state);
}
}
}
/// AppLayerDecoderEventsSetEventRaw wrapper.
pub fn sc_app_layer_decoder_events_set_event_raw(
events: *mut *mut AppLayerDecoderEvents, event: u8)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsSetEventRaw)(events, event);
}
}
}
/// AppLayerDecoderEventsFreeEvents wrapper.
pub fn sc_app_layer_decoder_events_free_events(
events: *mut *mut AppLayerDecoderEvents)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsFreeEvents)(events);
}
}
}
/// Opaque flow type (defined in C)
pub enum Flow {}
/// Extern functions operating on Flow.
extern {
pub fn FlowGetLastTimeAsParts(flow: &Flow, secs: *mut u64, usecs: *mut u64);
}
/// Rust implementation of Flow.
impl Flow {
/// Return the time of the last flow update as a `Duration`
/// since the epoch.
pub fn get_last_time(&mut self) -> std::time::Duration {
unsafe {
let mut secs: u64 = 0;
let mut usecs: u64 = 0;
FlowGetLastTimeAsParts(self, &mut secs, &mut usecs);
std::time::Duration::new(secs, usecs as u32 * 1000)
}
}
}
|
}
|
random_line_split
|
cargo_doc.rs
|
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, 'b>,
}
pub fn doc(manifest_path: &Path,
options: &DocOptions) -> CargoResult<()> {
let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(),
options.compile_opts.config));
|
let package = try!(source.root_package());
let mut lib_names = HashSet::new();
let mut bin_names = HashSet::new();
if options.compile_opts.spec.is_none() {
for target in package.targets().iter().filter(|t| t.documented()) {
if target.is_lib() {
assert!(lib_names.insert(target.name()));
} else {
assert!(bin_names.insert(target.name()));
}
}
for bin in bin_names.iter() {
if lib_names.contains(bin) {
return Err(human("Cannot document a package where a library \
and a binary have the same name. Consider \
renaming one or marking the target as \
`doc = false`"))
}
}
}
try!(ops::compile(manifest_path, &options.compile_opts));
if options.open_result {
let name = match options.compile_opts.spec {
Some(spec) => try!(PackageIdSpec::parse(spec)).name().to_string(),
None => {
match lib_names.iter().nth(0) {
Some(s) => s.to_string(),
None => return Ok(())
}
}
};
let path = package.absolute_target_dir().join("doc").join(&name)
.join("index.html");
if fs::metadata(&path).is_ok() {
open_docs(&path);
}
}
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn open_docs(path: &Path) {
// trying xdg-open
match Command::new("xdg-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying gnome-open
match Command::new("gnome-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying kde-open
match Command::new("kde-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "windows")]
fn open_docs(path: &Path) {
match Command::new("start").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "macos")]
fn open_docs(path: &Path) {
match Command::new("open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
|
try!(source.update());
|
random_line_split
|
cargo_doc.rs
|
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, 'b>,
}
pub fn doc(manifest_path: &Path,
options: &DocOptions) -> CargoResult<()> {
let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(),
options.compile_opts.config));
try!(source.update());
let package = try!(source.root_package());
let mut lib_names = HashSet::new();
let mut bin_names = HashSet::new();
if options.compile_opts.spec.is_none() {
for target in package.targets().iter().filter(|t| t.documented()) {
if target.is_lib() {
assert!(lib_names.insert(target.name()));
} else {
assert!(bin_names.insert(target.name()));
}
}
for bin in bin_names.iter() {
if lib_names.contains(bin) {
return Err(human("Cannot document a package where a library \
and a binary have the same name. Consider \
renaming one or marking the target as \
`doc = false`"))
}
}
}
try!(ops::compile(manifest_path, &options.compile_opts));
if options.open_result {
let name = match options.compile_opts.spec {
Some(spec) => try!(PackageIdSpec::parse(spec)).name().to_string(),
None => {
match lib_names.iter().nth(0) {
Some(s) => s.to_string(),
None => return Ok(())
}
}
};
let path = package.absolute_target_dir().join("doc").join(&name)
.join("index.html");
if fs::metadata(&path).is_ok() {
open_docs(&path);
}
}
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn open_docs(path: &Path) {
// trying xdg-open
match Command::new("xdg-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying gnome-open
match Command::new("gnome-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying kde-open
match Command::new("kde-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "windows")]
fn open_docs(path: &Path)
|
#[cfg(target_os = "macos")]
fn open_docs(path: &Path) {
match Command::new("open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
|
{
match Command::new("start").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
|
identifier_body
|
cargo_doc.rs
|
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, 'b>,
}
pub fn doc(manifest_path: &Path,
options: &DocOptions) -> CargoResult<()> {
let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(),
options.compile_opts.config));
try!(source.update());
let package = try!(source.root_package());
let mut lib_names = HashSet::new();
let mut bin_names = HashSet::new();
if options.compile_opts.spec.is_none() {
for target in package.targets().iter().filter(|t| t.documented()) {
if target.is_lib() {
assert!(lib_names.insert(target.name()));
} else {
assert!(bin_names.insert(target.name()));
}
}
for bin in bin_names.iter() {
if lib_names.contains(bin) {
return Err(human("Cannot document a package where a library \
and a binary have the same name. Consider \
renaming one or marking the target as \
`doc = false`"))
}
}
}
try!(ops::compile(manifest_path, &options.compile_opts));
if options.open_result {
let name = match options.compile_opts.spec {
Some(spec) => try!(PackageIdSpec::parse(spec)).name().to_string(),
None => {
match lib_names.iter().nth(0) {
Some(s) => s.to_string(),
None => return Ok(())
}
}
};
let path = package.absolute_target_dir().join("doc").join(&name)
.join("index.html");
if fs::metadata(&path).is_ok() {
open_docs(&path);
}
}
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn open_docs(path: &Path) {
// trying xdg-open
match Command::new("xdg-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying gnome-open
match Command::new("gnome-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying kde-open
match Command::new("kde-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "windows")]
fn
|
(path: &Path) {
match Command::new("start").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "macos")]
fn open_docs(path: &Path) {
match Command::new("open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
|
open_docs
|
identifier_name
|
cargo_doc.rs
|
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, 'b>,
}
pub fn doc(manifest_path: &Path,
options: &DocOptions) -> CargoResult<()> {
let mut source = try!(PathSource::for_path(manifest_path.parent().unwrap(),
options.compile_opts.config));
try!(source.update());
let package = try!(source.root_package());
let mut lib_names = HashSet::new();
let mut bin_names = HashSet::new();
if options.compile_opts.spec.is_none() {
for target in package.targets().iter().filter(|t| t.documented()) {
if target.is_lib() {
assert!(lib_names.insert(target.name()));
} else {
assert!(bin_names.insert(target.name()));
}
}
for bin in bin_names.iter() {
if lib_names.contains(bin) {
return Err(human("Cannot document a package where a library \
and a binary have the same name. Consider \
renaming one or marking the target as \
`doc = false`"))
}
}
}
try!(ops::compile(manifest_path, &options.compile_opts));
if options.open_result {
let name = match options.compile_opts.spec {
Some(spec) => try!(PackageIdSpec::parse(spec)).name().to_string(),
None => {
match lib_names.iter().nth(0) {
Some(s) => s.to_string(),
None => return Ok(())
}
}
};
let path = package.absolute_target_dir().join("doc").join(&name)
.join("index.html");
if fs::metadata(&path).is_ok()
|
}
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn open_docs(path: &Path) {
// trying xdg-open
match Command::new("xdg-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying gnome-open
match Command::new("gnome-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying kde-open
match Command::new("kde-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "windows")]
fn open_docs(path: &Path) {
match Command::new("start").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "macos")]
fn open_docs(path: &Path) {
match Command::new("open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
|
{
open_docs(&path);
}
|
conditional_block
|
q_lambda.rs
|
use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct
|
{
td_error: f64,
}
/// Watkins' Q-learning with eligibility traces.
///
/// # References
/// - Watkins, C. J. C. H. (1989). Learning from Delayed Rewards. Ph.D. thesis,
/// Cambridge University.
/// - Watkins, C. J. C. H., Dayan, P. (1992). Q-learning. Machine Learning,
/// 8:279–292.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct QLambda<F, T> {
#[weights]
pub fa_theta: F,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, R> Handler<&'m Transition<S, usize>> for QLambda<Q, Tr<&'m S, usize, Q, R>>
where
Q: Enumerable<(&'m S,)> + Differentiable<(&'m S, usize)> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, usize, Q, R>>>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, usize)>>::Jacobian>,
<Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>,
<<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> {
let s = t.from.state();
let qs = self.fa_theta.evaluate((s,));
let qsa = qs[t.action];
let grad_s = self.fa_theta.grad((s, t.action));
// Update trace:
if t.action!= argmax_first(qs).0 { self.trace.reset(); }
self.trace.update(&grad_s);
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} else {
let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
}
|
Response
|
identifier_name
|
q_lambda.rs
|
use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// Watkins' Q-learning with eligibility traces.
///
/// # References
/// - Watkins, C. J. C. H. (1989). Learning from Delayed Rewards. Ph.D. thesis,
/// Cambridge University.
/// - Watkins, C. J. C. H., Dayan, P. (1992). Q-learning. Machine Learning,
/// 8:279–292.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct QLambda<F, T> {
#[weights]
pub fa_theta: F,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, R> Handler<&'m Transition<S, usize>> for QLambda<Q, Tr<&'m S, usize, Q, R>>
where
Q: Enumerable<(&'m S,)> + Differentiable<(&'m S, usize)> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, usize, Q, R>>>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, usize)>>::Jacobian>,
<Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>,
<<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> {
|
residual
} else {
let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
}
|
let s = t.from.state();
let qs = self.fa_theta.evaluate((s,));
let qsa = qs[t.action];
let grad_s = self.fa_theta.grad((s, t.action));
// Update trace:
if t.action != argmax_first(qs).0 { self.trace.reset(); }
self.trace.update(&grad_s);
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
|
identifier_body
|
q_lambda.rs
|
use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// Watkins' Q-learning with eligibility traces.
///
/// # References
/// - Watkins, C. J. C. H. (1989). Learning from Delayed Rewards. Ph.D. thesis,
/// Cambridge University.
/// - Watkins, C. J. C. H., Dayan, P. (1992). Q-learning. Machine Learning,
/// 8:279–292.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct QLambda<F, T> {
#[weights]
pub fa_theta: F,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, R> Handler<&'m Transition<S, usize>> for QLambda<Q, Tr<&'m S, usize, Q, R>>
where
Q: Enumerable<(&'m S,)> + Differentiable<(&'m S, usize)> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, usize, Q, R>>>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, usize)>>::Jacobian>,
<Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>,
<<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> {
let s = t.from.state();
let qs = self.fa_theta.evaluate((s,));
let qsa = qs[t.action];
let grad_s = self.fa_theta.grad((s, t.action));
// Update trace:
if t.action!= argmax_first(qs).0 { self.trace.reset(); }
self.trace.update(&grad_s);
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} else {
|
Ok(Response { td_error, })
}
}
|
let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
|
conditional_block
|
q_lambda.rs
|
use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// Watkins' Q-learning with eligibility traces.
///
/// # References
/// - Watkins, C. J. C. H. (1989). Learning from Delayed Rewards. Ph.D. thesis,
/// Cambridge University.
/// - Watkins, C. J. C. H., Dayan, P. (1992). Q-learning. Machine Learning,
/// 8:279–292.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct QLambda<F, T> {
#[weights]
pub fa_theta: F,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, R> Handler<&'m Transition<S, usize>> for QLambda<Q, Tr<&'m S, usize, Q, R>>
where
Q: Enumerable<(&'m S,)> + Differentiable<(&'m S, usize)> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, usize, Q, R>>>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, usize)>>::Jacobian>,
<Q as Function<(&'m S,)>>::Output: Index<usize, Output = f64> + IntoIterator<Item = f64>,
<<Q as Function<(&'m S,)>>::Output as IntoIterator>::IntoIter: ExactSizeIterator,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, usize>) -> Result<Self::Response, Self::Error> {
let s = t.from.state();
let qs = self.fa_theta.evaluate((s,));
let qsa = qs[t.action];
let grad_s = self.fa_theta.grad((s, t.action));
// Update trace:
if t.action!= argmax_first(qs).0 { self.trace.reset(); }
self.trace.update(&grad_s);
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
|
self.trace.reset();
residual
} else {
let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
}
|
jacobian: &self.trace,
}).map_err(|_| ())?;
|
random_line_split
|
markdown.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Markdown formatting for rustdoc
//!
//! This module implements markdown formatting through the sundown C-library
//! (bundled into the rust runtime). This module self-contains the C bindings
//! and necessary legwork to render markdown, and exposes all of the
//! functionality through a unit-struct, `Markdown`, which has an implementation
//! of `fmt::Default`. Example usage:
//!
//! ```rust
//! let s = "My *markdown* _text_";
//! let html = format!("{}", Markdown(s));
//! //... something using html
//! ```
use std::cast;
use std::fmt;
use std::io;
use std::libc;
use std::str;
use std::unstable::intrinsics;
use std::vec;
/// A unit struct which has the `fmt::Default` trait implemented. When
/// formatted, this struct will emit the HTML corresponding to the rendered
/// version of the contained markdown string.
pub struct Markdown<'a>(&'a str);
static OUTPUT_UNIT: libc::size_t = 64;
static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0;
static MKDEXT_TABLES: libc::c_uint = 1 << 1;
static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2;
static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3;
static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
type sd_markdown = libc::c_void; // this is opaque to us
struct sd_callbacks {
blockcode: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
other: [libc::size_t,..25],
}
struct html_toc_data {
header_count: libc::c_int,
current_level: libc::c_int,
level_offset: libc::c_int,
}
struct html_renderopt {
toc_data: html_toc_data,
flags: libc::c_uint,
link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
}
struct my_opaque {
opt: html_renderopt,
dfltblk: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
}
struct buf {
data: *u8,
size: libc::size_t,
asize: libc::size_t,
unit: libc::size_t,
}
// sundown FFI
#[link(name = "sundown", kind = "static")]
extern {
fn sdhtml_renderer(callbacks: *sd_callbacks,
options_ptr: *html_renderopt,
render_flags: libc::c_uint);
fn sd_markdown_new(extensions: libc::c_uint,
max_nesting: libc::size_t,
callbacks: *sd_callbacks,
opaque: *libc::c_void) -> *sd_markdown;
fn sd_markdown_render(ob: *buf,
document: *u8,
doc_size: libc::size_t,
md: *sd_markdown);
fn sd_markdown_free(md: *sd_markdown);
fn bufnew(unit: libc::size_t) -> *buf;
fn bufrelease(b: *buf);
}
/// Returns Some(code) if `s` is a line that should be stripped from
/// documentation but used in example code. `code` is the portion of
/// `s` that should be used in tests. (None for lines that should be
/// left as-is.)
fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
let trimmed = s.trim();
if trimmed.starts_with("# ") {
Some(trimmed.slice_from(2))
} else {
None
}
}
pub fn render(w: &mut io::Writer, s: &str) {
extern fn block(ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
let my_opaque: &my_opaque = cast::transmute(opaque);
vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let text = str::from_utf8(text);
let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none());
let text = lines.to_owned_vec().connect("\n");
let buf = buf {
data: text.as_bytes().as_ptr(),
size: text.len() as libc::size_t,
asize: text.len() as libc::size_t,
unit: 0,
};
(my_opaque.dfltblk)(ob, &buf, lang, opaque);
})
}
}
// This code is all lifted from examples/sundown.c in the sundown repo
unsafe {
let ob = bufnew(OUTPUT_UNIT);
let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
MKDEXT_STRIKETHROUGH;
let options = html_renderopt {
toc_data: html_toc_data {
header_count: 0,
current_level: 0,
level_offset: 0,
},
flags: 0,
link_attributes: None,
};
let mut callbacks: sd_callbacks = intrinsics::init();
sdhtml_renderer(&callbacks, &options, 0);
let opaque = my_opaque {
opt: options,
dfltblk: callbacks.blockcode,
};
callbacks.blockcode = block;
let markdown = sd_markdown_new(extensions, 16, &callbacks,
&opaque as *my_opaque as *libc::c_void);
sd_markdown_render(ob, s.as_ptr(), s.len() as libc::size_t, markdown);
sd_markdown_free(markdown);
vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| {
w.write(buf);
});
bufrelease(ob);
}
}
pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
extern fn
|
(_ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
if text.is_null() || lang.is_null() { return }
let (test, shouldfail, ignore) =
vec::raw::buf_as_slice((*lang).data,
(*lang).size as uint, |lang| {
let s = str::from_utf8(lang);
(s.contains("rust"), s.contains("should_fail"),
s.contains("ignore"))
});
if!test { return }
vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let tests: &mut ::test::Collector = intrinsics::transmute(opaque);
let text = str::from_utf8(text);
let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l));
let text = lines.to_owned_vec().connect("\n");
tests.add_test(text, ignore, shouldfail);
})
}
}
unsafe {
let ob = bufnew(OUTPUT_UNIT);
let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
MKDEXT_STRIKETHROUGH;
let callbacks = sd_callbacks {
blockcode: block,
other: intrinsics::init()
};
let tests = tests as *mut ::test::Collector as *libc::c_void;
let markdown = sd_markdown_new(extensions, 16, &callbacks, tests);
sd_markdown_render(ob, doc.as_ptr(), doc.len() as libc::size_t,
markdown);
sd_markdown_free(markdown);
bufrelease(ob);
}
}
impl<'a> fmt::Default for Markdown<'a> {
fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) {
let Markdown(md) = *md;
// This is actually common enough to special-case
if md.len() == 0 { return; }
render(fmt.buf, md.as_slice());
}
}
|
block
|
identifier_name
|
markdown.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Markdown formatting for rustdoc
//!
//! This module implements markdown formatting through the sundown C-library
//! (bundled into the rust runtime). This module self-contains the C bindings
//! and necessary legwork to render markdown, and exposes all of the
//! functionality through a unit-struct, `Markdown`, which has an implementation
//! of `fmt::Default`. Example usage:
//!
//! ```rust
//! let s = "My *markdown* _text_";
//! let html = format!("{}", Markdown(s));
//! //... something using html
//! ```
use std::cast;
use std::fmt;
use std::io;
use std::libc;
use std::str;
use std::unstable::intrinsics;
use std::vec;
/// A unit struct which has the `fmt::Default` trait implemented. When
/// formatted, this struct will emit the HTML corresponding to the rendered
/// version of the contained markdown string.
pub struct Markdown<'a>(&'a str);
static OUTPUT_UNIT: libc::size_t = 64;
static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0;
static MKDEXT_TABLES: libc::c_uint = 1 << 1;
static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2;
static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3;
static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
type sd_markdown = libc::c_void; // this is opaque to us
struct sd_callbacks {
blockcode: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
other: [libc::size_t,..25],
}
struct html_toc_data {
header_count: libc::c_int,
current_level: libc::c_int,
level_offset: libc::c_int,
}
struct html_renderopt {
toc_data: html_toc_data,
flags: libc::c_uint,
link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
}
struct my_opaque {
opt: html_renderopt,
dfltblk: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
}
struct buf {
data: *u8,
size: libc::size_t,
asize: libc::size_t,
unit: libc::size_t,
}
// sundown FFI
#[link(name = "sundown", kind = "static")]
extern {
fn sdhtml_renderer(callbacks: *sd_callbacks,
options_ptr: *html_renderopt,
render_flags: libc::c_uint);
fn sd_markdown_new(extensions: libc::c_uint,
max_nesting: libc::size_t,
callbacks: *sd_callbacks,
opaque: *libc::c_void) -> *sd_markdown;
fn sd_markdown_render(ob: *buf,
document: *u8,
doc_size: libc::size_t,
md: *sd_markdown);
fn sd_markdown_free(md: *sd_markdown);
fn bufnew(unit: libc::size_t) -> *buf;
fn bufrelease(b: *buf);
}
/// Returns Some(code) if `s` is a line that should be stripped from
/// documentation but used in example code. `code` is the portion of
/// `s` that should be used in tests. (None for lines that should be
/// left as-is.)
fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
let trimmed = s.trim();
if trimmed.starts_with("# ") {
Some(trimmed.slice_from(2))
} else {
None
}
}
pub fn render(w: &mut io::Writer, s: &str) {
extern fn block(ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
let my_opaque: &my_opaque = cast::transmute(opaque);
vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let text = str::from_utf8(text);
let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none());
let text = lines.to_owned_vec().connect("\n");
let buf = buf {
data: text.as_bytes().as_ptr(),
size: text.len() as libc::size_t,
asize: text.len() as libc::size_t,
unit: 0,
};
(my_opaque.dfltblk)(ob, &buf, lang, opaque);
})
}
}
// This code is all lifted from examples/sundown.c in the sundown repo
unsafe {
let ob = bufnew(OUTPUT_UNIT);
let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
MKDEXT_STRIKETHROUGH;
let options = html_renderopt {
toc_data: html_toc_data {
header_count: 0,
current_level: 0,
level_offset: 0,
},
flags: 0,
link_attributes: None,
};
let mut callbacks: sd_callbacks = intrinsics::init();
sdhtml_renderer(&callbacks, &options, 0);
let opaque = my_opaque {
opt: options,
dfltblk: callbacks.blockcode,
};
callbacks.blockcode = block;
let markdown = sd_markdown_new(extensions, 16, &callbacks,
&opaque as *my_opaque as *libc::c_void);
sd_markdown_render(ob, s.as_ptr(), s.len() as libc::size_t, markdown);
sd_markdown_free(markdown);
vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| {
w.write(buf);
});
bufrelease(ob);
}
}
pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
extern fn block(_ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
if text.is_null() || lang.is_null()
|
let (test, shouldfail, ignore) =
vec::raw::buf_as_slice((*lang).data,
(*lang).size as uint, |lang| {
let s = str::from_utf8(lang);
(s.contains("rust"), s.contains("should_fail"),
s.contains("ignore"))
});
if!test { return }
vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let tests: &mut ::test::Collector = intrinsics::transmute(opaque);
let text = str::from_utf8(text);
let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l));
let text = lines.to_owned_vec().connect("\n");
tests.add_test(text, ignore, shouldfail);
})
}
}
unsafe {
let ob = bufnew(OUTPUT_UNIT);
let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
MKDEXT_STRIKETHROUGH;
let callbacks = sd_callbacks {
blockcode: block,
other: intrinsics::init()
};
let tests = tests as *mut ::test::Collector as *libc::c_void;
let markdown = sd_markdown_new(extensions, 16, &callbacks, tests);
sd_markdown_render(ob, doc.as_ptr(), doc.len() as libc::size_t,
markdown);
sd_markdown_free(markdown);
bufrelease(ob);
}
}
impl<'a> fmt::Default for Markdown<'a> {
fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) {
let Markdown(md) = *md;
// This is actually common enough to special-case
if md.len() == 0 { return; }
render(fmt.buf, md.as_slice());
}
}
|
{ return }
|
conditional_block
|
markdown.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Markdown formatting for rustdoc
//!
//! This module implements markdown formatting through the sundown C-library
//! (bundled into the rust runtime). This module self-contains the C bindings
//! and necessary legwork to render markdown, and exposes all of the
//! functionality through a unit-struct, `Markdown`, which has an implementation
//! of `fmt::Default`. Example usage:
//!
//! ```rust
//! let s = "My *markdown* _text_";
//! let html = format!("{}", Markdown(s));
//! //... something using html
//! ```
use std::cast;
use std::fmt;
use std::io;
use std::libc;
use std::str;
use std::unstable::intrinsics;
use std::vec;
/// A unit struct which has the `fmt::Default` trait implemented. When
/// formatted, this struct will emit the HTML corresponding to the rendered
/// version of the contained markdown string.
pub struct Markdown<'a>(&'a str);
static OUTPUT_UNIT: libc::size_t = 64;
|
static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3;
static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
type sd_markdown = libc::c_void; // this is opaque to us
struct sd_callbacks {
blockcode: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
other: [libc::size_t,..25],
}
struct html_toc_data {
header_count: libc::c_int,
current_level: libc::c_int,
level_offset: libc::c_int,
}
struct html_renderopt {
toc_data: html_toc_data,
flags: libc::c_uint,
link_attributes: Option<extern "C" fn(*buf, *buf, *libc::c_void)>,
}
struct my_opaque {
opt: html_renderopt,
dfltblk: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
}
struct buf {
data: *u8,
size: libc::size_t,
asize: libc::size_t,
unit: libc::size_t,
}
// sundown FFI
#[link(name = "sundown", kind = "static")]
extern {
fn sdhtml_renderer(callbacks: *sd_callbacks,
options_ptr: *html_renderopt,
render_flags: libc::c_uint);
fn sd_markdown_new(extensions: libc::c_uint,
max_nesting: libc::size_t,
callbacks: *sd_callbacks,
opaque: *libc::c_void) -> *sd_markdown;
fn sd_markdown_render(ob: *buf,
document: *u8,
doc_size: libc::size_t,
md: *sd_markdown);
fn sd_markdown_free(md: *sd_markdown);
fn bufnew(unit: libc::size_t) -> *buf;
fn bufrelease(b: *buf);
}
/// Returns Some(code) if `s` is a line that should be stripped from
/// documentation but used in example code. `code` is the portion of
/// `s` that should be used in tests. (None for lines that should be
/// left as-is.)
fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
let trimmed = s.trim();
if trimmed.starts_with("# ") {
Some(trimmed.slice_from(2))
} else {
None
}
}
pub fn render(w: &mut io::Writer, s: &str) {
extern fn block(ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
let my_opaque: &my_opaque = cast::transmute(opaque);
vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let text = str::from_utf8(text);
let mut lines = text.lines().filter(|l| stripped_filtered_line(*l).is_none());
let text = lines.to_owned_vec().connect("\n");
let buf = buf {
data: text.as_bytes().as_ptr(),
size: text.len() as libc::size_t,
asize: text.len() as libc::size_t,
unit: 0,
};
(my_opaque.dfltblk)(ob, &buf, lang, opaque);
})
}
}
// This code is all lifted from examples/sundown.c in the sundown repo
unsafe {
let ob = bufnew(OUTPUT_UNIT);
let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
MKDEXT_STRIKETHROUGH;
let options = html_renderopt {
toc_data: html_toc_data {
header_count: 0,
current_level: 0,
level_offset: 0,
},
flags: 0,
link_attributes: None,
};
let mut callbacks: sd_callbacks = intrinsics::init();
sdhtml_renderer(&callbacks, &options, 0);
let opaque = my_opaque {
opt: options,
dfltblk: callbacks.blockcode,
};
callbacks.blockcode = block;
let markdown = sd_markdown_new(extensions, 16, &callbacks,
&opaque as *my_opaque as *libc::c_void);
sd_markdown_render(ob, s.as_ptr(), s.len() as libc::size_t, markdown);
sd_markdown_free(markdown);
vec::raw::buf_as_slice((*ob).data, (*ob).size as uint, |buf| {
w.write(buf);
});
bufrelease(ob);
}
}
pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
extern fn block(_ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
if text.is_null() || lang.is_null() { return }
let (test, shouldfail, ignore) =
vec::raw::buf_as_slice((*lang).data,
(*lang).size as uint, |lang| {
let s = str::from_utf8(lang);
(s.contains("rust"), s.contains("should_fail"),
s.contains("ignore"))
});
if!test { return }
vec::raw::buf_as_slice((*text).data, (*text).size as uint, |text| {
let tests: &mut ::test::Collector = intrinsics::transmute(opaque);
let text = str::from_utf8(text);
let mut lines = text.lines().map(|l| stripped_filtered_line(l).unwrap_or(l));
let text = lines.to_owned_vec().connect("\n");
tests.add_test(text, ignore, shouldfail);
})
}
}
unsafe {
let ob = bufnew(OUTPUT_UNIT);
let extensions = MKDEXT_NO_INTRA_EMPHASIS | MKDEXT_TABLES |
MKDEXT_FENCED_CODE | MKDEXT_AUTOLINK |
MKDEXT_STRIKETHROUGH;
let callbacks = sd_callbacks {
blockcode: block,
other: intrinsics::init()
};
let tests = tests as *mut ::test::Collector as *libc::c_void;
let markdown = sd_markdown_new(extensions, 16, &callbacks, tests);
sd_markdown_render(ob, doc.as_ptr(), doc.len() as libc::size_t,
markdown);
sd_markdown_free(markdown);
bufrelease(ob);
}
}
impl<'a> fmt::Default for Markdown<'a> {
fn fmt(md: &Markdown<'a>, fmt: &mut fmt::Formatter) {
let Markdown(md) = *md;
// This is actually common enough to special-case
if md.len() == 0 { return; }
render(fmt.buf, md.as_slice());
}
}
|
static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0;
static MKDEXT_TABLES: libc::c_uint = 1 << 1;
static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2;
|
random_line_split
|
foreign2.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.
mod bar {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
mod zed {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
mod libc {
#[abi = "cdecl"]
#[nolink]
pub extern {
pub fn write(fd: int, buf: *u8, count: ::core::libc::size_t)
-> ::core::libc::ssize_t;
}
}
mod baz {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
pub fn main()
|
{ }
|
identifier_body
|
|
foreign2.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.
mod bar {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
mod zed {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
mod libc {
#[abi = "cdecl"]
#[nolink]
pub extern {
pub fn write(fd: int, buf: *u8, count: ::core::libc::size_t)
-> ::core::libc::ssize_t;
}
}
mod baz {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
pub fn
|
() { }
|
main
|
identifier_name
|
foreign2.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.
mod bar {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
mod zed {
#[abi = "cdecl"]
#[nolink]
pub extern {}
}
mod libc {
#[abi = "cdecl"]
#[nolink]
pub extern {
pub fn write(fd: int, buf: *u8, count: ::core::libc::size_t)
-> ::core::libc::ssize_t;
}
}
mod baz {
#[abi = "cdecl"]
#[nolink]
pub extern {}
|
pub fn main() { }
|
}
|
random_line_split
|
erlang_rust_port.rs
|
// see erlang_rust_port.erl
extern crate erl_ext;
extern crate getopts;
use getopts::Options;
use erl_ext::{Decoder,Encoder,Error};
use std::io;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("u", "utf8-atoms", "Use utf-8 atoms feature");
opts.optflag("s", "small-atoms", "Use small atoms feature");
opts.optflag("f", "fair-new-fun", "Fairly calculate NEW_FUN size (requires extra memory)");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
let mut in_f = io::stdin();
let mut out_f = io::stdout();
// let mut out_writer = std::io::BufferedWriter::with_capacity(20480,
// out_f.unwrap());
let decoder = Decoder::new(&mut in_f);
let encoder = Encoder::new(&mut out_f,
matches.opt_present("u"),
matches.opt_present("s"),
matches.opt_present("f"));
match read_write_loop(decoder, encoder) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: {}", err),
Ok(()) => () // unreachable in this example
};
}
fn read_write_loop<R: io::Read>(mut decoder: Decoder<R>, mut encoder: Encoder) -> Result<(), Error>
|
{
loop {
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
try!(encoder.write_prelude());
try!(encoder.encode_term(term));
try!(encoder.flush());
}
}
|
identifier_body
|
|
erlang_rust_port.rs
|
// see erlang_rust_port.erl
|
extern crate erl_ext;
extern crate getopts;
use getopts::Options;
use erl_ext::{Decoder,Encoder,Error};
use std::io;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("u", "utf8-atoms", "Use utf-8 atoms feature");
opts.optflag("s", "small-atoms", "Use small atoms feature");
opts.optflag("f", "fair-new-fun", "Fairly calculate NEW_FUN size (requires extra memory)");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
let mut in_f = io::stdin();
let mut out_f = io::stdout();
// let mut out_writer = std::io::BufferedWriter::with_capacity(20480,
// out_f.unwrap());
let decoder = Decoder::new(&mut in_f);
let encoder = Encoder::new(&mut out_f,
matches.opt_present("u"),
matches.opt_present("s"),
matches.opt_present("f"));
match read_write_loop(decoder, encoder) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: {}", err),
Ok(()) => () // unreachable in this example
};
}
fn read_write_loop<R: io::Read>(mut decoder: Decoder<R>, mut encoder: Encoder) -> Result<(), Error> {
loop {
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
try!(encoder.write_prelude());
try!(encoder.encode_term(term));
try!(encoder.flush());
}
}
|
random_line_split
|
|
erlang_rust_port.rs
|
// see erlang_rust_port.erl
extern crate erl_ext;
extern crate getopts;
use getopts::Options;
use erl_ext::{Decoder,Encoder,Error};
use std::io;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("u", "utf8-atoms", "Use utf-8 atoms feature");
opts.optflag("s", "small-atoms", "Use small atoms feature");
opts.optflag("f", "fair-new-fun", "Fairly calculate NEW_FUN size (requires extra memory)");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
let mut in_f = io::stdin();
let mut out_f = io::stdout();
// let mut out_writer = std::io::BufferedWriter::with_capacity(20480,
// out_f.unwrap());
let decoder = Decoder::new(&mut in_f);
let encoder = Encoder::new(&mut out_f,
matches.opt_present("u"),
matches.opt_present("s"),
matches.opt_present("f"));
match read_write_loop(decoder, encoder) {
Err(Error::ByteorderUnexpectedEOF) => (), // port was closed
Err(ref err) =>
panic!("Error: {}", err),
Ok(()) => () // unreachable in this example
};
}
fn
|
<R: io::Read>(mut decoder: Decoder<R>, mut encoder: Encoder) -> Result<(), Error> {
loop {
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
try!(encoder.write_prelude());
try!(encoder.encode_term(term));
try!(encoder.flush());
}
}
|
read_write_loop
|
identifier_name
|
dom_manipulation.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::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, EventCancelable, EventTask, SimpleEventTask};
use dom::eventtarget::EventTarget;
use dom::window::Window;
use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use script_thread::MainThreadScriptMsg;
use servo_atoms::Atom;
use std::fmt;
use std::result::Result;
use std::sync::mpsc::Sender;
use task::{TaskCanceller, TaskOnce};
use task_source::TaskSource;
#[derive(Clone, JSTraceable)]
pub struct DOMManipulationTaskSource(pub Sender<MainThreadScriptMsg>);
impl fmt::Debug for DOMManipulationTaskSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMManipulationTaskSource(...)")
}
}
impl TaskSource for DOMManipulationTaskSource {
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
|
{
let msg = MainThreadScriptMsg::Common(CommonScriptMsg::Task(
ScriptThreadEventCategory::ScriptEvent,
Box::new(canceller.wrap_task(task)),
));
self.0.send(msg).map_err(|_| ())
}
}
impl DOMManipulationTaskSource {
pub fn queue_event(&self,
target: &EventTarget,
name: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
window: &Window) {
let target = Trusted::new(target);
let task = EventTask {
target: target,
name: name,
bubbles: bubbles,
cancelable: cancelable,
};
let _ = self.queue(task, window.upcast());
}
pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window) {
let target = Trusted::new(target);
let _ = self.queue(SimpleEventTask { target, name }, window.upcast());
}
}
|
) -> Result<(), ()>
where
T: TaskOnce + 'static,
|
random_line_split
|
dom_manipulation.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::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, EventCancelable, EventTask, SimpleEventTask};
use dom::eventtarget::EventTarget;
use dom::window::Window;
use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use script_thread::MainThreadScriptMsg;
use servo_atoms::Atom;
use std::fmt;
use std::result::Result;
use std::sync::mpsc::Sender;
use task::{TaskCanceller, TaskOnce};
use task_source::TaskSource;
#[derive(Clone, JSTraceable)]
pub struct
|
(pub Sender<MainThreadScriptMsg>);
impl fmt::Debug for DOMManipulationTaskSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMManipulationTaskSource(...)")
}
}
impl TaskSource for DOMManipulationTaskSource {
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
) -> Result<(), ()>
where
T: TaskOnce +'static,
{
let msg = MainThreadScriptMsg::Common(CommonScriptMsg::Task(
ScriptThreadEventCategory::ScriptEvent,
Box::new(canceller.wrap_task(task)),
));
self.0.send(msg).map_err(|_| ())
}
}
impl DOMManipulationTaskSource {
pub fn queue_event(&self,
target: &EventTarget,
name: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
window: &Window) {
let target = Trusted::new(target);
let task = EventTask {
target: target,
name: name,
bubbles: bubbles,
cancelable: cancelable,
};
let _ = self.queue(task, window.upcast());
}
pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window) {
let target = Trusted::new(target);
let _ = self.queue(SimpleEventTask { target, name }, window.upcast());
}
}
|
DOMManipulationTaskSource
|
identifier_name
|
dom_manipulation.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::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, EventCancelable, EventTask, SimpleEventTask};
use dom::eventtarget::EventTarget;
use dom::window::Window;
use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use script_thread::MainThreadScriptMsg;
use servo_atoms::Atom;
use std::fmt;
use std::result::Result;
use std::sync::mpsc::Sender;
use task::{TaskCanceller, TaskOnce};
use task_source::TaskSource;
#[derive(Clone, JSTraceable)]
pub struct DOMManipulationTaskSource(pub Sender<MainThreadScriptMsg>);
impl fmt::Debug for DOMManipulationTaskSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMManipulationTaskSource(...)")
}
}
impl TaskSource for DOMManipulationTaskSource {
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
) -> Result<(), ()>
where
T: TaskOnce +'static,
{
let msg = MainThreadScriptMsg::Common(CommonScriptMsg::Task(
ScriptThreadEventCategory::ScriptEvent,
Box::new(canceller.wrap_task(task)),
));
self.0.send(msg).map_err(|_| ())
}
}
impl DOMManipulationTaskSource {
pub fn queue_event(&self,
target: &EventTarget,
name: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
window: &Window) {
let target = Trusted::new(target);
let task = EventTask {
target: target,
name: name,
bubbles: bubbles,
cancelable: cancelable,
};
let _ = self.queue(task, window.upcast());
}
pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window)
|
}
|
{
let target = Trusted::new(target);
let _ = self.queue(SimpleEventTask { target, name }, window.upcast());
}
|
identifier_body
|
htmltablerowelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowElement {
htmlelement: HTMLElement,
}
impl HTMLTableRowElement {
pub fn RowIndex(&self) -> i32 {
0
}
pub fn GetRowIndex(&self) -> i32 {
0
}
pub fn SectionRowIndex(&self) -> i32 {
0
}
pub fn GetSectionRowIndex(&self) -> i32 {
0
}
|
pub fn DeleteCell(&mut self, _index: i32) -> ErrorResult {
Ok(())
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Ch(&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOMString) -> ErrorResult {
Ok(())
}
pub fn ChOff(&self) -> DOMString {
None
}
pub fn SetChOff(&self, _ch_off: &DOMString) -> ErrorResult {
Ok(())
}
pub fn VAlign(&self) -> DOMString {
None
}
pub fn SetVAlign(&self, _v_align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn BgColor(&self) -> DOMString {
None
}
pub fn SetBgColor(&self, _bg_color: &DOMString) -> ErrorResult {
Ok(())
}
}
|
random_line_split
|
|
htmltablerowelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowElement {
htmlelement: HTMLElement,
}
impl HTMLTableRowElement {
pub fn RowIndex(&self) -> i32 {
0
}
pub fn GetRowIndex(&self) -> i32 {
0
}
pub fn SectionRowIndex(&self) -> i32 {
0
}
pub fn GetSectionRowIndex(&self) -> i32 {
0
}
pub fn DeleteCell(&mut self, _index: i32) -> ErrorResult {
Ok(())
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn
|
(&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOMString) -> ErrorResult {
Ok(())
}
pub fn ChOff(&self) -> DOMString {
None
}
pub fn SetChOff(&self, _ch_off: &DOMString) -> ErrorResult {
Ok(())
}
pub fn VAlign(&self) -> DOMString {
None
}
pub fn SetVAlign(&self, _v_align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn BgColor(&self) -> DOMString {
None
}
pub fn SetBgColor(&self, _bg_color: &DOMString) -> ErrorResult {
Ok(())
}
}
|
Ch
|
identifier_name
|
htmltablerowelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowElement {
htmlelement: HTMLElement,
}
impl HTMLTableRowElement {
pub fn RowIndex(&self) -> i32 {
0
}
pub fn GetRowIndex(&self) -> i32 {
0
}
pub fn SectionRowIndex(&self) -> i32 {
0
}
pub fn GetSectionRowIndex(&self) -> i32 {
0
}
pub fn DeleteCell(&mut self, _index: i32) -> ErrorResult
|
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Ch(&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOMString) -> ErrorResult {
Ok(())
}
pub fn ChOff(&self) -> DOMString {
None
}
pub fn SetChOff(&self, _ch_off: &DOMString) -> ErrorResult {
Ok(())
}
pub fn VAlign(&self) -> DOMString {
None
}
pub fn SetVAlign(&self, _v_align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn BgColor(&self) -> DOMString {
None
}
pub fn SetBgColor(&self, _bg_color: &DOMString) -> ErrorResult {
Ok(())
}
}
|
{
Ok(())
}
|
identifier_body
|
main.rs
|
/*
cmongo2sql
Utility to convert a MongoDB JSON dump to a SQL dump.
Copyright 2016 Sam Saint-Pettersen.
Licensed under the MIT/X11 License.
Rust port of original Python tool (1.0.5).
*/
extern crate clioptions;
extern crate regex;
extern crate rustc_serialize;
extern crate chrono;
use clioptions::CliOptions;
use regex::Regex;
use rustc_serialize::json::Json;
use chrono::*;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn is_date(v: &str) -> bool {
let re = Regex::new(r"\d{4}-\d{2}-\d{2}.*").unwrap();
let mut date = false;
if re.is_match(&v) {
date = true;
}
date
}
fn parse_date(v: &str) -> String {
let mut re = Regex::new("T").unwrap();
let mut p = v.to_string();
p = re.replace(&p, " ");
re = Regex::new(r"\.\d{3}Z").unwrap();
p = re.replace(&p, "");
re = Regex::new(r"\.\d{3}\+\d{4}").unwrap();
p = re.replace(&p, "");
p
}
fn
|
(signature: &str, input: &str, output: &str, db: &str, comments: bool, verbose: bool) {
let mut records = Vec::new();
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for line in file.lines() {
records.push(Json::from_str(&line.unwrap()).unwrap());
}
let mut table = String::new();
let re = Regex::new(r"(.*)\..{3,4}").unwrap();
for cap in re.captures_iter(&input) {
table = cap.at(1).unwrap().to_string();
}
let dtable = format!("DROP TABLE IF EXISTS `{}`;", table);
let insert = format!("INSERT INTO `{}` VALUES (", table);
let mut ctable: Vec<String> = Vec::new();
let mut inserts: Vec<String> = Vec::new();
let mut fields: Vec<String> = Vec::new();
ctable.push(format!("CREATE TABLE IF NOT EXISTS `{}` (", table));
for record in records {
let r = record.as_object();
for c in r {
for (k, v) in c.iter() {
if v.is_object() {
let v = format!("{}", v);
let re = Regex::new("(.[^:]*):([\"-\\.:_A-Za-z0-9]*)").unwrap();
for cap in re.captures_iter(&v) {
let t = format!("{}", cap.at(1).unwrap().to_string());
let mut d = format!("{}", cap.at(2).unwrap().to_string());
let t = &t[2..t.len()-1]; // Strip type of '{"' & '}'.
if t == "$oid" &&!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` VARCHAR(24),", k));
}
else if t == "$date" {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` TIMESTAMP,", k));
}
d = parse_date(&d);
}
inserts.push(format!("{},", d));
}
}
else if v.is_string() {
let v = format!("{}", v);
if!fields.contains(&k) {
fields.push(format!("{}", k));
if!is_date(&v) {
let mut length = 50;
if k == "description" {
length = 100;
}
ctable.push(format!("`{}` VARCHAR({}),", k, length));
}
else {
ctable.push(format!("`{}` TIMESTAMP,", k));
}
}
if is_date(&v) {
inserts.push(format!("{}", parse_date(&v)));
}
else {
inserts.push(format!("{},", v));
}
}
else if v.is_number() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` NUMERIC(15, 2),", k));
}
let v = format!("{}", v);
let n = v.parse::<f32>().ok();
let v = match n {
Some(v) => v,
None => 0 as f32
};
inserts.push(format!("{:.*},", 2, v));
}
else if v.is_boolean() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` BOOLEAN,", k));
}
let v = format!("{}", v);
inserts.push(format!("{},", v.to_uppercase()));
}
}
}
}
let mut last = ctable[ctable.len() - 1].clone().to_string();
last = format!("{});", &last[0..last.len() - 1]);
let index = ctable.len() - 1;
ctable[index] = last;
let mut records: Vec<Vec<String>> = Vec::new();
let v = &inserts;
for record in v.chunks(fields.len()) {
let no_comma = fields.len() - 1;
let mut r: Vec<String> = Vec::new();
r.push(insert.clone());
for (i, c) in record.iter().enumerate() {
if i < no_comma {
r.push(c.to_string());
}
else {
r.push(format!("{});", &c[0..c.len() - 1]));
}
}
records.push(r);
}
let mut sql: Vec<String> = Vec::new();
if comments {
let timestamp: DateTime<Local> = Local::now();
sql.push(format!("-- SQL table dump from MongoDB collection: {} ({} -> {})", table, input, output));
sql.push(format!("-- Generated by: {}", signature));
sql.push(format!("-- Generated at: {}", timestamp));
sql.push(String::new());
}
if db.len() > 0 {
sql.push(format!("USE `{}`;", db));
}
sql.push(dtable);
sql.append(&mut ctable);
sql.push(String::new());
for r in records {
for f in r {
sql.push(f);
}
sql.push(String::new());
}
if verbose {
println!("\nGenerating SQL dump file: '{}' from", output);
println!("MongoDB JSON dump file: '{}'.\n", input);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(sql.join("\n").as_bytes());
}
fn check_extensions(program: &str, input: &str, output: &str) {
let mut re = Regex::new(r".json$").unwrap();
if!re.is_match(&input) {
display_error(&program, &format!("Input file '{}' is not JSON", &input));
}
re = Regex::new(r".sql$").unwrap();
if!re.is_match(&output) {
display_error(&program, &format!("Output file '{}' is not SQL", &output));
}
}
fn display_error(program: &str, err: &str) {
println!("Error: {}.", err);
display_usage(&program, -1);
}
fn display_version(signature: &str) {
println!("{}", signature);
exit(0);
}
fn display_usage(program: &str, code: i32) {
println!("\ncmongo2sql");
println!("Utility to convert a MongoDB JSON dump to a SQL dump.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Licensed under the MIT/X11 License.");
println!("\nUsage: {} -f|--file <input.json> -o|--out <output.sql>", program);
println!("-d|--db <database> -n|--no-comments -i|--ignore-ext -l|--verbose [-v|--version][-h|--help]");
println!("\n-f|--file: MongoDB JSON file to convert.");
println!("-o|--out: SQL file as output.");
println!("-d|--db: Database name to use for output.");
println!("-n|--no-comments: Do not write comments in output.");
println!("-i|--ignore-ext: Ignore file extensions for input/output.");
println!("-l|--verbose: Display console output on conversion.");
println!("-v|--version: Display program version and exit.");
println!("-h|--help: Display this help information and exit.");
exit(code);
}
fn main() {
let signature = "cmongo2sql 1.0.0 (https://github.com/stpettersens/db-tools)";
let cli = CliOptions::new("cmongo2sql");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut db = String::new();
let mut comments = true;
let mut extensions = true;
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(&signature),
"-f" | "--file" => input = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-d" | "--db" => db = cli.next_argument(i),
"-n" | "--no-comments" => comments = false,
"-i" | "--ignore-ext" => extensions = false,
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input file specified");
}
else if output.is_empty() {
display_error(&program, "No output file specified");
}
if extensions {
check_extensions(&program, &input, &output);
}
convert_json_to_sql(&signature, &input, &output, &db, comments, verbose);
}
else {
display_error(&program, "No options specified");
}
}
|
convert_json_to_sql
|
identifier_name
|
main.rs
|
/*
cmongo2sql
Utility to convert a MongoDB JSON dump to a SQL dump.
Copyright 2016 Sam Saint-Pettersen.
Licensed under the MIT/X11 License.
Rust port of original Python tool (1.0.5).
*/
extern crate clioptions;
extern crate regex;
extern crate rustc_serialize;
extern crate chrono;
use clioptions::CliOptions;
use regex::Regex;
use rustc_serialize::json::Json;
use chrono::*;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn is_date(v: &str) -> bool {
let re = Regex::new(r"\d{4}-\d{2}-\d{2}.*").unwrap();
let mut date = false;
if re.is_match(&v) {
date = true;
}
date
}
fn parse_date(v: &str) -> String {
let mut re = Regex::new("T").unwrap();
let mut p = v.to_string();
p = re.replace(&p, " ");
re = Regex::new(r"\.\d{3}Z").unwrap();
p = re.replace(&p, "");
re = Regex::new(r"\.\d{3}\+\d{4}").unwrap();
p = re.replace(&p, "");
p
}
fn convert_json_to_sql(signature: &str, input: &str, output: &str, db: &str, comments: bool, verbose: bool) {
let mut records = Vec::new();
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for line in file.lines() {
records.push(Json::from_str(&line.unwrap()).unwrap());
}
let mut table = String::new();
let re = Regex::new(r"(.*)\..{3,4}").unwrap();
for cap in re.captures_iter(&input) {
table = cap.at(1).unwrap().to_string();
}
let dtable = format!("DROP TABLE IF EXISTS `{}`;", table);
let insert = format!("INSERT INTO `{}` VALUES (", table);
let mut ctable: Vec<String> = Vec::new();
let mut inserts: Vec<String> = Vec::new();
let mut fields: Vec<String> = Vec::new();
ctable.push(format!("CREATE TABLE IF NOT EXISTS `{}` (", table));
for record in records {
let r = record.as_object();
for c in r {
for (k, v) in c.iter() {
if v.is_object() {
let v = format!("{}", v);
let re = Regex::new("(.[^:]*):([\"-\\.:_A-Za-z0-9]*)").unwrap();
for cap in re.captures_iter(&v) {
let t = format!("{}", cap.at(1).unwrap().to_string());
let mut d = format!("{}", cap.at(2).unwrap().to_string());
let t = &t[2..t.len()-1]; // Strip type of '{"' & '}'.
if t == "$oid" &&!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` VARCHAR(24),", k));
}
else if t == "$date" {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` TIMESTAMP,", k));
}
d = parse_date(&d);
}
inserts.push(format!("{},", d));
}
}
else if v.is_string() {
let v = format!("{}", v);
if!fields.contains(&k) {
fields.push(format!("{}", k));
if!is_date(&v) {
let mut length = 50;
if k == "description" {
length = 100;
}
ctable.push(format!("`{}` VARCHAR({}),", k, length));
}
else {
ctable.push(format!("`{}` TIMESTAMP,", k));
}
}
if is_date(&v) {
inserts.push(format!("{}", parse_date(&v)));
}
else {
inserts.push(format!("{},", v));
}
}
else if v.is_number() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` NUMERIC(15, 2),", k));
}
let v = format!("{}", v);
let n = v.parse::<f32>().ok();
let v = match n {
Some(v) => v,
None => 0 as f32
};
inserts.push(format!("{:.*},", 2, v));
}
else if v.is_boolean() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` BOOLEAN,", k));
}
let v = format!("{}", v);
inserts.push(format!("{},", v.to_uppercase()));
}
}
}
}
let mut last = ctable[ctable.len() - 1].clone().to_string();
last = format!("{});", &last[0..last.len() - 1]);
let index = ctable.len() - 1;
ctable[index] = last;
let mut records: Vec<Vec<String>> = Vec::new();
let v = &inserts;
for record in v.chunks(fields.len()) {
let no_comma = fields.len() - 1;
let mut r: Vec<String> = Vec::new();
r.push(insert.clone());
for (i, c) in record.iter().enumerate() {
if i < no_comma {
r.push(c.to_string());
}
else {
r.push(format!("{});", &c[0..c.len() - 1]));
}
}
records.push(r);
}
let mut sql: Vec<String> = Vec::new();
if comments {
let timestamp: DateTime<Local> = Local::now();
sql.push(format!("-- SQL table dump from MongoDB collection: {} ({} -> {})", table, input, output));
sql.push(format!("-- Generated by: {}", signature));
sql.push(format!("-- Generated at: {}", timestamp));
sql.push(String::new());
}
if db.len() > 0 {
sql.push(format!("USE `{}`;", db));
}
sql.push(dtable);
sql.append(&mut ctable);
sql.push(String::new());
for r in records {
for f in r {
sql.push(f);
}
sql.push(String::new());
}
if verbose {
println!("\nGenerating SQL dump file: '{}' from", output);
println!("MongoDB JSON dump file: '{}'.\n", input);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(sql.join("\n").as_bytes());
}
fn check_extensions(program: &str, input: &str, output: &str) {
let mut re = Regex::new(r".json$").unwrap();
if!re.is_match(&input) {
display_error(&program, &format!("Input file '{}' is not JSON", &input));
}
re = Regex::new(r".sql$").unwrap();
if!re.is_match(&output) {
display_error(&program, &format!("Output file '{}' is not SQL", &output));
}
}
fn display_error(program: &str, err: &str) {
println!("Error: {}.", err);
display_usage(&program, -1);
}
fn display_version(signature: &str) {
println!("{}", signature);
exit(0);
}
fn display_usage(program: &str, code: i32) {
println!("\ncmongo2sql");
println!("Utility to convert a MongoDB JSON dump to a SQL dump.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Licensed under the MIT/X11 License.");
println!("\nUsage: {} -f|--file <input.json> -o|--out <output.sql>", program);
println!("-d|--db <database> -n|--no-comments -i|--ignore-ext -l|--verbose [-v|--version][-h|--help]");
println!("\n-f|--file: MongoDB JSON file to convert.");
println!("-o|--out: SQL file as output.");
println!("-d|--db: Database name to use for output.");
println!("-n|--no-comments: Do not write comments in output.");
println!("-i|--ignore-ext: Ignore file extensions for input/output.");
println!("-l|--verbose: Display console output on conversion.");
println!("-v|--version: Display program version and exit.");
println!("-h|--help: Display this help information and exit.");
exit(code);
}
fn main() {
let signature = "cmongo2sql 1.0.0 (https://github.com/stpettersens/db-tools)";
let cli = CliOptions::new("cmongo2sql");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut db = String::new();
let mut comments = true;
let mut extensions = true;
let mut verbose = false;
if cli.get_num() > 1
|
}
if extensions {
check_extensions(&program, &input, &output);
}
convert_json_to_sql(&signature, &input, &output, &db, comments, verbose);
}
else {
display_error(&program, "No options specified");
}
}
|
{
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(&signature),
"-f" | "--file" => input = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-d" | "--db" => db = cli.next_argument(i),
"-n" | "--no-comments" => comments = false,
"-i" | "--ignore-ext" => extensions = false,
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input file specified");
}
else if output.is_empty() {
display_error(&program, "No output file specified");
|
conditional_block
|
main.rs
|
/*
cmongo2sql
Utility to convert a MongoDB JSON dump to a SQL dump.
Copyright 2016 Sam Saint-Pettersen.
Licensed under the MIT/X11 License.
Rust port of original Python tool (1.0.5).
*/
extern crate clioptions;
extern crate regex;
extern crate rustc_serialize;
extern crate chrono;
use clioptions::CliOptions;
use regex::Regex;
use rustc_serialize::json::Json;
use chrono::*;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn is_date(v: &str) -> bool {
let re = Regex::new(r"\d{4}-\d{2}-\d{2}.*").unwrap();
let mut date = false;
if re.is_match(&v) {
date = true;
}
date
}
fn parse_date(v: &str) -> String {
let mut re = Regex::new("T").unwrap();
let mut p = v.to_string();
p = re.replace(&p, " ");
re = Regex::new(r"\.\d{3}Z").unwrap();
p = re.replace(&p, "");
re = Regex::new(r"\.\d{3}\+\d{4}").unwrap();
p = re.replace(&p, "");
p
}
fn convert_json_to_sql(signature: &str, input: &str, output: &str, db: &str, comments: bool, verbose: bool) {
let mut records = Vec::new();
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for line in file.lines() {
records.push(Json::from_str(&line.unwrap()).unwrap());
}
let mut table = String::new();
let re = Regex::new(r"(.*)\..{3,4}").unwrap();
for cap in re.captures_iter(&input) {
table = cap.at(1).unwrap().to_string();
}
let dtable = format!("DROP TABLE IF EXISTS `{}`;", table);
let insert = format!("INSERT INTO `{}` VALUES (", table);
let mut ctable: Vec<String> = Vec::new();
let mut inserts: Vec<String> = Vec::new();
let mut fields: Vec<String> = Vec::new();
ctable.push(format!("CREATE TABLE IF NOT EXISTS `{}` (", table));
for record in records {
let r = record.as_object();
for c in r {
for (k, v) in c.iter() {
if v.is_object() {
let v = format!("{}", v);
let re = Regex::new("(.[^:]*):([\"-\\.:_A-Za-z0-9]*)").unwrap();
for cap in re.captures_iter(&v) {
let t = format!("{}", cap.at(1).unwrap().to_string());
let mut d = format!("{}", cap.at(2).unwrap().to_string());
let t = &t[2..t.len()-1]; // Strip type of '{"' & '}'.
if t == "$oid" &&!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` VARCHAR(24),", k));
}
else if t == "$date" {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` TIMESTAMP,", k));
}
d = parse_date(&d);
}
inserts.push(format!("{},", d));
}
}
else if v.is_string() {
let v = format!("{}", v);
if!fields.contains(&k) {
fields.push(format!("{}", k));
if!is_date(&v) {
let mut length = 50;
if k == "description" {
length = 100;
}
ctable.push(format!("`{}` VARCHAR({}),", k, length));
}
else {
ctable.push(format!("`{}` TIMESTAMP,", k));
}
}
if is_date(&v) {
inserts.push(format!("{}", parse_date(&v)));
}
else {
inserts.push(format!("{},", v));
}
}
else if v.is_number() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` NUMERIC(15, 2),", k));
}
let v = format!("{}", v);
let n = v.parse::<f32>().ok();
let v = match n {
Some(v) => v,
None => 0 as f32
};
inserts.push(format!("{:.*},", 2, v));
}
else if v.is_boolean() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` BOOLEAN,", k));
}
let v = format!("{}", v);
inserts.push(format!("{},", v.to_uppercase()));
}
}
}
}
let mut last = ctable[ctable.len() - 1].clone().to_string();
last = format!("{});", &last[0..last.len() - 1]);
let index = ctable.len() - 1;
ctable[index] = last;
let mut records: Vec<Vec<String>> = Vec::new();
let v = &inserts;
for record in v.chunks(fields.len()) {
let no_comma = fields.len() - 1;
let mut r: Vec<String> = Vec::new();
r.push(insert.clone());
for (i, c) in record.iter().enumerate() {
if i < no_comma {
r.push(c.to_string());
}
else {
r.push(format!("{});", &c[0..c.len() - 1]));
}
}
records.push(r);
}
let mut sql: Vec<String> = Vec::new();
if comments {
let timestamp: DateTime<Local> = Local::now();
sql.push(format!("-- SQL table dump from MongoDB collection: {} ({} -> {})", table, input, output));
sql.push(format!("-- Generated by: {}", signature));
sql.push(format!("-- Generated at: {}", timestamp));
sql.push(String::new());
}
if db.len() > 0 {
sql.push(format!("USE `{}`;", db));
}
sql.push(dtable);
sql.append(&mut ctable);
sql.push(String::new());
for r in records {
for f in r {
sql.push(f);
}
sql.push(String::new());
}
if verbose {
println!("\nGenerating SQL dump file: '{}' from", output);
println!("MongoDB JSON dump file: '{}'.\n", input);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(sql.join("\n").as_bytes());
}
fn check_extensions(program: &str, input: &str, output: &str) {
let mut re = Regex::new(r".json$").unwrap();
if!re.is_match(&input) {
display_error(&program, &format!("Input file '{}' is not JSON", &input));
}
re = Regex::new(r".sql$").unwrap();
if!re.is_match(&output) {
display_error(&program, &format!("Output file '{}' is not SQL", &output));
}
}
fn display_error(program: &str, err: &str)
|
fn display_version(signature: &str) {
println!("{}", signature);
exit(0);
}
fn display_usage(program: &str, code: i32) {
println!("\ncmongo2sql");
println!("Utility to convert a MongoDB JSON dump to a SQL dump.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Licensed under the MIT/X11 License.");
println!("\nUsage: {} -f|--file <input.json> -o|--out <output.sql>", program);
println!("-d|--db <database> -n|--no-comments -i|--ignore-ext -l|--verbose [-v|--version][-h|--help]");
println!("\n-f|--file: MongoDB JSON file to convert.");
println!("-o|--out: SQL file as output.");
println!("-d|--db: Database name to use for output.");
println!("-n|--no-comments: Do not write comments in output.");
println!("-i|--ignore-ext: Ignore file extensions for input/output.");
println!("-l|--verbose: Display console output on conversion.");
println!("-v|--version: Display program version and exit.");
println!("-h|--help: Display this help information and exit.");
exit(code);
}
fn main() {
let signature = "cmongo2sql 1.0.0 (https://github.com/stpettersens/db-tools)";
let cli = CliOptions::new("cmongo2sql");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut db = String::new();
let mut comments = true;
let mut extensions = true;
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(&signature),
"-f" | "--file" => input = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-d" | "--db" => db = cli.next_argument(i),
"-n" | "--no-comments" => comments = false,
"-i" | "--ignore-ext" => extensions = false,
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input file specified");
}
else if output.is_empty() {
display_error(&program, "No output file specified");
}
if extensions {
check_extensions(&program, &input, &output);
}
convert_json_to_sql(&signature, &input, &output, &db, comments, verbose);
}
else {
display_error(&program, "No options specified");
}
}
|
{
println!("Error: {}.", err);
display_usage(&program, -1);
}
|
identifier_body
|
main.rs
|
/*
cmongo2sql
Utility to convert a MongoDB JSON dump to a SQL dump.
Copyright 2016 Sam Saint-Pettersen.
Licensed under the MIT/X11 License.
Rust port of original Python tool (1.0.5).
*/
extern crate clioptions;
extern crate regex;
extern crate rustc_serialize;
extern crate chrono;
use clioptions::CliOptions;
use regex::Regex;
use rustc_serialize::json::Json;
use chrono::*;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn is_date(v: &str) -> bool {
let re = Regex::new(r"\d{4}-\d{2}-\d{2}.*").unwrap();
let mut date = false;
if re.is_match(&v) {
date = true;
}
date
}
fn parse_date(v: &str) -> String {
let mut re = Regex::new("T").unwrap();
let mut p = v.to_string();
p = re.replace(&p, " ");
re = Regex::new(r"\.\d{3}Z").unwrap();
p = re.replace(&p, "");
re = Regex::new(r"\.\d{3}\+\d{4}").unwrap();
p = re.replace(&p, "");
p
}
fn convert_json_to_sql(signature: &str, input: &str, output: &str, db: &str, comments: bool, verbose: bool) {
let mut records = Vec::new();
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for line in file.lines() {
records.push(Json::from_str(&line.unwrap()).unwrap());
}
let mut table = String::new();
let re = Regex::new(r"(.*)\..{3,4}").unwrap();
for cap in re.captures_iter(&input) {
table = cap.at(1).unwrap().to_string();
}
let dtable = format!("DROP TABLE IF EXISTS `{}`;", table);
let insert = format!("INSERT INTO `{}` VALUES (", table);
let mut ctable: Vec<String> = Vec::new();
let mut inserts: Vec<String> = Vec::new();
let mut fields: Vec<String> = Vec::new();
ctable.push(format!("CREATE TABLE IF NOT EXISTS `{}` (", table));
for record in records {
let r = record.as_object();
for c in r {
for (k, v) in c.iter() {
if v.is_object() {
let v = format!("{}", v);
let re = Regex::new("(.[^:]*):([\"-\\.:_A-Za-z0-9]*)").unwrap();
for cap in re.captures_iter(&v) {
let t = format!("{}", cap.at(1).unwrap().to_string());
let mut d = format!("{}", cap.at(2).unwrap().to_string());
let t = &t[2..t.len()-1]; // Strip type of '{"' & '}'.
if t == "$oid" &&!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` VARCHAR(24),", k));
}
else if t == "$date" {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` TIMESTAMP,", k));
}
d = parse_date(&d);
}
inserts.push(format!("{},", d));
}
}
else if v.is_string() {
let v = format!("{}", v);
if!fields.contains(&k) {
fields.push(format!("{}", k));
if!is_date(&v) {
let mut length = 50;
if k == "description" {
length = 100;
}
ctable.push(format!("`{}` VARCHAR({}),", k, length));
}
else {
ctable.push(format!("`{}` TIMESTAMP,", k));
}
}
if is_date(&v) {
inserts.push(format!("{}", parse_date(&v)));
}
else {
inserts.push(format!("{},", v));
}
}
else if v.is_number() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` NUMERIC(15, 2),", k));
}
let v = format!("{}", v);
let n = v.parse::<f32>().ok();
let v = match n {
Some(v) => v,
None => 0 as f32
};
inserts.push(format!("{:.*},", 2, v));
}
else if v.is_boolean() {
if!fields.contains(&k) {
fields.push(format!("{}", k));
ctable.push(format!("`{}` BOOLEAN,", k));
}
let v = format!("{}", v);
inserts.push(format!("{},", v.to_uppercase()));
}
}
}
}
let mut last = ctable[ctable.len() - 1].clone().to_string();
last = format!("{});", &last[0..last.len() - 1]);
let index = ctable.len() - 1;
ctable[index] = last;
let mut records: Vec<Vec<String>> = Vec::new();
let v = &inserts;
for record in v.chunks(fields.len()) {
let no_comma = fields.len() - 1;
let mut r: Vec<String> = Vec::new();
r.push(insert.clone());
for (i, c) in record.iter().enumerate() {
if i < no_comma {
r.push(c.to_string());
}
else {
r.push(format!("{});", &c[0..c.len() - 1]));
}
}
records.push(r);
}
let mut sql: Vec<String> = Vec::new();
if comments {
let timestamp: DateTime<Local> = Local::now();
sql.push(format!("-- SQL table dump from MongoDB collection: {} ({} -> {})", table, input, output));
sql.push(format!("-- Generated by: {}", signature));
sql.push(format!("-- Generated at: {}", timestamp));
sql.push(String::new());
}
if db.len() > 0 {
sql.push(format!("USE `{}`;", db));
}
sql.push(dtable);
sql.append(&mut ctable);
sql.push(String::new());
for r in records {
for f in r {
sql.push(f);
}
sql.push(String::new());
}
if verbose {
println!("\nGenerating SQL dump file: '{}' from", output);
println!("MongoDB JSON dump file: '{}'.\n", input);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(sql.join("\n").as_bytes());
}
fn check_extensions(program: &str, input: &str, output: &str) {
let mut re = Regex::new(r".json$").unwrap();
if!re.is_match(&input) {
display_error(&program, &format!("Input file '{}' is not JSON", &input));
}
re = Regex::new(r".sql$").unwrap();
if!re.is_match(&output) {
display_error(&program, &format!("Output file '{}' is not SQL", &output));
}
}
fn display_error(program: &str, err: &str) {
println!("Error: {}.", err);
display_usage(&program, -1);
}
fn display_version(signature: &str) {
println!("{}", signature);
exit(0);
}
fn display_usage(program: &str, code: i32) {
println!("\ncmongo2sql");
println!("Utility to convert a MongoDB JSON dump to a SQL dump.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Licensed under the MIT/X11 License.");
println!("\nUsage: {} -f|--file <input.json> -o|--out <output.sql>", program);
println!("-d|--db <database> -n|--no-comments -i|--ignore-ext -l|--verbose [-v|--version][-h|--help]");
println!("\n-f|--file: MongoDB JSON file to convert.");
println!("-o|--out: SQL file as output.");
println!("-d|--db: Database name to use for output.");
println!("-n|--no-comments: Do not write comments in output.");
println!("-i|--ignore-ext: Ignore file extensions for input/output.");
println!("-l|--verbose: Display console output on conversion.");
println!("-v|--version: Display program version and exit.");
println!("-h|--help: Display this help information and exit.");
exit(code);
}
fn main() {
let signature = "cmongo2sql 1.0.0 (https://github.com/stpettersens/db-tools)";
let cli = CliOptions::new("cmongo2sql");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut db = String::new();
let mut comments = true;
let mut extensions = true;
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(&signature),
"-f" | "--file" => input = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-d" | "--db" => db = cli.next_argument(i),
"-n" | "--no-comments" => comments = false,
"-i" | "--ignore-ext" => extensions = false,
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
|
display_error(&program, "No input file specified");
}
else if output.is_empty() {
display_error(&program, "No output file specified");
}
if extensions {
check_extensions(&program, &input, &output);
}
convert_json_to_sql(&signature, &input, &output, &db, comments, verbose);
}
else {
display_error(&program, "No options specified");
}
}
|
if input.is_empty() {
|
random_line_split
|
incremental.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 flow::{self, FlowFlags, Flow};
use style::computed_values::float;
use style::selector_parser::RestyleDamage;
use style::servo::restyle_damage::ServoRestyleDamage;
/// Used in a flow traversal to indicate whether this re-layout should be incremental or not.
#[derive(Clone, Copy, PartialEq)]
pub enum RelayoutMode {
Incremental,
Force
}
bitflags! {
pub struct SpecialRestyleDamage: u8 {
#[doc = "If this flag is set, we need to reflow the entire document. This is more or less a \
temporary hack to deal with cases that we don't handle incrementally yet."]
const REFLOW_ENTIRE_DOCUMENT = 0x01;
}
}
pub trait LayoutDamageComputation {
fn compute_layout_damage(self) -> SpecialRestyleDamage;
fn reflow_entire_document(self);
}
impl<'a> LayoutDamageComputation for &'a mut Flow {
fn compute_layout_damage(self) -> SpecialRestyleDamage
|
special_damage.insert(kid.compute_layout_damage());
}
self_base.restyle_damage
.insert(flow::base(kid).restyle_damage.damage_for_parent(
child_is_absolutely_positioned));
has_counter_affecting_children = has_counter_affecting_children ||
flow::base(kid).flags.intersects(FlowFlags::AFFECTS_COUNTERS |
FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN);
}
}
let self_base = flow::mut_base(self);
if self_base.flags.float_kind()!= float::T::none &&
self_base.restyle_damage.intersects(ServoRestyleDamage::REFLOW) {
special_damage.insert(SpecialRestyleDamage::REFLOW_ENTIRE_DOCUMENT);
}
if has_counter_affecting_children {
self_base.flags.insert(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
} else {
self_base.flags.remove(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
}
special_damage
}
fn reflow_entire_document(self) {
let self_base = flow::mut_base(self);
self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
self_base.restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
for kid in self_base.children.iter_mut() {
kid.reflow_entire_document();
}
}
}
|
{
let mut special_damage = SpecialRestyleDamage::empty();
let is_absolutely_positioned = flow::base(self).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
// In addition to damage, we use this phase to compute whether nodes affect CSS counters.
let mut has_counter_affecting_children = false;
{
let self_base = flow::mut_base(self);
// Take a snapshot of the parent damage before updating it with damage from children.
let parent_damage = self_base.restyle_damage;
for kid in self_base.children.iter_mut() {
let child_is_absolutely_positioned =
flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
flow::mut_base(kid).restyle_damage.insert(
parent_damage.damage_for_child(is_absolutely_positioned,
child_is_absolutely_positioned));
{
let kid: &mut Flow = kid;
|
identifier_body
|
incremental.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 flow::{self, FlowFlags, Flow};
use style::computed_values::float;
use style::selector_parser::RestyleDamage;
use style::servo::restyle_damage::ServoRestyleDamage;
/// Used in a flow traversal to indicate whether this re-layout should be incremental or not.
#[derive(Clone, Copy, PartialEq)]
pub enum RelayoutMode {
Incremental,
Force
}
bitflags! {
pub struct SpecialRestyleDamage: u8 {
#[doc = "If this flag is set, we need to reflow the entire document. This is more or less a \
temporary hack to deal with cases that we don't handle incrementally yet."]
const REFLOW_ENTIRE_DOCUMENT = 0x01;
}
}
pub trait LayoutDamageComputation {
fn compute_layout_damage(self) -> SpecialRestyleDamage;
fn reflow_entire_document(self);
}
impl<'a> LayoutDamageComputation for &'a mut Flow {
fn compute_layout_damage(self) -> SpecialRestyleDamage {
let mut special_damage = SpecialRestyleDamage::empty();
let is_absolutely_positioned = flow::base(self).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
// In addition to damage, we use this phase to compute whether nodes affect CSS counters.
let mut has_counter_affecting_children = false;
{
let self_base = flow::mut_base(self);
// Take a snapshot of the parent damage before updating it with damage from children.
let parent_damage = self_base.restyle_damage;
for kid in self_base.children.iter_mut() {
let child_is_absolutely_positioned =
flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
flow::mut_base(kid).restyle_damage.insert(
parent_damage.damage_for_child(is_absolutely_positioned,
child_is_absolutely_positioned));
{
let kid: &mut Flow = kid;
special_damage.insert(kid.compute_layout_damage());
}
self_base.restyle_damage
.insert(flow::base(kid).restyle_damage.damage_for_parent(
child_is_absolutely_positioned));
has_counter_affecting_children = has_counter_affecting_children ||
flow::base(kid).flags.intersects(FlowFlags::AFFECTS_COUNTERS |
FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN);
}
}
let self_base = flow::mut_base(self);
if self_base.flags.float_kind()!= float::T::none &&
self_base.restyle_damage.intersects(ServoRestyleDamage::REFLOW) {
special_damage.insert(SpecialRestyleDamage::REFLOW_ENTIRE_DOCUMENT);
}
if has_counter_affecting_children {
self_base.flags.insert(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
} else {
self_base.flags.remove(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
}
special_damage
}
fn reflow_entire_document(self) {
let self_base = flow::mut_base(self);
self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
|
}
|
self_base.restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
for kid in self_base.children.iter_mut() {
kid.reflow_entire_document();
}
}
|
random_line_split
|
incremental.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 flow::{self, FlowFlags, Flow};
use style::computed_values::float;
use style::selector_parser::RestyleDamage;
use style::servo::restyle_damage::ServoRestyleDamage;
/// Used in a flow traversal to indicate whether this re-layout should be incremental or not.
#[derive(Clone, Copy, PartialEq)]
pub enum
|
{
Incremental,
Force
}
bitflags! {
pub struct SpecialRestyleDamage: u8 {
#[doc = "If this flag is set, we need to reflow the entire document. This is more or less a \
temporary hack to deal with cases that we don't handle incrementally yet."]
const REFLOW_ENTIRE_DOCUMENT = 0x01;
}
}
pub trait LayoutDamageComputation {
fn compute_layout_damage(self) -> SpecialRestyleDamage;
fn reflow_entire_document(self);
}
impl<'a> LayoutDamageComputation for &'a mut Flow {
fn compute_layout_damage(self) -> SpecialRestyleDamage {
let mut special_damage = SpecialRestyleDamage::empty();
let is_absolutely_positioned = flow::base(self).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
// In addition to damage, we use this phase to compute whether nodes affect CSS counters.
let mut has_counter_affecting_children = false;
{
let self_base = flow::mut_base(self);
// Take a snapshot of the parent damage before updating it with damage from children.
let parent_damage = self_base.restyle_damage;
for kid in self_base.children.iter_mut() {
let child_is_absolutely_positioned =
flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
flow::mut_base(kid).restyle_damage.insert(
parent_damage.damage_for_child(is_absolutely_positioned,
child_is_absolutely_positioned));
{
let kid: &mut Flow = kid;
special_damage.insert(kid.compute_layout_damage());
}
self_base.restyle_damage
.insert(flow::base(kid).restyle_damage.damage_for_parent(
child_is_absolutely_positioned));
has_counter_affecting_children = has_counter_affecting_children ||
flow::base(kid).flags.intersects(FlowFlags::AFFECTS_COUNTERS |
FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN);
}
}
let self_base = flow::mut_base(self);
if self_base.flags.float_kind()!= float::T::none &&
self_base.restyle_damage.intersects(ServoRestyleDamage::REFLOW) {
special_damage.insert(SpecialRestyleDamage::REFLOW_ENTIRE_DOCUMENT);
}
if has_counter_affecting_children {
self_base.flags.insert(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
} else {
self_base.flags.remove(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
}
special_damage
}
fn reflow_entire_document(self) {
let self_base = flow::mut_base(self);
self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
self_base.restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
for kid in self_base.children.iter_mut() {
kid.reflow_entire_document();
}
}
}
|
RelayoutMode
|
identifier_name
|
incremental.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 flow::{self, FlowFlags, Flow};
use style::computed_values::float;
use style::selector_parser::RestyleDamage;
use style::servo::restyle_damage::ServoRestyleDamage;
/// Used in a flow traversal to indicate whether this re-layout should be incremental or not.
#[derive(Clone, Copy, PartialEq)]
pub enum RelayoutMode {
Incremental,
Force
}
bitflags! {
pub struct SpecialRestyleDamage: u8 {
#[doc = "If this flag is set, we need to reflow the entire document. This is more or less a \
temporary hack to deal with cases that we don't handle incrementally yet."]
const REFLOW_ENTIRE_DOCUMENT = 0x01;
}
}
pub trait LayoutDamageComputation {
fn compute_layout_damage(self) -> SpecialRestyleDamage;
fn reflow_entire_document(self);
}
impl<'a> LayoutDamageComputation for &'a mut Flow {
fn compute_layout_damage(self) -> SpecialRestyleDamage {
let mut special_damage = SpecialRestyleDamage::empty();
let is_absolutely_positioned = flow::base(self).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
// In addition to damage, we use this phase to compute whether nodes affect CSS counters.
let mut has_counter_affecting_children = false;
{
let self_base = flow::mut_base(self);
// Take a snapshot of the parent damage before updating it with damage from children.
let parent_damage = self_base.restyle_damage;
for kid in self_base.children.iter_mut() {
let child_is_absolutely_positioned =
flow::base(kid).flags.contains(FlowFlags::IS_ABSOLUTELY_POSITIONED);
flow::mut_base(kid).restyle_damage.insert(
parent_damage.damage_for_child(is_absolutely_positioned,
child_is_absolutely_positioned));
{
let kid: &mut Flow = kid;
special_damage.insert(kid.compute_layout_damage());
}
self_base.restyle_damage
.insert(flow::base(kid).restyle_damage.damage_for_parent(
child_is_absolutely_positioned));
has_counter_affecting_children = has_counter_affecting_children ||
flow::base(kid).flags.intersects(FlowFlags::AFFECTS_COUNTERS |
FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN);
}
}
let self_base = flow::mut_base(self);
if self_base.flags.float_kind()!= float::T::none &&
self_base.restyle_damage.intersects(ServoRestyleDamage::REFLOW) {
special_damage.insert(SpecialRestyleDamage::REFLOW_ENTIRE_DOCUMENT);
}
if has_counter_affecting_children
|
else {
self_base.flags.remove(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
}
special_damage
}
fn reflow_entire_document(self) {
let self_base = flow::mut_base(self);
self_base.restyle_damage.insert(RestyleDamage::rebuild_and_reflow());
self_base.restyle_damage.remove(ServoRestyleDamage::RECONSTRUCT_FLOW);
for kid in self_base.children.iter_mut() {
kid.reflow_entire_document();
}
}
}
|
{
self_base.flags.insert(FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN)
}
|
conditional_block
|
sendfn-spawn-with-fn-arg.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::Cell;
use std::task;
pub fn main() { test05(); }
fn
|
(f: ~fn(int)) {
f(22);
}
fn test05() {
let three = ~3;
let fn_to_send: ~fn(int) = |n| {
error!(*three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
let fn_to_send = Cell::new(fn_to_send);
task::spawn(|| {
test05_start(fn_to_send.take());
});
}
|
test05_start
|
identifier_name
|
sendfn-spawn-with-fn-arg.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::Cell;
use std::task;
pub fn main() { test05(); }
fn test05_start(f: ~fn(int))
|
fn test05() {
let three = ~3;
let fn_to_send: ~fn(int) = |n| {
error!(*three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
let fn_to_send = Cell::new(fn_to_send);
task::spawn(|| {
test05_start(fn_to_send.take());
});
}
|
{
f(22);
}
|
identifier_body
|
sendfn-spawn-with-fn-arg.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::Cell;
use std::task;
pub fn main() { test05(); }
|
fn test05_start(f: ~fn(int)) {
f(22);
}
fn test05() {
let three = ~3;
let fn_to_send: ~fn(int) = |n| {
error!(*three + n); // will copy x into the closure
assert_eq!(*three, 3);
};
let fn_to_send = Cell::new(fn_to_send);
task::spawn(|| {
test05_start(fn_to_send.take());
});
}
|
random_line_split
|
|
serviceworkerglobalscope.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 devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods;
use dom::bindings::global::{GlobalRef, global_root_from_context};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root, RootCollection};
use dom::bindings::reflector::Reflectable;
use dom::bindings::str::DOMString;
use dom::eventtarget::EventTarget;
use dom::messageevent::MessageEvent;
use dom::serviceworker::TrustedServiceWorkerAddress;
use dom::workerglobalscope::WorkerGlobalScope;
use ipc_channel::ipc::{self, IpcSender, IpcReceiver};
use ipc_channel::router::ROUTER;
use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
use msg::constellation_msg::PipelineId;
use net_traits::{LoadContext, load_whole_resource, IpcSend, CustomResponseMediator};
use rand::random;
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx};
use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg};
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::thread;
use std::time::Duration;
use style::thread_state;
use style::thread_state::{IN_WORKER, SCRIPT};
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
/// Messages used to control service worker event loop
pub enum ServiceWorkerScriptMsg {
/// Message common to all workers
CommonWorker(WorkerScriptMsg),
// Message to request a custom response by the service worker
Response(CustomResponseMediator)
}
pub enum MixedMessage {
FromServiceWorker(ServiceWorkerScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
FromTimeoutThread(()),
}
#[dom_struct]
pub struct ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
id: PipelineId,
#[ignore_heap_size_of = "Defined in std"]
receiver: Receiver<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
own_sender: Sender<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<()>,
#[ignore_heap_size_of = "Trusted<T> has unclear ownership like JS<T>"]
worker: DOMRefCell<Option<TrustedServiceWorkerAddress>>,
#[ignore_heap_size_of = "Defined in std"]
swmanager_sender: IpcSender<ServiceWorkerMsg>,
#[ignore_heap_size_of = "Defined in std"]
scope_url: Url
}
impl ServiceWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> ServiceWorkerGlobalScope {
ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(init,
worker_url,
runtime,
from_devtools_receiver,
timer_event_chan,
None),
id: id,
receiver: receiver,
timer_event_port: timer_event_port,
own_sender: own_sender,
worker: DOMRefCell::new(None),
swmanager_sender: swmanager_sender,
scope_url: scope_url
}
}
pub fn new(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> Root<ServiceWorkerGlobalScope> {
let cx = runtime.cx();
let scope = box ServiceWorkerGlobalScope::new_inherited(init,
worker_url,
id,
from_devtools_receiver,
runtime,
own_sender,
receiver,
timer_event_chan,
timer_event_port,
swmanager_sender,
scope_url);
ServiceWorkerGlobalScopeBinding::Wrap(cx, scope)
}
#[allow(unsafe_code)]
pub fn run_serviceworker_scope(scope_things: ScopeThings,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url) {
let ScopeThings { script_url,
pipeline_id,
init,
worker_load_origin,
.. } = scope_things;
let serialized_worker_url = script_url.to_string();
spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || {
thread_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(LoadContext::Script,
&init.resource_threads.sender(),
script_url,
&worker_load_origin) {
Err(_) => {
println!("error loading script {}", serialized_worker_url);
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let runtime = unsafe { new_rt_and_cx() };
let (devtools_mpsc_chan, devtools_mpsc_port) = channel();
ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan);
// TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here
let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap();
let (timer_chan, timer_port) = channel();
let global = ServiceWorkerGlobalScope::new(
init, url, pipeline_id, devtools_mpsc_port, runtime,
own_sender, receiver,
timer_ipc_chan, timer_port, swmanager_sender, scope_url);
let scope = global.upcast::<WorkerGlobalScope>();
unsafe {
// Handle interrupt requests
JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback));
}
scope.execute_script(DOMString::from(source));
// Service workers are time limited
spawn_named("SWTimeoutThread".to_owned(), move || {
let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap();
thread::sleep(Duration::new(sw_lifetime_timeout, 0));
let _ = timer_chan.send(());
});
scope.upcast::<EventTarget>().fire_simple_event("activate");
let reporter_name = format!("service-worker-reporter-{}", random::<u64>());
scope.mem_profiler_chan().run_with_memory_reporting(|| {
while let Ok(event) = global.receive_event() {
if!global.handle_event(event) {
break;
}
}
}, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports);
});
}
fn handle_event(&self, event: MixedMessage) -> bool {
match event {
MixedMessage::FromDevtools(msg) => {
let global_ref = GlobalRef::Worker(self.upcast());
match msg {
DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) =>
devtools::handle_evaluate_js(&global_ref, string, sender),
DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) =>
devtools::handle_get_cached_messages(pipe_id, message_types, sender),
DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) =>
devtools::handle_wants_live_notifications(&global_ref, bool_val),
_ => debug!("got an unusable devtools control message inside the worker!"),
}
true
}
MixedMessage::FromServiceWorker(msg) => {
self.handle_script_event(msg);
true
}
MixedMessage::FromTimeoutThread(_) => {
let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone()));
false
}
}
}
fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) {
use self::ServiceWorkerScriptMsg::*;
|
CommonWorker(WorkerScriptMsg::DOMMessage(data)) => {
let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast();
let _ac = JSAutoCompartment::new(scope.get_cx(),
scope.reflector().get_jsobject().get());
rooted!(in(scope.get_cx()) let mut message = UndefinedValue());
data.read(GlobalRef::Worker(scope), message.handle_mut());
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle());
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => {
runnable.handler()
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => {
let scope = self.upcast::<WorkerGlobalScope>();
let cx = scope.get_cx();
let path_seg = format!("url({})", scope.get_url());
let reports = get_reports(cx, path_seg);
reports_chan.send(reports);
},
Response(mediator) => {
// TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event
// when we have the Request and Response dom api's implemented
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section
self.upcast::<EventTarget>().fire_simple_event("fetch");
let _ = mediator.response_chan.send(None);
}
}
}
#[allow(unsafe_code)]
fn receive_event(&self) -> Result<MixedMessage, RecvError> {
let scope = self.upcast::<WorkerGlobalScope>();
let worker_port = &self.receiver;
let devtools_port = scope.from_devtools_receiver();
let timer_event_port = &self.timer_event_port;
let sel = Select::new();
let mut worker_handle = sel.handle(worker_port);
let mut devtools_handle = sel.handle(devtools_port);
let mut timer_port_handle = sel.handle(timer_event_port);
unsafe {
worker_handle.add();
if scope.from_devtools_sender().is_some() {
devtools_handle.add();
}
timer_port_handle.add();
}
let ret = sel.wait();
if ret == worker_handle.id() {
Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv())))
}else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(try!(devtools_port.recv())))
} else if ret == timer_port_handle.id() {
Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv())))
} else {
panic!("unexpected select result!")
}
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn process_event(&self, msg: CommonScriptMsg) {
self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg)));
}
}
#[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
let global = global_root_from_context(cx);
let worker = match global.r() {
GlobalRef::Worker(w) => w,
_ => panic!("global for worker is not a worker scope")
};
assert!(worker.is::<ServiceWorkerGlobalScope>());
// A false response causes the script to terminate
!worker.is_closing()
}
impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope {
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-global-scope-onmessage-attribute
event_handler!(message, GetOnmessage, SetOnmessage);
}
|
match msg {
|
random_line_split
|
serviceworkerglobalscope.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 devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods;
use dom::bindings::global::{GlobalRef, global_root_from_context};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root, RootCollection};
use dom::bindings::reflector::Reflectable;
use dom::bindings::str::DOMString;
use dom::eventtarget::EventTarget;
use dom::messageevent::MessageEvent;
use dom::serviceworker::TrustedServiceWorkerAddress;
use dom::workerglobalscope::WorkerGlobalScope;
use ipc_channel::ipc::{self, IpcSender, IpcReceiver};
use ipc_channel::router::ROUTER;
use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
use msg::constellation_msg::PipelineId;
use net_traits::{LoadContext, load_whole_resource, IpcSend, CustomResponseMediator};
use rand::random;
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx};
use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg};
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::thread;
use std::time::Duration;
use style::thread_state;
use style::thread_state::{IN_WORKER, SCRIPT};
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
/// Messages used to control service worker event loop
pub enum ServiceWorkerScriptMsg {
/// Message common to all workers
CommonWorker(WorkerScriptMsg),
// Message to request a custom response by the service worker
Response(CustomResponseMediator)
}
pub enum MixedMessage {
FromServiceWorker(ServiceWorkerScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
FromTimeoutThread(()),
}
#[dom_struct]
pub struct ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
id: PipelineId,
#[ignore_heap_size_of = "Defined in std"]
receiver: Receiver<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
own_sender: Sender<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<()>,
#[ignore_heap_size_of = "Trusted<T> has unclear ownership like JS<T>"]
worker: DOMRefCell<Option<TrustedServiceWorkerAddress>>,
#[ignore_heap_size_of = "Defined in std"]
swmanager_sender: IpcSender<ServiceWorkerMsg>,
#[ignore_heap_size_of = "Defined in std"]
scope_url: Url
}
impl ServiceWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> ServiceWorkerGlobalScope {
ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(init,
worker_url,
runtime,
from_devtools_receiver,
timer_event_chan,
None),
id: id,
receiver: receiver,
timer_event_port: timer_event_port,
own_sender: own_sender,
worker: DOMRefCell::new(None),
swmanager_sender: swmanager_sender,
scope_url: scope_url
}
}
pub fn new(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> Root<ServiceWorkerGlobalScope> {
let cx = runtime.cx();
let scope = box ServiceWorkerGlobalScope::new_inherited(init,
worker_url,
id,
from_devtools_receiver,
runtime,
own_sender,
receiver,
timer_event_chan,
timer_event_port,
swmanager_sender,
scope_url);
ServiceWorkerGlobalScopeBinding::Wrap(cx, scope)
}
#[allow(unsafe_code)]
pub fn run_serviceworker_scope(scope_things: ScopeThings,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url) {
let ScopeThings { script_url,
pipeline_id,
init,
worker_load_origin,
.. } = scope_things;
let serialized_worker_url = script_url.to_string();
spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || {
thread_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(LoadContext::Script,
&init.resource_threads.sender(),
script_url,
&worker_load_origin) {
Err(_) => {
println!("error loading script {}", serialized_worker_url);
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let runtime = unsafe { new_rt_and_cx() };
let (devtools_mpsc_chan, devtools_mpsc_port) = channel();
ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan);
// TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here
let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap();
let (timer_chan, timer_port) = channel();
let global = ServiceWorkerGlobalScope::new(
init, url, pipeline_id, devtools_mpsc_port, runtime,
own_sender, receiver,
timer_ipc_chan, timer_port, swmanager_sender, scope_url);
let scope = global.upcast::<WorkerGlobalScope>();
unsafe {
// Handle interrupt requests
JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback));
}
scope.execute_script(DOMString::from(source));
// Service workers are time limited
spawn_named("SWTimeoutThread".to_owned(), move || {
let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap();
thread::sleep(Duration::new(sw_lifetime_timeout, 0));
let _ = timer_chan.send(());
});
scope.upcast::<EventTarget>().fire_simple_event("activate");
let reporter_name = format!("service-worker-reporter-{}", random::<u64>());
scope.mem_profiler_chan().run_with_memory_reporting(|| {
while let Ok(event) = global.receive_event() {
if!global.handle_event(event) {
break;
}
}
}, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports);
});
}
fn handle_event(&self, event: MixedMessage) -> bool {
match event {
MixedMessage::FromDevtools(msg) => {
let global_ref = GlobalRef::Worker(self.upcast());
match msg {
DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) =>
devtools::handle_evaluate_js(&global_ref, string, sender),
DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) =>
devtools::handle_get_cached_messages(pipe_id, message_types, sender),
DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) =>
devtools::handle_wants_live_notifications(&global_ref, bool_val),
_ => debug!("got an unusable devtools control message inside the worker!"),
}
true
}
MixedMessage::FromServiceWorker(msg) => {
self.handle_script_event(msg);
true
}
MixedMessage::FromTimeoutThread(_) => {
let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone()));
false
}
}
}
fn handle_script_event(&self, msg: ServiceWorkerScriptMsg)
|
let reports = get_reports(cx, path_seg);
reports_chan.send(reports);
},
Response(mediator) => {
// TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event
// when we have the Request and Response dom api's implemented
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section
self.upcast::<EventTarget>().fire_simple_event("fetch");
let _ = mediator.response_chan.send(None);
}
}
}
#[allow(unsafe_code)]
fn receive_event(&self) -> Result<MixedMessage, RecvError> {
let scope = self.upcast::<WorkerGlobalScope>();
let worker_port = &self.receiver;
let devtools_port = scope.from_devtools_receiver();
let timer_event_port = &self.timer_event_port;
let sel = Select::new();
let mut worker_handle = sel.handle(worker_port);
let mut devtools_handle = sel.handle(devtools_port);
let mut timer_port_handle = sel.handle(timer_event_port);
unsafe {
worker_handle.add();
if scope.from_devtools_sender().is_some() {
devtools_handle.add();
}
timer_port_handle.add();
}
let ret = sel.wait();
if ret == worker_handle.id() {
Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv())))
}else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(try!(devtools_port.recv())))
} else if ret == timer_port_handle.id() {
Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv())))
} else {
panic!("unexpected select result!")
}
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn process_event(&self, msg: CommonScriptMsg) {
self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg)));
}
}
#[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
let global = global_root_from_context(cx);
let worker = match global.r() {
GlobalRef::Worker(w) => w,
_ => panic!("global for worker is not a worker scope")
};
assert!(worker.is::<ServiceWorkerGlobalScope>());
// A false response causes the script to terminate
!worker.is_closing()
}
impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope {
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-global-scope-onmessage-attribute
event_handler!(message, GetOnmessage, SetOnmessage);
}
|
{
use self::ServiceWorkerScriptMsg::*;
match msg {
CommonWorker(WorkerScriptMsg::DOMMessage(data)) => {
let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast();
let _ac = JSAutoCompartment::new(scope.get_cx(),
scope.reflector().get_jsobject().get());
rooted!(in(scope.get_cx()) let mut message = UndefinedValue());
data.read(GlobalRef::Worker(scope), message.handle_mut());
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle());
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => {
runnable.handler()
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => {
let scope = self.upcast::<WorkerGlobalScope>();
let cx = scope.get_cx();
let path_seg = format!("url({})", scope.get_url());
|
identifier_body
|
serviceworkerglobalscope.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 devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods;
use dom::bindings::global::{GlobalRef, global_root_from_context};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root, RootCollection};
use dom::bindings::reflector::Reflectable;
use dom::bindings::str::DOMString;
use dom::eventtarget::EventTarget;
use dom::messageevent::MessageEvent;
use dom::serviceworker::TrustedServiceWorkerAddress;
use dom::workerglobalscope::WorkerGlobalScope;
use ipc_channel::ipc::{self, IpcSender, IpcReceiver};
use ipc_channel::router::ROUTER;
use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
use msg::constellation_msg::PipelineId;
use net_traits::{LoadContext, load_whole_resource, IpcSend, CustomResponseMediator};
use rand::random;
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx};
use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg};
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::thread;
use std::time::Duration;
use style::thread_state;
use style::thread_state::{IN_WORKER, SCRIPT};
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
/// Messages used to control service worker event loop
pub enum ServiceWorkerScriptMsg {
/// Message common to all workers
CommonWorker(WorkerScriptMsg),
// Message to request a custom response by the service worker
Response(CustomResponseMediator)
}
pub enum MixedMessage {
FromServiceWorker(ServiceWorkerScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
FromTimeoutThread(()),
}
#[dom_struct]
pub struct ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
id: PipelineId,
#[ignore_heap_size_of = "Defined in std"]
receiver: Receiver<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
own_sender: Sender<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<()>,
#[ignore_heap_size_of = "Trusted<T> has unclear ownership like JS<T>"]
worker: DOMRefCell<Option<TrustedServiceWorkerAddress>>,
#[ignore_heap_size_of = "Defined in std"]
swmanager_sender: IpcSender<ServiceWorkerMsg>,
#[ignore_heap_size_of = "Defined in std"]
scope_url: Url
}
impl ServiceWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> ServiceWorkerGlobalScope {
ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(init,
worker_url,
runtime,
from_devtools_receiver,
timer_event_chan,
None),
id: id,
receiver: receiver,
timer_event_port: timer_event_port,
own_sender: own_sender,
worker: DOMRefCell::new(None),
swmanager_sender: swmanager_sender,
scope_url: scope_url
}
}
pub fn
|
(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> Root<ServiceWorkerGlobalScope> {
let cx = runtime.cx();
let scope = box ServiceWorkerGlobalScope::new_inherited(init,
worker_url,
id,
from_devtools_receiver,
runtime,
own_sender,
receiver,
timer_event_chan,
timer_event_port,
swmanager_sender,
scope_url);
ServiceWorkerGlobalScopeBinding::Wrap(cx, scope)
}
#[allow(unsafe_code)]
pub fn run_serviceworker_scope(scope_things: ScopeThings,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url) {
let ScopeThings { script_url,
pipeline_id,
init,
worker_load_origin,
.. } = scope_things;
let serialized_worker_url = script_url.to_string();
spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || {
thread_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(LoadContext::Script,
&init.resource_threads.sender(),
script_url,
&worker_load_origin) {
Err(_) => {
println!("error loading script {}", serialized_worker_url);
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let runtime = unsafe { new_rt_and_cx() };
let (devtools_mpsc_chan, devtools_mpsc_port) = channel();
ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan);
// TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here
let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap();
let (timer_chan, timer_port) = channel();
let global = ServiceWorkerGlobalScope::new(
init, url, pipeline_id, devtools_mpsc_port, runtime,
own_sender, receiver,
timer_ipc_chan, timer_port, swmanager_sender, scope_url);
let scope = global.upcast::<WorkerGlobalScope>();
unsafe {
// Handle interrupt requests
JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback));
}
scope.execute_script(DOMString::from(source));
// Service workers are time limited
spawn_named("SWTimeoutThread".to_owned(), move || {
let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap();
thread::sleep(Duration::new(sw_lifetime_timeout, 0));
let _ = timer_chan.send(());
});
scope.upcast::<EventTarget>().fire_simple_event("activate");
let reporter_name = format!("service-worker-reporter-{}", random::<u64>());
scope.mem_profiler_chan().run_with_memory_reporting(|| {
while let Ok(event) = global.receive_event() {
if!global.handle_event(event) {
break;
}
}
}, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports);
});
}
fn handle_event(&self, event: MixedMessage) -> bool {
match event {
MixedMessage::FromDevtools(msg) => {
let global_ref = GlobalRef::Worker(self.upcast());
match msg {
DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) =>
devtools::handle_evaluate_js(&global_ref, string, sender),
DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) =>
devtools::handle_get_cached_messages(pipe_id, message_types, sender),
DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) =>
devtools::handle_wants_live_notifications(&global_ref, bool_val),
_ => debug!("got an unusable devtools control message inside the worker!"),
}
true
}
MixedMessage::FromServiceWorker(msg) => {
self.handle_script_event(msg);
true
}
MixedMessage::FromTimeoutThread(_) => {
let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone()));
false
}
}
}
fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) {
use self::ServiceWorkerScriptMsg::*;
match msg {
CommonWorker(WorkerScriptMsg::DOMMessage(data)) => {
let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast();
let _ac = JSAutoCompartment::new(scope.get_cx(),
scope.reflector().get_jsobject().get());
rooted!(in(scope.get_cx()) let mut message = UndefinedValue());
data.read(GlobalRef::Worker(scope), message.handle_mut());
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle());
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => {
runnable.handler()
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => {
let scope = self.upcast::<WorkerGlobalScope>();
let cx = scope.get_cx();
let path_seg = format!("url({})", scope.get_url());
let reports = get_reports(cx, path_seg);
reports_chan.send(reports);
},
Response(mediator) => {
// TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event
// when we have the Request and Response dom api's implemented
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section
self.upcast::<EventTarget>().fire_simple_event("fetch");
let _ = mediator.response_chan.send(None);
}
}
}
#[allow(unsafe_code)]
fn receive_event(&self) -> Result<MixedMessage, RecvError> {
let scope = self.upcast::<WorkerGlobalScope>();
let worker_port = &self.receiver;
let devtools_port = scope.from_devtools_receiver();
let timer_event_port = &self.timer_event_port;
let sel = Select::new();
let mut worker_handle = sel.handle(worker_port);
let mut devtools_handle = sel.handle(devtools_port);
let mut timer_port_handle = sel.handle(timer_event_port);
unsafe {
worker_handle.add();
if scope.from_devtools_sender().is_some() {
devtools_handle.add();
}
timer_port_handle.add();
}
let ret = sel.wait();
if ret == worker_handle.id() {
Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv())))
}else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(try!(devtools_port.recv())))
} else if ret == timer_port_handle.id() {
Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv())))
} else {
panic!("unexpected select result!")
}
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn process_event(&self, msg: CommonScriptMsg) {
self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg)));
}
}
#[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
let global = global_root_from_context(cx);
let worker = match global.r() {
GlobalRef::Worker(w) => w,
_ => panic!("global for worker is not a worker scope")
};
assert!(worker.is::<ServiceWorkerGlobalScope>());
// A false response causes the script to terminate
!worker.is_closing()
}
impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope {
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-global-scope-onmessage-attribute
event_handler!(message, GetOnmessage, SetOnmessage);
}
|
new
|
identifier_name
|
serviceworkerglobalscope.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 devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::WorkerScriptMsg;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods;
use dom::bindings::global::{GlobalRef, global_root_from_context};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root, RootCollection};
use dom::bindings::reflector::Reflectable;
use dom::bindings::str::DOMString;
use dom::eventtarget::EventTarget;
use dom::messageevent::MessageEvent;
use dom::serviceworker::TrustedServiceWorkerAddress;
use dom::workerglobalscope::WorkerGlobalScope;
use ipc_channel::ipc::{self, IpcSender, IpcReceiver};
use ipc_channel::router::ROUTER;
use js::jsapi::{JS_SetInterruptCallback, JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
use msg::constellation_msg::PipelineId;
use net_traits::{LoadContext, load_whole_resource, IpcSend, CustomResponseMediator};
use rand::random;
use script_runtime::{CommonScriptMsg, StackRootTLS, get_reports, new_rt_and_cx};
use script_traits::{TimerEvent, WorkerGlobalScopeInit, ScopeThings, ServiceWorkerMsg};
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::thread;
use std::time::Duration;
use style::thread_state;
use style::thread_state::{IN_WORKER, SCRIPT};
use url::Url;
use util::prefs::PREFS;
use util::thread::spawn_named;
/// Messages used to control service worker event loop
pub enum ServiceWorkerScriptMsg {
/// Message common to all workers
CommonWorker(WorkerScriptMsg),
// Message to request a custom response by the service worker
Response(CustomResponseMediator)
}
pub enum MixedMessage {
FromServiceWorker(ServiceWorkerScriptMsg),
FromDevtools(DevtoolScriptControlMsg),
FromTimeoutThread(()),
}
#[dom_struct]
pub struct ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
id: PipelineId,
#[ignore_heap_size_of = "Defined in std"]
receiver: Receiver<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
own_sender: Sender<ServiceWorkerScriptMsg>,
#[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<()>,
#[ignore_heap_size_of = "Trusted<T> has unclear ownership like JS<T>"]
worker: DOMRefCell<Option<TrustedServiceWorkerAddress>>,
#[ignore_heap_size_of = "Defined in std"]
swmanager_sender: IpcSender<ServiceWorkerMsg>,
#[ignore_heap_size_of = "Defined in std"]
scope_url: Url
}
impl ServiceWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> ServiceWorkerGlobalScope {
ServiceWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(init,
worker_url,
runtime,
from_devtools_receiver,
timer_event_chan,
None),
id: id,
receiver: receiver,
timer_event_port: timer_event_port,
own_sender: own_sender,
worker: DOMRefCell::new(None),
swmanager_sender: swmanager_sender,
scope_url: scope_url
}
}
pub fn new(init: WorkerGlobalScopeInit,
worker_url: Url,
id: PipelineId,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<()>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url)
-> Root<ServiceWorkerGlobalScope> {
let cx = runtime.cx();
let scope = box ServiceWorkerGlobalScope::new_inherited(init,
worker_url,
id,
from_devtools_receiver,
runtime,
own_sender,
receiver,
timer_event_chan,
timer_event_port,
swmanager_sender,
scope_url);
ServiceWorkerGlobalScopeBinding::Wrap(cx, scope)
}
#[allow(unsafe_code)]
pub fn run_serviceworker_scope(scope_things: ScopeThings,
own_sender: Sender<ServiceWorkerScriptMsg>,
receiver: Receiver<ServiceWorkerScriptMsg>,
devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
swmanager_sender: IpcSender<ServiceWorkerMsg>,
scope_url: Url) {
let ScopeThings { script_url,
pipeline_id,
init,
worker_load_origin,
.. } = scope_things;
let serialized_worker_url = script_url.to_string();
spawn_named(format!("ServiceWorker for {}", serialized_worker_url), move || {
thread_state::initialize(SCRIPT | IN_WORKER);
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let (url, source) = match load_whole_resource(LoadContext::Script,
&init.resource_threads.sender(),
script_url,
&worker_load_origin) {
Err(_) => {
println!("error loading script {}", serialized_worker_url);
return;
}
Ok((metadata, bytes)) => {
(metadata.final_url, String::from_utf8(bytes).unwrap())
}
};
let runtime = unsafe { new_rt_and_cx() };
let (devtools_mpsc_chan, devtools_mpsc_port) = channel();
ROUTER.route_ipc_receiver_to_mpsc_sender(devtools_receiver, devtools_mpsc_chan);
// TODO XXXcreativcoder use this timer_ipc_port, when we have a service worker instance here
let (timer_ipc_chan, _timer_ipc_port) = ipc::channel().unwrap();
let (timer_chan, timer_port) = channel();
let global = ServiceWorkerGlobalScope::new(
init, url, pipeline_id, devtools_mpsc_port, runtime,
own_sender, receiver,
timer_ipc_chan, timer_port, swmanager_sender, scope_url);
let scope = global.upcast::<WorkerGlobalScope>();
unsafe {
// Handle interrupt requests
JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback));
}
scope.execute_script(DOMString::from(source));
// Service workers are time limited
spawn_named("SWTimeoutThread".to_owned(), move || {
let sw_lifetime_timeout = PREFS.get("dom.serviceworker.timeout_seconds").as_u64().unwrap();
thread::sleep(Duration::new(sw_lifetime_timeout, 0));
let _ = timer_chan.send(());
});
scope.upcast::<EventTarget>().fire_simple_event("activate");
let reporter_name = format!("service-worker-reporter-{}", random::<u64>());
scope.mem_profiler_chan().run_with_memory_reporting(|| {
while let Ok(event) = global.receive_event() {
if!global.handle_event(event) {
break;
}
}
}, reporter_name, scope.script_chan(), CommonScriptMsg::CollectReports);
});
}
fn handle_event(&self, event: MixedMessage) -> bool {
match event {
MixedMessage::FromDevtools(msg) => {
let global_ref = GlobalRef::Worker(self.upcast());
match msg {
DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) =>
devtools::handle_evaluate_js(&global_ref, string, sender),
DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) =>
devtools::handle_get_cached_messages(pipe_id, message_types, sender),
DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) =>
devtools::handle_wants_live_notifications(&global_ref, bool_val),
_ => debug!("got an unusable devtools control message inside the worker!"),
}
true
}
MixedMessage::FromServiceWorker(msg) => {
self.handle_script_event(msg);
true
}
MixedMessage::FromTimeoutThread(_) => {
let _ = self.swmanager_sender.send(ServiceWorkerMsg::Timeout(self.scope_url.clone()));
false
}
}
}
fn handle_script_event(&self, msg: ServiceWorkerScriptMsg) {
use self::ServiceWorkerScriptMsg::*;
match msg {
CommonWorker(WorkerScriptMsg::DOMMessage(data)) => {
let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast();
let _ac = JSAutoCompartment::new(scope.get_cx(),
scope.reflector().get_jsobject().get());
rooted!(in(scope.get_cx()) let mut message = UndefinedValue());
data.read(GlobalRef::Worker(scope), message.handle_mut());
MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle());
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => {
runnable.handler()
},
CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan))) => {
let scope = self.upcast::<WorkerGlobalScope>();
let cx = scope.get_cx();
let path_seg = format!("url({})", scope.get_url());
let reports = get_reports(cx, path_seg);
reports_chan.send(reports);
},
Response(mediator) => {
// TODO XXXcreativcoder This will eventually use a FetchEvent interface to fire event
// when we have the Request and Response dom api's implemented
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker_1/index.html#fetch-event-section
self.upcast::<EventTarget>().fire_simple_event("fetch");
let _ = mediator.response_chan.send(None);
}
}
}
#[allow(unsafe_code)]
fn receive_event(&self) -> Result<MixedMessage, RecvError> {
let scope = self.upcast::<WorkerGlobalScope>();
let worker_port = &self.receiver;
let devtools_port = scope.from_devtools_receiver();
let timer_event_port = &self.timer_event_port;
let sel = Select::new();
let mut worker_handle = sel.handle(worker_port);
let mut devtools_handle = sel.handle(devtools_port);
let mut timer_port_handle = sel.handle(timer_event_port);
unsafe {
worker_handle.add();
if scope.from_devtools_sender().is_some() {
devtools_handle.add();
}
timer_port_handle.add();
}
let ret = sel.wait();
if ret == worker_handle.id()
|
else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(try!(devtools_port.recv())))
} else if ret == timer_port_handle.id() {
Ok(MixedMessage::FromTimeoutThread(try!(timer_event_port.recv())))
} else {
panic!("unexpected select result!")
}
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn process_event(&self, msg: CommonScriptMsg) {
self.handle_script_event(ServiceWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(msg)));
}
}
#[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
let global = global_root_from_context(cx);
let worker = match global.r() {
GlobalRef::Worker(w) => w,
_ => panic!("global for worker is not a worker scope")
};
assert!(worker.is::<ServiceWorkerGlobalScope>());
// A false response causes the script to terminate
!worker.is_closing()
}
impl ServiceWorkerGlobalScopeMethods for ServiceWorkerGlobalScope {
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#service-worker-global-scope-onmessage-attribute
event_handler!(message, GetOnmessage, SetOnmessage);
}
|
{
Ok(MixedMessage::FromServiceWorker(try!(worker_port.recv())))
}
|
conditional_block
|
main.rs
|
// Recap: The Rules of References
// 1. At any time, you can have *either* but not both of:
// a. One mutable reference
// b. Any number of immutable references
// 2. References must always be valid.
fn main() {
references();
mutable_references();
mutable_reference_scope_invalid();
mutable_reference_scope_valid();
immutable_references();
dangling_references();
}
fn references() {
let s = String::from("Hello");
let l = calculate_length(&s);
println!("The length of {} is {}", s, l);
}
fn mutable_references() {
let s = String::from("Hello");
// change(&mut s); // Err: cannot borrow immutable as mutable
let mut s = String::from("Hello"); // mutable variable
change(&mut s); // OK!
println!("The new string is {}", s);
}
fn mutable_reference_scope_invalid() {
let mut s = String::from("Hello");
// There can only be one mutable reference to a particular data
// in a particular scope:
let r = &mut s;
// let r2 = &mut s; // cannot borrow `s` as mutable more than once at a time
{
// let r2 = &mut s; // Same as above
}
}
fn mutable_reference_scope_valid() {
let mut s = String::from("Hello");
{
let r = &mut s;
r.push_str("GG");
} // r goes out of scope
let r2 = &mut s; // And now it's okay to create a new mutable reference
}
fn immutable_references()
|
fn dangling_references() {
// let reference = dangle();
//
// fn dangle() -> &String {
// let s = String::from("Hello");
// &s // s is deallocated while the reference is returned
// }
}
fn calculate_length(s: &String) -> usize {
s.len()
}
// The following function will cause compile error
// fn change(s: &String) {
// s.push_str("GG"); // cannot borrow immutable borrowed content `*s` as mutable
// }
// The following function compiles fine
fn change(s: &mut String) {
s.push_str(", world");
}
|
{
// It's okay to have multiple immutable references in the same scope
let s = String::from("Hello");
let r = &s; // OK!
let r2 = &s; // OK!
}
|
identifier_body
|
main.rs
|
// Recap: The Rules of References
// 1. At any time, you can have *either* but not both of:
// a. One mutable reference
// b. Any number of immutable references
// 2. References must always be valid.
fn main() {
references();
mutable_references();
mutable_reference_scope_invalid();
mutable_reference_scope_valid();
immutable_references();
dangling_references();
}
fn references() {
let s = String::from("Hello");
let l = calculate_length(&s);
println!("The length of {} is {}", s, l);
}
fn mutable_references() {
let s = String::from("Hello");
// change(&mut s); // Err: cannot borrow immutable as mutable
let mut s = String::from("Hello"); // mutable variable
change(&mut s); // OK!
println!("The new string is {}", s);
}
fn mutable_reference_scope_invalid() {
let mut s = String::from("Hello");
// There can only be one mutable reference to a particular data
// in a particular scope:
let r = &mut s;
// let r2 = &mut s; // cannot borrow `s` as mutable more than once at a time
{
// let r2 = &mut s; // Same as above
}
}
fn mutable_reference_scope_valid() {
let mut s = String::from("Hello");
{
let r = &mut s;
r.push_str("GG");
} // r goes out of scope
let r2 = &mut s; // And now it's okay to create a new mutable reference
}
fn immutable_references() {
// It's okay to have multiple immutable references in the same scope
let s = String::from("Hello");
let r = &s; // OK!
let r2 = &s; // OK!
}
fn
|
() {
// let reference = dangle();
//
// fn dangle() -> &String {
// let s = String::from("Hello");
// &s // s is deallocated while the reference is returned
// }
}
fn calculate_length(s: &String) -> usize {
s.len()
}
// The following function will cause compile error
// fn change(s: &String) {
// s.push_str("GG"); // cannot borrow immutable borrowed content `*s` as mutable
// }
// The following function compiles fine
fn change(s: &mut String) {
s.push_str(", world");
}
|
dangling_references
|
identifier_name
|
main.rs
|
// Recap: The Rules of References
// 1. At any time, you can have *either* but not both of:
// a. One mutable reference
// b. Any number of immutable references
// 2. References must always be valid.
fn main() {
references();
mutable_references();
mutable_reference_scope_invalid();
mutable_reference_scope_valid();
immutable_references();
dangling_references();
}
fn references() {
let s = String::from("Hello");
let l = calculate_length(&s);
println!("The length of {} is {}", s, l);
}
fn mutable_references() {
let s = String::from("Hello");
// change(&mut s); // Err: cannot borrow immutable as mutable
let mut s = String::from("Hello"); // mutable variable
change(&mut s); // OK!
println!("The new string is {}", s);
}
fn mutable_reference_scope_invalid() {
let mut s = String::from("Hello");
// There can only be one mutable reference to a particular data
// in a particular scope:
let r = &mut s;
// let r2 = &mut s; // cannot borrow `s` as mutable more than once at a time
|
}
fn mutable_reference_scope_valid() {
let mut s = String::from("Hello");
{
let r = &mut s;
r.push_str("GG");
} // r goes out of scope
let r2 = &mut s; // And now it's okay to create a new mutable reference
}
fn immutable_references() {
// It's okay to have multiple immutable references in the same scope
let s = String::from("Hello");
let r = &s; // OK!
let r2 = &s; // OK!
}
fn dangling_references() {
// let reference = dangle();
//
// fn dangle() -> &String {
// let s = String::from("Hello");
// &s // s is deallocated while the reference is returned
// }
}
fn calculate_length(s: &String) -> usize {
s.len()
}
// The following function will cause compile error
// fn change(s: &String) {
// s.push_str("GG"); // cannot borrow immutable borrowed content `*s` as mutable
// }
// The following function compiles fine
fn change(s: &mut String) {
s.push_str(", world");
}
|
{
// let r2 = &mut s; // Same as above
}
|
random_line_split
|
i16.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.
//! Operations and constants for signed 16-bits integers (`i16` type)
#[allow(non_uppercase_statics)];
use prelude::*;
use default::Default;
use num::{Bitwise, Bounded, CheckedAdd, CheckedSub, CheckedMul};
use num::{CheckedDiv, Zero, One, strconv};
use num::{ToStrRadix, FromStrRadix};
use option::{Option, Some, None};
use str;
use unstable::intrinsics;
int_module!(i16, 16)
impl Bitwise for i16 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline]
fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } }
/// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic.
#[inline]
fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic.
#[inline]
fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } }
}
impl CheckedAdd for i16 {
#[inline]
fn checked_add(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_add_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedSub for i16 {
#[inline]
fn checked_sub(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_sub_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedMul for i16 {
|
if y { None } else { Some(x) }
}
}
}
|
#[inline]
fn checked_mul(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_mul_with_overflow(*self, *v);
|
random_line_split
|
i16.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.
//! Operations and constants for signed 16-bits integers (`i16` type)
#[allow(non_uppercase_statics)];
use prelude::*;
use default::Default;
use num::{Bitwise, Bounded, CheckedAdd, CheckedSub, CheckedMul};
use num::{CheckedDiv, Zero, One, strconv};
use num::{ToStrRadix, FromStrRadix};
use option::{Option, Some, None};
use str;
use unstable::intrinsics;
int_module!(i16, 16)
impl Bitwise for i16 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline]
fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } }
/// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic.
#[inline]
fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic.
#[inline]
fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } }
}
impl CheckedAdd for i16 {
#[inline]
fn checked_add(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_add_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedSub for i16 {
#[inline]
fn checked_sub(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_sub_with_overflow(*self, *v);
if y
|
else { Some(x) }
}
}
}
impl CheckedMul for i16 {
#[inline]
fn checked_mul(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_mul_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
|
{ None }
|
conditional_block
|
i16.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.
//! Operations and constants for signed 16-bits integers (`i16` type)
#[allow(non_uppercase_statics)];
use prelude::*;
use default::Default;
use num::{Bitwise, Bounded, CheckedAdd, CheckedSub, CheckedMul};
use num::{CheckedDiv, Zero, One, strconv};
use num::{ToStrRadix, FromStrRadix};
use option::{Option, Some, None};
use str;
use unstable::intrinsics;
int_module!(i16, 16)
impl Bitwise for i16 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline]
fn population_count(&self) -> i16
|
/// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic.
#[inline]
fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic.
#[inline]
fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } }
}
impl CheckedAdd for i16 {
#[inline]
fn checked_add(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_add_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedSub for i16 {
#[inline]
fn checked_sub(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_sub_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedMul for i16 {
#[inline]
fn checked_mul(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_mul_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
|
{ unsafe { intrinsics::ctpop16(*self) } }
|
identifier_body
|
i16.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.
//! Operations and constants for signed 16-bits integers (`i16` type)
#[allow(non_uppercase_statics)];
use prelude::*;
use default::Default;
use num::{Bitwise, Bounded, CheckedAdd, CheckedSub, CheckedMul};
use num::{CheckedDiv, Zero, One, strconv};
use num::{ToStrRadix, FromStrRadix};
use option::{Option, Some, None};
use str;
use unstable::intrinsics;
int_module!(i16, 16)
impl Bitwise for i16 {
/// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic.
#[inline]
fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } }
/// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic.
#[inline]
fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } }
/// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic.
#[inline]
fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } }
}
impl CheckedAdd for i16 {
#[inline]
fn checked_add(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_add_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedSub for i16 {
#[inline]
fn
|
(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_sub_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
impl CheckedMul for i16 {
#[inline]
fn checked_mul(&self, v: &i16) -> Option<i16> {
unsafe {
let (x, y) = intrinsics::i16_mul_with_overflow(*self, *v);
if y { None } else { Some(x) }
}
}
}
|
checked_sub
|
identifier_name
|
extern-stress.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.
// This creates a bunch of yielding tasks that run concurrently
// while holding onto C stacks
use std::libc;
use std::task;
mod rustrt {
use std::libc;
pub extern {
pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
task::yield();
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
rustrt::rust_dbg_call(cb, n)
}
}
pub fn
|
() {
for 100u.times {
do task::spawn {
assert_eq!(count(5u), 16u);
};
}
}
|
main
|
identifier_name
|
extern-stress.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.
// This creates a bunch of yielding tasks that run concurrently
// while holding onto C stacks
use std::libc;
use std::task;
mod rustrt {
use std::libc;
pub extern {
pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u
|
else {
task::yield();
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
for 100u.times {
do task::spawn {
assert_eq!(count(5u), 16u);
};
}
}
|
{
data
}
|
conditional_block
|
extern-stress.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.
// This creates a bunch of yielding tasks that run concurrently
// while holding onto C stacks
use std::libc;
use std::task;
mod rustrt {
use std::libc;
pub extern {
pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t {
if data == 1u {
data
} else {
task::yield();
count(data - 1u) + count(data - 1u)
}
}
fn count(n: uint) -> uint {
unsafe {
rustrt::rust_dbg_call(cb, n)
}
}
|
for 100u.times {
do task::spawn {
assert_eq!(count(5u), 16u);
};
}
}
|
pub fn main() {
|
random_line_split
|
extern-stress.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.
// This creates a bunch of yielding tasks that run concurrently
// while holding onto C stacks
use std::libc;
use std::task;
mod rustrt {
use std::libc;
pub extern {
pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t)
-> libc::uintptr_t;
}
}
extern fn cb(data: libc::uintptr_t) -> libc::uintptr_t
|
fn count(n: uint) -> uint {
unsafe {
rustrt::rust_dbg_call(cb, n)
}
}
pub fn main() {
for 100u.times {
do task::spawn {
assert_eq!(count(5u), 16u);
};
}
}
|
{
if data == 1u {
data
} else {
task::yield();
count(data - 1u) + count(data - 1u)
}
}
|
identifier_body
|
build.rs
|
extern crate capnpc;
extern crate cc;
extern crate cmake;
fn main() {
// Compile RPC schema file into rust code
capnpc::CompilerCommand::new()
.src_prefix("schema")
.file("schema/pung.capnp")
.run().expect("schema compiler command");
// Compile and link pung C++ PIR shim
cc::Build::new()
.file("src/pir/cpp/pungPIR.cpp")
.include("deps/xpir/")
.flag("-std=c++11")
.flag("-fopenmp")
.flag("-Wno-unused-parameter")
.pic(true)
.cpp(true)
.compile("libpung_pir.a");
|
.define("PERF_TIMERS", "OFF")
.build();
println!("cargo:rustc-link-search=native={}/build/pir", dst.display());
println!("cargo:rustc-link-lib=static=pir_static");
// Dynamic libraries needed by XPIR
println!("cargo:rustc-link-lib=gomp");
println!("cargo:rustc-link-lib=gmp");
println!("cargo:rustc-link-lib=mpfr");
println!("cargo:rustc-link-lib=boost_thread");
println!("cargo:rustc-link-lib=boost_system");
}
|
// Compile and link XPIR c++ shim
let dst = cmake::Config::new("deps/xpir")
.define("CMAKE_BUILD_TYPE", "Release")
.define("MULTI_THREAD", "OFF")
|
random_line_split
|
build.rs
|
extern crate capnpc;
extern crate cc;
extern crate cmake;
fn main()
|
// Compile and link XPIR c++ shim
let dst = cmake::Config::new("deps/xpir")
.define("CMAKE_BUILD_TYPE", "Release")
.define("MULTI_THREAD", "OFF")
.define("PERF_TIMERS", "OFF")
.build();
println!("cargo:rustc-link-search=native={}/build/pir", dst.display());
println!("cargo:rustc-link-lib=static=pir_static");
// Dynamic libraries needed by XPIR
println!("cargo:rustc-link-lib=gomp");
println!("cargo:rustc-link-lib=gmp");
println!("cargo:rustc-link-lib=mpfr");
println!("cargo:rustc-link-lib=boost_thread");
println!("cargo:rustc-link-lib=boost_system");
}
|
{
// Compile RPC schema file into rust code
capnpc::CompilerCommand::new()
.src_prefix("schema")
.file("schema/pung.capnp")
.run().expect("schema compiler command");
// Compile and link pung C++ PIR shim
cc::Build::new()
.file("src/pir/cpp/pungPIR.cpp")
.include("deps/xpir/")
.flag("-std=c++11")
.flag("-fopenmp")
.flag("-Wno-unused-parameter")
.pic(true)
.cpp(true)
.compile("libpung_pir.a");
|
identifier_body
|
build.rs
|
extern crate capnpc;
extern crate cc;
extern crate cmake;
fn
|
() {
// Compile RPC schema file into rust code
capnpc::CompilerCommand::new()
.src_prefix("schema")
.file("schema/pung.capnp")
.run().expect("schema compiler command");
// Compile and link pung C++ PIR shim
cc::Build::new()
.file("src/pir/cpp/pungPIR.cpp")
.include("deps/xpir/")
.flag("-std=c++11")
.flag("-fopenmp")
.flag("-Wno-unused-parameter")
.pic(true)
.cpp(true)
.compile("libpung_pir.a");
// Compile and link XPIR c++ shim
let dst = cmake::Config::new("deps/xpir")
.define("CMAKE_BUILD_TYPE", "Release")
.define("MULTI_THREAD", "OFF")
.define("PERF_TIMERS", "OFF")
.build();
println!("cargo:rustc-link-search=native={}/build/pir", dst.display());
println!("cargo:rustc-link-lib=static=pir_static");
// Dynamic libraries needed by XPIR
println!("cargo:rustc-link-lib=gomp");
println!("cargo:rustc-link-lib=gmp");
println!("cargo:rustc-link-lib=mpfr");
println!("cargo:rustc-link-lib=boost_thread");
println!("cargo:rustc-link-lib=boost_system");
}
|
main
|
identifier_name
|
trait-bounds-basic.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(core)]
trait Foo : ::std::marker::MarkerTrait {
}
fn
|
(_x: Box<Foo+Send>) {
}
fn c(x: Box<Foo+Sync+Send>) {
e(x);
}
fn d(x: Box<Foo+Send>) {
e(x);
}
fn e(x: Box<Foo>) {
e(x);
}
pub fn main() { }
|
b
|
identifier_name
|
trait-bounds-basic.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(core)]
trait Foo : ::std::marker::MarkerTrait {
}
fn b(_x: Box<Foo+Send>) {
}
fn c(x: Box<Foo+Sync+Send>) {
e(x);
|
fn d(x: Box<Foo+Send>) {
e(x);
}
fn e(x: Box<Foo>) {
e(x);
}
pub fn main() { }
|
}
|
random_line_split
|
trait-bounds-basic.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
#![feature(core)]
trait Foo : ::std::marker::MarkerTrait {
}
fn b(_x: Box<Foo+Send>) {
}
fn c(x: Box<Foo+Sync+Send>) {
e(x);
}
fn d(x: Box<Foo+Send>)
|
fn e(x: Box<Foo>) {
e(x);
}
pub fn main() { }
|
{
e(x);
}
|
identifier_body
|
lib.rs
|
#![crate_name = "xpath"]
#![feature(macro_rules)]
extern crate document;
use std::collections::HashMap;
use document::{Any,ToAny};
use document::{Nodeset};
use tokenizer::{XPathTokenizer,XPathTokenDeabbreviator,XPathTokenDisambiguator};
use parser::XPathParser;
pub mod axis;
pub mod expression;
pub mod function;
pub mod node_test;
pub mod parser;
pub mod token;
pub mod tokenizer;
#[deriving(PartialEq,Show,Clone)]
pub enum XPathValue {
Boolean(bool),
Number(f64),
String(String),
Nodes(Nodeset), // rename as Nodeset
}
impl XPathValue {
pub fn boolean(&self) -> bool {
match *self {
Boolean(val) => val,
Number(n) => n!= 0.0 &&! n.is_nan(),
String(ref s) =>! s.is_empty(),
Nodes(ref nodeset) => nodeset.size() > 0,
}
}
pub fn number(&self) -> f64 {
match *self {
Number(val) => val,
_ => -42.0
}
}
pub fn string(&self) -> String {
match *self {
String(ref val) => val.clone(),
_ => "Unimplemented".to_string(),
}
}
pub fn nodeset(&self) -> Nodeset {
match *self {
Nodes(ref ns) => ns.clone(),
_ => fail!("Did not evaluate to a nodeset!"),
}
}
}
pub trait XPathFunction {
fn evaluate(&self,
context: &XPathEvaluationContext,
args: Vec<XPathValue>) -> XPathValue;
}
type BoxFunc = Box<XPathFunction +'static>;
pub type Functions = HashMap<String, BoxFunc>;
pub type Variables = HashMap<String, XPathValue>;
pub struct XPathEvaluationContext<'a> {
node: Any,
functions: & 'a Functions,
variables: & 'a Variables,
position: uint,
}
impl<'a> XPathEvaluationContext<'a> {
pub fn new<A: ToAny>(node: A,
functions: &'a Functions,
variables: &'a Variables) -> XPathEvaluationContext<'a>
{
XPathEvaluationContext {
node: node.to_any(),
functions: functions,
variables: variables,
position: 0,
}
}
fn node(&self) -> &Any {
&self.node
}
fn new_context_for(& self, _size: uint) -> XPathEvaluationContext<'a> {
XPathEvaluationContext {
node: self.node.clone(),
functions: self.functions,
variables: self.variables,
position: 0,
}
}
|
}
fn position(&self) -> uint {
self.position
}
fn function_for_name(&self, name: &str) -> Option<& 'a BoxFunc> {
self.functions.find(&name.to_string())
}
fn value_of(&self, name: &str) -> Option<&XPathValue> {
self.variables.find(&name.to_string())
}
}
pub struct XPathFactory {
parser: XPathParser,
}
impl XPathFactory {
pub fn new() -> XPathFactory {
XPathFactory { parser: XPathParser::new() }
}
pub fn build(&self, xpath: &str) -> parser::ParseResult {
let tokenizer = XPathTokenizer::new(xpath);
let deabbreviator = XPathTokenDeabbreviator::new(tokenizer);
let disambiguator = XPathTokenDisambiguator::new(deabbreviator);
self.parser.parse(disambiguator)
}
}
|
pub fn next<A: ToAny>(& mut self, node: A) {
self.node = node.to_any();
self.position += 1;
|
random_line_split
|
lib.rs
|
#![crate_name = "xpath"]
#![feature(macro_rules)]
extern crate document;
use std::collections::HashMap;
use document::{Any,ToAny};
use document::{Nodeset};
use tokenizer::{XPathTokenizer,XPathTokenDeabbreviator,XPathTokenDisambiguator};
use parser::XPathParser;
pub mod axis;
pub mod expression;
pub mod function;
pub mod node_test;
pub mod parser;
pub mod token;
pub mod tokenizer;
#[deriving(PartialEq,Show,Clone)]
pub enum XPathValue {
Boolean(bool),
Number(f64),
String(String),
Nodes(Nodeset), // rename as Nodeset
}
impl XPathValue {
pub fn boolean(&self) -> bool {
match *self {
Boolean(val) => val,
Number(n) => n!= 0.0 &&! n.is_nan(),
String(ref s) =>! s.is_empty(),
Nodes(ref nodeset) => nodeset.size() > 0,
}
}
pub fn number(&self) -> f64 {
match *self {
Number(val) => val,
_ => -42.0
}
}
pub fn string(&self) -> String {
match *self {
String(ref val) => val.clone(),
_ => "Unimplemented".to_string(),
}
}
pub fn nodeset(&self) -> Nodeset {
match *self {
Nodes(ref ns) => ns.clone(),
_ => fail!("Did not evaluate to a nodeset!"),
}
}
}
pub trait XPathFunction {
fn evaluate(&self,
context: &XPathEvaluationContext,
args: Vec<XPathValue>) -> XPathValue;
}
type BoxFunc = Box<XPathFunction +'static>;
pub type Functions = HashMap<String, BoxFunc>;
pub type Variables = HashMap<String, XPathValue>;
pub struct XPathEvaluationContext<'a> {
node: Any,
functions: & 'a Functions,
variables: & 'a Variables,
position: uint,
}
impl<'a> XPathEvaluationContext<'a> {
pub fn
|
<A: ToAny>(node: A,
functions: &'a Functions,
variables: &'a Variables) -> XPathEvaluationContext<'a>
{
XPathEvaluationContext {
node: node.to_any(),
functions: functions,
variables: variables,
position: 0,
}
}
fn node(&self) -> &Any {
&self.node
}
fn new_context_for(& self, _size: uint) -> XPathEvaluationContext<'a> {
XPathEvaluationContext {
node: self.node.clone(),
functions: self.functions,
variables: self.variables,
position: 0,
}
}
pub fn next<A: ToAny>(& mut self, node: A) {
self.node = node.to_any();
self.position += 1;
}
fn position(&self) -> uint {
self.position
}
fn function_for_name(&self, name: &str) -> Option<& 'a BoxFunc> {
self.functions.find(&name.to_string())
}
fn value_of(&self, name: &str) -> Option<&XPathValue> {
self.variables.find(&name.to_string())
}
}
pub struct XPathFactory {
parser: XPathParser,
}
impl XPathFactory {
pub fn new() -> XPathFactory {
XPathFactory { parser: XPathParser::new() }
}
pub fn build(&self, xpath: &str) -> parser::ParseResult {
let tokenizer = XPathTokenizer::new(xpath);
let deabbreviator = XPathTokenDeabbreviator::new(tokenizer);
let disambiguator = XPathTokenDisambiguator::new(deabbreviator);
self.parser.parse(disambiguator)
}
}
|
new
|
identifier_name
|
optimizer.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/. */
//! Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
use display_list::{DisplayItem, DisplayList, StackingContext};
use collections::dlist::DList;
use geom::rect::Rect;
use servo_util::geometry::{mod, Au};
use sync::Arc;
/// Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
pub struct DisplayListOptimizer {
/// The visible rect in page coordinates.
visible_rect: Rect<Au>,
}
impl DisplayListOptimizer {
/// Creates a new display list optimizer object. `visible_rect` specifies the visible rect in
/// page coordinates.
pub fn new(visible_rect: &Rect<f32>) -> DisplayListOptimizer {
DisplayListOptimizer {
visible_rect: geometry::f32_rect_to_au_rect(*visible_rect),
}
}
/// Optimizes the given display list, returning an equivalent, but cheaper-to-paint, one.
pub fn optimize(self, display_list: &DisplayList) -> DisplayList {
let mut result = DisplayList::new();
self.add_in_bounds_display_items(&mut result.background_and_borders,
display_list.background_and_borders.iter());
self.add_in_bounds_display_items(&mut result.block_backgrounds_and_borders,
display_list.block_backgrounds_and_borders.iter());
self.add_in_bounds_display_items(&mut result.floats, display_list.floats.iter());
self.add_in_bounds_display_items(&mut result.content, display_list.content.iter());
self.add_in_bounds_stacking_contexts(&mut result.children, display_list.children.iter());
result
}
/// Adds display items that intersect the visible rect to `result_list`.
fn add_in_bounds_display_items<'a,I>(&self,
result_list: &mut DList<DisplayItem>,
mut display_items: I)
where I: Iterator<&'a DisplayItem> {
for display_item in display_items {
if self.visible_rect.intersects(&display_item.base().bounds) &&
self.visible_rect.intersects(&display_item.base().clip_rect) {
result_list.push_back((*display_item).clone())
}
}
}
/// Adds child stacking contexts whose boundaries intersect the visible rect to `result_list`.
fn add_in_bounds_stacking_contexts<'a,I>(&self,
result_list: &mut DList<Arc<StackingContext>>,
mut stacking_contexts: I)
|
self.visible_rect.intersects(&stacking_context.clip_rect) {
result_list.push_back((*stacking_context).clone())
}
}
}
}
|
where I: Iterator<&'a Arc<StackingContext>> {
for stacking_context in stacking_contexts {
if self.visible_rect.intersects(&stacking_context.bounds) &&
|
random_line_split
|
optimizer.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/. */
//! Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
use display_list::{DisplayItem, DisplayList, StackingContext};
use collections::dlist::DList;
use geom::rect::Rect;
use servo_util::geometry::{mod, Au};
use sync::Arc;
/// Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
pub struct DisplayListOptimizer {
/// The visible rect in page coordinates.
visible_rect: Rect<Au>,
}
impl DisplayListOptimizer {
/// Creates a new display list optimizer object. `visible_rect` specifies the visible rect in
/// page coordinates.
pub fn new(visible_rect: &Rect<f32>) -> DisplayListOptimizer {
DisplayListOptimizer {
visible_rect: geometry::f32_rect_to_au_rect(*visible_rect),
}
}
/// Optimizes the given display list, returning an equivalent, but cheaper-to-paint, one.
pub fn optimize(self, display_list: &DisplayList) -> DisplayList
|
/// Adds display items that intersect the visible rect to `result_list`.
fn add_in_bounds_display_items<'a,I>(&self,
result_list: &mut DList<DisplayItem>,
mut display_items: I)
where I: Iterator<&'a DisplayItem> {
for display_item in display_items {
if self.visible_rect.intersects(&display_item.base().bounds) &&
self.visible_rect.intersects(&display_item.base().clip_rect) {
result_list.push_back((*display_item).clone())
}
}
}
/// Adds child stacking contexts whose boundaries intersect the visible rect to `result_list`.
fn add_in_bounds_stacking_contexts<'a,I>(&self,
result_list: &mut DList<Arc<StackingContext>>,
mut stacking_contexts: I)
where I: Iterator<&'a Arc<StackingContext>> {
for stacking_context in stacking_contexts {
if self.visible_rect.intersects(&stacking_context.bounds) &&
self.visible_rect.intersects(&stacking_context.clip_rect) {
result_list.push_back((*stacking_context).clone())
}
}
}
}
|
{
let mut result = DisplayList::new();
self.add_in_bounds_display_items(&mut result.background_and_borders,
display_list.background_and_borders.iter());
self.add_in_bounds_display_items(&mut result.block_backgrounds_and_borders,
display_list.block_backgrounds_and_borders.iter());
self.add_in_bounds_display_items(&mut result.floats, display_list.floats.iter());
self.add_in_bounds_display_items(&mut result.content, display_list.content.iter());
self.add_in_bounds_stacking_contexts(&mut result.children, display_list.children.iter());
result
}
|
identifier_body
|
optimizer.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/. */
//! Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
use display_list::{DisplayItem, DisplayList, StackingContext};
use collections::dlist::DList;
use geom::rect::Rect;
use servo_util::geometry::{mod, Au};
use sync::Arc;
/// Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
pub struct DisplayListOptimizer {
/// The visible rect in page coordinates.
visible_rect: Rect<Au>,
}
impl DisplayListOptimizer {
/// Creates a new display list optimizer object. `visible_rect` specifies the visible rect in
/// page coordinates.
pub fn new(visible_rect: &Rect<f32>) -> DisplayListOptimizer {
DisplayListOptimizer {
visible_rect: geometry::f32_rect_to_au_rect(*visible_rect),
}
}
/// Optimizes the given display list, returning an equivalent, but cheaper-to-paint, one.
pub fn optimize(self, display_list: &DisplayList) -> DisplayList {
let mut result = DisplayList::new();
self.add_in_bounds_display_items(&mut result.background_and_borders,
display_list.background_and_borders.iter());
self.add_in_bounds_display_items(&mut result.block_backgrounds_and_borders,
display_list.block_backgrounds_and_borders.iter());
self.add_in_bounds_display_items(&mut result.floats, display_list.floats.iter());
self.add_in_bounds_display_items(&mut result.content, display_list.content.iter());
self.add_in_bounds_stacking_contexts(&mut result.children, display_list.children.iter());
result
}
/// Adds display items that intersect the visible rect to `result_list`.
fn add_in_bounds_display_items<'a,I>(&self,
result_list: &mut DList<DisplayItem>,
mut display_items: I)
where I: Iterator<&'a DisplayItem> {
for display_item in display_items {
if self.visible_rect.intersects(&display_item.base().bounds) &&
self.visible_rect.intersects(&display_item.base().clip_rect) {
result_list.push_back((*display_item).clone())
}
}
}
/// Adds child stacking contexts whose boundaries intersect the visible rect to `result_list`.
fn
|
<'a,I>(&self,
result_list: &mut DList<Arc<StackingContext>>,
mut stacking_contexts: I)
where I: Iterator<&'a Arc<StackingContext>> {
for stacking_context in stacking_contexts {
if self.visible_rect.intersects(&stacking_context.bounds) &&
self.visible_rect.intersects(&stacking_context.clip_rect) {
result_list.push_back((*stacking_context).clone())
}
}
}
}
|
add_in_bounds_stacking_contexts
|
identifier_name
|
optimizer.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/. */
//! Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
use display_list::{DisplayItem, DisplayList, StackingContext};
use collections::dlist::DList;
use geom::rect::Rect;
use servo_util::geometry::{mod, Au};
use sync::Arc;
/// Transforms a display list to produce a visually-equivalent, but cheaper-to-render, one.
pub struct DisplayListOptimizer {
/// The visible rect in page coordinates.
visible_rect: Rect<Au>,
}
impl DisplayListOptimizer {
/// Creates a new display list optimizer object. `visible_rect` specifies the visible rect in
/// page coordinates.
pub fn new(visible_rect: &Rect<f32>) -> DisplayListOptimizer {
DisplayListOptimizer {
visible_rect: geometry::f32_rect_to_au_rect(*visible_rect),
}
}
/// Optimizes the given display list, returning an equivalent, but cheaper-to-paint, one.
pub fn optimize(self, display_list: &DisplayList) -> DisplayList {
let mut result = DisplayList::new();
self.add_in_bounds_display_items(&mut result.background_and_borders,
display_list.background_and_borders.iter());
self.add_in_bounds_display_items(&mut result.block_backgrounds_and_borders,
display_list.block_backgrounds_and_borders.iter());
self.add_in_bounds_display_items(&mut result.floats, display_list.floats.iter());
self.add_in_bounds_display_items(&mut result.content, display_list.content.iter());
self.add_in_bounds_stacking_contexts(&mut result.children, display_list.children.iter());
result
}
/// Adds display items that intersect the visible rect to `result_list`.
fn add_in_bounds_display_items<'a,I>(&self,
result_list: &mut DList<DisplayItem>,
mut display_items: I)
where I: Iterator<&'a DisplayItem> {
for display_item in display_items {
if self.visible_rect.intersects(&display_item.base().bounds) &&
self.visible_rect.intersects(&display_item.base().clip_rect)
|
}
}
/// Adds child stacking contexts whose boundaries intersect the visible rect to `result_list`.
fn add_in_bounds_stacking_contexts<'a,I>(&self,
result_list: &mut DList<Arc<StackingContext>>,
mut stacking_contexts: I)
where I: Iterator<&'a Arc<StackingContext>> {
for stacking_context in stacking_contexts {
if self.visible_rect.intersects(&stacking_context.bounds) &&
self.visible_rect.intersects(&stacking_context.clip_rect) {
result_list.push_back((*stacking_context).clone())
}
}
}
}
|
{
result_list.push_back((*display_item).clone())
}
|
conditional_block
|
main_context.rs
|
// Copyright 2015-2016, 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 <https://opensource.org/licenses/MIT>
use glib_sys::{self, gboolean, gpointer};
use source::Priority;
use std::mem;
use translate::*;
use MainContext;
use Source;
use SourceId;
impl MainContext {
pub fn prepare(&self) -> (bool, i32) {
unsafe {
let mut priority = mem::MaybeUninit::uninit();
let res = from_glib(glib_sys::g_main_context_prepare(
self.to_glib_none().0,
priority.as_mut_ptr(),
));
let priority = priority.assume_init();
(res, priority)
}
}
pub fn find_source_by_id(&self, source_id: &SourceId) -> Option<Source> {
unsafe {
from_glib_none(glib_sys::g_main_context_find_source_by_id(
self.to_glib_none().0,
source_id.to_glib(),
))
}
}
/// Invokes `func` on the main context.
pub fn invoke<F>(&self, func: F)
where
F: FnOnce() + Send +'static,
{
self.invoke_with_priority(::PRIORITY_DEFAULT_IDLE, func);
}
/// Invokes `func` on the main context with the given priority.
pub fn invoke_with_priority<F>(&self, priority: Priority, func: F)
where
F: FnOnce() + Send +'static,
{
unsafe {
self.invoke_unsafe(priority, func);
}
}
/// Invokes `func` on the main context.
///
/// Different to `invoke()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
pub fn invoke_local<F>(&self, func: F)
where
F: FnOnce() +'static,
{
self.invoke_local_with_priority(::PRIORITY_DEFAULT_IDLE, func);
}
/// Invokes `func` on the main context with the given priority.
///
/// Different to `invoke_with_priority()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
pub fn invoke_local_with_priority<F>(&self, priority: Priority, func: F)
where
F: FnOnce() +'static,
{
unsafe {
assert!(self.is_owner());
self.invoke_unsafe(priority, func);
}
}
unsafe fn invoke_unsafe<F>(&self, priority: Priority, func: F)
where
F: FnOnce() +'static,
{
unsafe extern "C" fn trampoline<F: FnOnce() +'static>(func: gpointer) -> gboolean {
let func: &mut Option<F> = &mut *(func as *mut Option<F>);
let func = func
.take()
.expect("MainContext::invoke() closure called multiple times");
func();
glib_sys::G_SOURCE_REMOVE
}
unsafe extern "C" fn destroy_closure<F: FnOnce() +'static>(ptr: gpointer) {
Box::<Option<F>>::from_raw(ptr as *mut _);
}
let func = Box::into_raw(Box::new(Some(func)));
glib_sys::g_main_context_invoke_full(
self.to_glib_none().0,
priority.to_glib(),
Some(trampoline::<F>),
func as gpointer,
Some(destroy_closure::<F>),
)
}
/// Calls closure with context configured as the thread default one.
///
/// Thread default context is changed in panic-safe manner by calling
/// [`push_thread_default`][push_thread_default] before calling closure
/// and [`pop_thread_default`][pop_thread_default] afterwards regardless
/// of whether closure panicked or not.
///
/// [push_thread_default]: struct.MainContext.html#method.push_thread_default
/// [pop_thread_default]: struct.MainContext.html#method.pop_thread_default
pub fn with_thread_default<R, F: Sized>(&self, func: F) -> R
where
F: FnOnce() -> R,
{
let _thread_default = ThreadDefaultContext::new(self);
func()
}
}
struct ThreadDefaultContext<'a>(&'a MainContext);
impl<'a> ThreadDefaultContext<'a> {
fn new(ctx: &MainContext) -> ThreadDefaultContext {
ctx.push_thread_default();
ThreadDefaultContext(ctx)
}
}
impl<'a> Drop for ThreadDefaultContext<'a> {
fn drop(&mut self) {
self.0.pop_thread_default();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic;
use std::ptr;
use std::thread;
#[test]
fn test_invoke() {
let c = MainContext::new();
let l = ::MainLoop::new(Some(&c), false);
let l_clone = l.clone();
thread::spawn(move || {
c.invoke(move || l_clone.quit());
});
l.run();
}
fn is_same_context(a: &MainContext, b: &MainContext) -> bool {
ptr::eq(a.to_glib_none().0, b.to_glib_none().0)
}
#[test]
fn
|
() {
let a = MainContext::new();
let b = MainContext::new();
assert!(!is_same_context(&a, &b));
a.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
b.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&b, &t));
});
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
});
}
#[test]
fn test_with_thread_default_is_panic_safe() {
let a = MainContext::new();
let b = MainContext::new();
assert!(!is_same_context(&a, &b));
a.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
let result = panic::catch_unwind(|| {
b.with_thread_default(|| {
panic!();
});
});
assert!(result.is_err());
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
});
}
}
|
test_with_thread_default
|
identifier_name
|
main_context.rs
|
// Copyright 2015-2016, 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 <https://opensource.org/licenses/MIT>
use glib_sys::{self, gboolean, gpointer};
use source::Priority;
use std::mem;
use translate::*;
use MainContext;
use Source;
use SourceId;
impl MainContext {
pub fn prepare(&self) -> (bool, i32) {
unsafe {
let mut priority = mem::MaybeUninit::uninit();
let res = from_glib(glib_sys::g_main_context_prepare(
self.to_glib_none().0,
priority.as_mut_ptr(),
));
let priority = priority.assume_init();
(res, priority)
}
}
pub fn find_source_by_id(&self, source_id: &SourceId) -> Option<Source> {
unsafe {
from_glib_none(glib_sys::g_main_context_find_source_by_id(
self.to_glib_none().0,
source_id.to_glib(),
))
}
}
/// Invokes `func` on the main context.
pub fn invoke<F>(&self, func: F)
where
F: FnOnce() + Send +'static,
{
self.invoke_with_priority(::PRIORITY_DEFAULT_IDLE, func);
}
/// Invokes `func` on the main context with the given priority.
pub fn invoke_with_priority<F>(&self, priority: Priority, func: F)
where
F: FnOnce() + Send +'static,
{
unsafe {
self.invoke_unsafe(priority, func);
}
}
/// Invokes `func` on the main context.
///
/// Different to `invoke()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
pub fn invoke_local<F>(&self, func: F)
where
F: FnOnce() +'static,
{
self.invoke_local_with_priority(::PRIORITY_DEFAULT_IDLE, func);
}
/// Invokes `func` on the main context with the given priority.
///
/// Different to `invoke_with_priority()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
pub fn invoke_local_with_priority<F>(&self, priority: Priority, func: F)
where
F: FnOnce() +'static,
{
unsafe {
assert!(self.is_owner());
self.invoke_unsafe(priority, func);
}
}
unsafe fn invoke_unsafe<F>(&self, priority: Priority, func: F)
where
F: FnOnce() +'static,
{
unsafe extern "C" fn trampoline<F: FnOnce() +'static>(func: gpointer) -> gboolean {
let func: &mut Option<F> = &mut *(func as *mut Option<F>);
let func = func
.take()
.expect("MainContext::invoke() closure called multiple times");
func();
glib_sys::G_SOURCE_REMOVE
}
unsafe extern "C" fn destroy_closure<F: FnOnce() +'static>(ptr: gpointer) {
Box::<Option<F>>::from_raw(ptr as *mut _);
}
let func = Box::into_raw(Box::new(Some(func)));
glib_sys::g_main_context_invoke_full(
self.to_glib_none().0,
priority.to_glib(),
Some(trampoline::<F>),
func as gpointer,
Some(destroy_closure::<F>),
)
}
/// Calls closure with context configured as the thread default one.
///
/// Thread default context is changed in panic-safe manner by calling
/// [`push_thread_default`][push_thread_default] before calling closure
/// and [`pop_thread_default`][pop_thread_default] afterwards regardless
/// of whether closure panicked or not.
///
/// [push_thread_default]: struct.MainContext.html#method.push_thread_default
/// [pop_thread_default]: struct.MainContext.html#method.pop_thread_default
pub fn with_thread_default<R, F: Sized>(&self, func: F) -> R
where
F: FnOnce() -> R,
{
let _thread_default = ThreadDefaultContext::new(self);
func()
}
}
struct ThreadDefaultContext<'a>(&'a MainContext);
impl<'a> ThreadDefaultContext<'a> {
fn new(ctx: &MainContext) -> ThreadDefaultContext {
ctx.push_thread_default();
ThreadDefaultContext(ctx)
}
}
impl<'a> Drop for ThreadDefaultContext<'a> {
fn drop(&mut self) {
self.0.pop_thread_default();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic;
|
fn test_invoke() {
let c = MainContext::new();
let l = ::MainLoop::new(Some(&c), false);
let l_clone = l.clone();
thread::spawn(move || {
c.invoke(move || l_clone.quit());
});
l.run();
}
fn is_same_context(a: &MainContext, b: &MainContext) -> bool {
ptr::eq(a.to_glib_none().0, b.to_glib_none().0)
}
#[test]
fn test_with_thread_default() {
let a = MainContext::new();
let b = MainContext::new();
assert!(!is_same_context(&a, &b));
a.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
b.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&b, &t));
});
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
});
}
#[test]
fn test_with_thread_default_is_panic_safe() {
let a = MainContext::new();
let b = MainContext::new();
assert!(!is_same_context(&a, &b));
a.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
let result = panic::catch_unwind(|| {
b.with_thread_default(|| {
panic!();
});
});
assert!(result.is_err());
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
});
}
}
|
use std::ptr;
use std::thread;
#[test]
|
random_line_split
|
main_context.rs
|
// Copyright 2015-2016, 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 <https://opensource.org/licenses/MIT>
use glib_sys::{self, gboolean, gpointer};
use source::Priority;
use std::mem;
use translate::*;
use MainContext;
use Source;
use SourceId;
impl MainContext {
pub fn prepare(&self) -> (bool, i32) {
unsafe {
let mut priority = mem::MaybeUninit::uninit();
let res = from_glib(glib_sys::g_main_context_prepare(
self.to_glib_none().0,
priority.as_mut_ptr(),
));
let priority = priority.assume_init();
(res, priority)
}
}
pub fn find_source_by_id(&self, source_id: &SourceId) -> Option<Source> {
unsafe {
from_glib_none(glib_sys::g_main_context_find_source_by_id(
self.to_glib_none().0,
source_id.to_glib(),
))
}
}
/// Invokes `func` on the main context.
pub fn invoke<F>(&self, func: F)
where
F: FnOnce() + Send +'static,
{
self.invoke_with_priority(::PRIORITY_DEFAULT_IDLE, func);
}
/// Invokes `func` on the main context with the given priority.
pub fn invoke_with_priority<F>(&self, priority: Priority, func: F)
where
F: FnOnce() + Send +'static,
{
unsafe {
self.invoke_unsafe(priority, func);
}
}
/// Invokes `func` on the main context.
///
/// Different to `invoke()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
pub fn invoke_local<F>(&self, func: F)
where
F: FnOnce() +'static,
{
self.invoke_local_with_priority(::PRIORITY_DEFAULT_IDLE, func);
}
/// Invokes `func` on the main context with the given priority.
///
/// Different to `invoke_with_priority()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
pub fn invoke_local_with_priority<F>(&self, priority: Priority, func: F)
where
F: FnOnce() +'static,
{
unsafe {
assert!(self.is_owner());
self.invoke_unsafe(priority, func);
}
}
unsafe fn invoke_unsafe<F>(&self, priority: Priority, func: F)
where
F: FnOnce() +'static,
{
unsafe extern "C" fn trampoline<F: FnOnce() +'static>(func: gpointer) -> gboolean
|
unsafe extern "C" fn destroy_closure<F: FnOnce() +'static>(ptr: gpointer) {
Box::<Option<F>>::from_raw(ptr as *mut _);
}
let func = Box::into_raw(Box::new(Some(func)));
glib_sys::g_main_context_invoke_full(
self.to_glib_none().0,
priority.to_glib(),
Some(trampoline::<F>),
func as gpointer,
Some(destroy_closure::<F>),
)
}
/// Calls closure with context configured as the thread default one.
///
/// Thread default context is changed in panic-safe manner by calling
/// [`push_thread_default`][push_thread_default] before calling closure
/// and [`pop_thread_default`][pop_thread_default] afterwards regardless
/// of whether closure panicked or not.
///
/// [push_thread_default]: struct.MainContext.html#method.push_thread_default
/// [pop_thread_default]: struct.MainContext.html#method.pop_thread_default
pub fn with_thread_default<R, F: Sized>(&self, func: F) -> R
where
F: FnOnce() -> R,
{
let _thread_default = ThreadDefaultContext::new(self);
func()
}
}
struct ThreadDefaultContext<'a>(&'a MainContext);
impl<'a> ThreadDefaultContext<'a> {
fn new(ctx: &MainContext) -> ThreadDefaultContext {
ctx.push_thread_default();
ThreadDefaultContext(ctx)
}
}
impl<'a> Drop for ThreadDefaultContext<'a> {
fn drop(&mut self) {
self.0.pop_thread_default();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::panic;
use std::ptr;
use std::thread;
#[test]
fn test_invoke() {
let c = MainContext::new();
let l = ::MainLoop::new(Some(&c), false);
let l_clone = l.clone();
thread::spawn(move || {
c.invoke(move || l_clone.quit());
});
l.run();
}
fn is_same_context(a: &MainContext, b: &MainContext) -> bool {
ptr::eq(a.to_glib_none().0, b.to_glib_none().0)
}
#[test]
fn test_with_thread_default() {
let a = MainContext::new();
let b = MainContext::new();
assert!(!is_same_context(&a, &b));
a.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
b.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&b, &t));
});
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
});
}
#[test]
fn test_with_thread_default_is_panic_safe() {
let a = MainContext::new();
let b = MainContext::new();
assert!(!is_same_context(&a, &b));
a.with_thread_default(|| {
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
let result = panic::catch_unwind(|| {
b.with_thread_default(|| {
panic!();
});
});
assert!(result.is_err());
let t = MainContext::get_thread_default().unwrap();
assert!(is_same_context(&a, &t));
});
}
}
|
{
let func: &mut Option<F> = &mut *(func as *mut Option<F>);
let func = func
.take()
.expect("MainContext::invoke() closure called multiple times");
func();
glib_sys::G_SOURCE_REMOVE
}
|
identifier_body
|
ir.rs
|
//! Enumerations and structs to represent instructions.
//! Shared by the SSA representation and the intermediate representation of the ESIL parser.
use std::default::Default;
pub type Address = u64;
pub type WidthSpec = u16;
#[derive(Debug, Clone, Default)]
pub struct MAddr {
// maybe store section id and offset instead
pub val: u64,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MArity {
Zero,
Unary,
Binary,
Ternary, // Unused for now. Maybe remove later?
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MValType {
Register,
Temporary,
Internal,
EsilCur,
EsilOld,
Lastsz,
Unknown,
Null,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MOpcode {
OpAdd,
OpSub,
OpMul,
OpDiv,
OpMod,
OpAnd,
OpOr,
OpXor,
OpNot,
OpEq,
OpCmp,
OpGt,
OpLt,
OpLteq,
OpGteq,
OpLsl,
OpLsr,
OpIf,
OpJmp,
OpCJmp,
OpCall,
OpLoad,
OpStore,
OpNarrow(WidthSpec),
OpWiden(WidthSpec),
OpConst(u64),
OpNop,
OpInvalid,
OpInc,
OpDec,
OpCl, // '}'
}
#[derive(Debug, Clone, Default)]
pub struct MRegInfo {
pub reg_type: String,
pub reg: String,
pub size: usize,
pub alias: String,
pub offset: usize,
}
#[derive(Debug, Clone)]
pub struct MVal {
pub name: String,
pub size: WidthSpec,
pub val_type: MValType,
pub reg_info: Option<MRegInfo>,
pub typeset: u32,
pub as_literal: Option<u64>,
}
// Default for MVal is null.
impl Default for MVal {
fn default() -> Self {
MVal::new("".to_string(), 0, MValType::Null, 0, None)
}
}
// Minor: Change MInst to take Option<MVal> instead. This will allow us to eliminate MVal::null and
// check for `None` instead.
#[derive(Debug, Clone)]
pub struct MInst {
pub addr: MAddr,
pub opcode: MOpcode,
pub dst: MVal,
pub operand_1: MVal,
pub operand_2: MVal,
pub update_flags: bool,
}
impl MOpcode {
pub fn
|
(&self, dst: MVal, op1: MVal, op2: MVal, addr: Option<MAddr>) -> MInst {
MInst::new(*self, dst, op1, op2, addr)
}
pub fn is_binary(&self) -> bool {
self.arity() == MArity::Binary
}
pub fn is_unary(&self) -> bool {
self.arity() == MArity::Unary
}
pub fn arity(&self) -> MArity {
self.info().1
}
pub fn to_string(&self) -> String {
self.info().0
}
pub fn has_sideeffects(&self) -> bool {
match *self {
MOpcode::OpStore => true,
MOpcode::OpJmp => true,
MOpcode::OpCJmp => true,
MOpcode::OpCall => true,
_ => false,
}
}
pub fn allowed_in_ssa(&self) -> bool {
match *self {
MOpcode::OpJmp => false,
MOpcode::OpCJmp => false,
MOpcode::OpNop => false,
MOpcode::OpInvalid => false,
MOpcode::OpInc => false,
MOpcode::OpDec => false,
MOpcode::OpCl => false,
_ => true,
}
}
fn info(&self) -> (String, MArity) {
let (op, arity) = match *self {
MOpcode::OpAdd => ("+", MArity::Binary),
MOpcode::OpSub => ("-", MArity::Binary),
MOpcode::OpMul => ("*", MArity::Binary),
MOpcode::OpDiv => ("/", MArity::Binary),
MOpcode::OpMod => ("%", MArity::Binary),
MOpcode::OpAnd => ("&", MArity::Binary),
MOpcode::OpOr => ("|", MArity::Binary),
MOpcode::OpXor => ("^", MArity::Binary),
MOpcode::OpNot => ("!", MArity::Unary),
MOpcode::OpEq => ("=", MArity::Binary),
MOpcode::OpCmp => ("==", MArity::Binary),
MOpcode::OpGt => (">", MArity::Binary),
MOpcode::OpLt => ("<", MArity::Binary),
MOpcode::OpLteq => ("<=", MArity::Binary),
MOpcode::OpGteq => (">=", MArity::Binary),
MOpcode::OpLsl => ("<<", MArity::Binary),
MOpcode::OpLsr => (">>", MArity::Binary),
MOpcode::OpIf => ("if", MArity::Unary),
MOpcode::OpLoad => ("load", MArity::Unary),
MOpcode::OpStore => ("store", MArity::Binary),
MOpcode::OpNarrow(_) => ("narrow", MArity::Unary),
MOpcode::OpWiden(_) => ("widen", MArity::Unary),
MOpcode::OpJmp => ("jmp", MArity::Unary),
MOpcode::OpCJmp => ("jmp if", MArity::Binary),
MOpcode::OpCall => ("call", MArity::Unary),
MOpcode::OpConst(_) => ("const", MArity::Zero),
MOpcode::OpNop => ("nop", MArity::Zero),
MOpcode::OpInvalid => ("invalid", MArity::Zero),
MOpcode::OpInc => ("++", MArity::Unary),
MOpcode::OpDec => ("--", MArity::Unary),
MOpcode::OpCl => ("}", MArity::Zero),
};
(String::from(op), arity)
}
}
impl MRegInfo {
pub fn new() -> MRegInfo {
let def: MRegInfo = Default::default();
def
}
}
impl MVal {
pub fn new(name: String, size: WidthSpec, val_type: MValType, typeset: u32, reg_info: Option<MRegInfo>) -> MVal {
MVal {
name: name.clone(),
size: size,
val_type: val_type,
typeset: typeset,
reg_info: reg_info,
as_literal: None
}
}
pub fn null() -> MVal {
MVal::new("".to_string(), 0, MValType::Null, 0, None)
}
pub fn tmp(i: u64, size: WidthSpec) -> MVal {
MVal::new(format!("tmp_{:x}", i), size, MValType::Temporary, 0, None)
}
pub fn esilcur() -> MVal {
MVal::new("".to_string(), 64, MValType::EsilCur, 0, None)
}
pub fn esilold() -> MVal {
MVal::new("".to_string(), 64, MValType::EsilOld, 0, None)
}
pub fn esillastsz() -> MVal {
MVal::new("".to_string(), 64, MValType::Lastsz, 0, None)
}
}
impl MInst {
pub fn new(opcode: MOpcode, dst: MVal, op1: MVal, op2: MVal, _addr: Option<MAddr>) -> MInst {
let addr = _addr.unwrap_or_default();
MInst {
addr: addr,
opcode: opcode,
dst: dst,
operand_1: op1,
operand_2: op2,
update_flags: false,
}
}
}
impl MAddr {
pub fn new(addr: u64) -> MAddr {
MAddr { val: addr }
}
}
|
to_inst
|
identifier_name
|
ir.rs
|
//! Enumerations and structs to represent instructions.
//! Shared by the SSA representation and the intermediate representation of the ESIL parser.
use std::default::Default;
pub type Address = u64;
pub type WidthSpec = u16;
#[derive(Debug, Clone, Default)]
pub struct MAddr {
// maybe store section id and offset instead
pub val: u64,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MArity {
Zero,
Unary,
Binary,
Ternary, // Unused for now. Maybe remove later?
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MValType {
Register,
Temporary,
Internal,
EsilCur,
EsilOld,
Lastsz,
Unknown,
Null,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MOpcode {
OpAdd,
OpSub,
OpMul,
OpDiv,
OpMod,
OpAnd,
OpOr,
OpXor,
OpNot,
OpEq,
OpCmp,
OpGt,
OpLt,
OpLteq,
OpGteq,
OpLsl,
OpLsr,
OpIf,
OpJmp,
OpCJmp,
OpCall,
OpLoad,
OpStore,
OpNarrow(WidthSpec),
OpWiden(WidthSpec),
OpConst(u64),
OpNop,
OpInvalid,
OpInc,
OpDec,
OpCl, // '}'
}
#[derive(Debug, Clone, Default)]
pub struct MRegInfo {
pub reg_type: String,
pub reg: String,
pub size: usize,
pub alias: String,
pub offset: usize,
}
#[derive(Debug, Clone)]
pub struct MVal {
pub name: String,
pub size: WidthSpec,
pub val_type: MValType,
pub reg_info: Option<MRegInfo>,
pub typeset: u32,
pub as_literal: Option<u64>,
}
// Default for MVal is null.
impl Default for MVal {
fn default() -> Self {
MVal::new("".to_string(), 0, MValType::Null, 0, None)
}
}
// Minor: Change MInst to take Option<MVal> instead. This will allow us to eliminate MVal::null and
// check for `None` instead.
#[derive(Debug, Clone)]
pub struct MInst {
pub addr: MAddr,
pub opcode: MOpcode,
pub dst: MVal,
pub operand_1: MVal,
pub operand_2: MVal,
pub update_flags: bool,
}
impl MOpcode {
pub fn to_inst(&self, dst: MVal, op1: MVal, op2: MVal, addr: Option<MAddr>) -> MInst {
MInst::new(*self, dst, op1, op2, addr)
}
pub fn is_binary(&self) -> bool {
self.arity() == MArity::Binary
}
pub fn is_unary(&self) -> bool {
self.arity() == MArity::Unary
}
pub fn arity(&self) -> MArity {
self.info().1
}
pub fn to_string(&self) -> String {
self.info().0
}
pub fn has_sideeffects(&self) -> bool {
match *self {
MOpcode::OpStore => true,
MOpcode::OpJmp => true,
MOpcode::OpCJmp => true,
MOpcode::OpCall => true,
_ => false,
}
}
pub fn allowed_in_ssa(&self) -> bool {
match *self {
MOpcode::OpJmp => false,
MOpcode::OpCJmp => false,
MOpcode::OpNop => false,
MOpcode::OpInvalid => false,
MOpcode::OpInc => false,
MOpcode::OpDec => false,
MOpcode::OpCl => false,
_ => true,
}
}
fn info(&self) -> (String, MArity) {
let (op, arity) = match *self {
MOpcode::OpAdd => ("+", MArity::Binary),
MOpcode::OpSub => ("-", MArity::Binary),
MOpcode::OpMul => ("*", MArity::Binary),
MOpcode::OpDiv => ("/", MArity::Binary),
MOpcode::OpMod => ("%", MArity::Binary),
MOpcode::OpAnd => ("&", MArity::Binary),
MOpcode::OpOr => ("|", MArity::Binary),
MOpcode::OpXor => ("^", MArity::Binary),
MOpcode::OpNot => ("!", MArity::Unary),
MOpcode::OpEq => ("=", MArity::Binary),
MOpcode::OpCmp => ("==", MArity::Binary),
MOpcode::OpGt => (">", MArity::Binary),
MOpcode::OpLt => ("<", MArity::Binary),
MOpcode::OpLteq => ("<=", MArity::Binary),
MOpcode::OpGteq => (">=", MArity::Binary),
MOpcode::OpLsl => ("<<", MArity::Binary),
MOpcode::OpLsr => (">>", MArity::Binary),
MOpcode::OpIf => ("if", MArity::Unary),
MOpcode::OpLoad => ("load", MArity::Unary),
MOpcode::OpStore => ("store", MArity::Binary),
MOpcode::OpNarrow(_) => ("narrow", MArity::Unary),
MOpcode::OpWiden(_) => ("widen", MArity::Unary),
MOpcode::OpJmp => ("jmp", MArity::Unary),
MOpcode::OpCJmp => ("jmp if", MArity::Binary),
MOpcode::OpCall => ("call", MArity::Unary),
MOpcode::OpConst(_) => ("const", MArity::Zero),
MOpcode::OpNop => ("nop", MArity::Zero),
MOpcode::OpInvalid => ("invalid", MArity::Zero),
MOpcode::OpInc => ("++", MArity::Unary),
MOpcode::OpDec => ("--", MArity::Unary),
MOpcode::OpCl => ("}", MArity::Zero),
};
(String::from(op), arity)
}
}
impl MRegInfo {
pub fn new() -> MRegInfo {
let def: MRegInfo = Default::default();
def
}
}
impl MVal {
pub fn new(name: String, size: WidthSpec, val_type: MValType, typeset: u32, reg_info: Option<MRegInfo>) -> MVal {
MVal {
name: name.clone(),
size: size,
val_type: val_type,
typeset: typeset,
reg_info: reg_info,
as_literal: None
}
}
pub fn null() -> MVal {
MVal::new("".to_string(), 0, MValType::Null, 0, None)
}
pub fn tmp(i: u64, size: WidthSpec) -> MVal {
MVal::new(format!("tmp_{:x}", i), size, MValType::Temporary, 0, None)
}
pub fn esilcur() -> MVal
|
pub fn esilold() -> MVal {
MVal::new("".to_string(), 64, MValType::EsilOld, 0, None)
}
pub fn esillastsz() -> MVal {
MVal::new("".to_string(), 64, MValType::Lastsz, 0, None)
}
}
impl MInst {
pub fn new(opcode: MOpcode, dst: MVal, op1: MVal, op2: MVal, _addr: Option<MAddr>) -> MInst {
let addr = _addr.unwrap_or_default();
MInst {
addr: addr,
opcode: opcode,
dst: dst,
operand_1: op1,
operand_2: op2,
update_flags: false,
}
}
}
impl MAddr {
pub fn new(addr: u64) -> MAddr {
MAddr { val: addr }
}
}
|
{
MVal::new("".to_string(), 64, MValType::EsilCur, 0, None)
}
|
identifier_body
|
ir.rs
|
//! Enumerations and structs to represent instructions.
//! Shared by the SSA representation and the intermediate representation of the ESIL parser.
use std::default::Default;
pub type Address = u64;
pub type WidthSpec = u16;
#[derive(Debug, Clone, Default)]
pub struct MAddr {
// maybe store section id and offset instead
pub val: u64,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MArity {
Zero,
Unary,
|
pub enum MValType {
Register,
Temporary,
Internal,
EsilCur,
EsilOld,
Lastsz,
Unknown,
Null,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum MOpcode {
OpAdd,
OpSub,
OpMul,
OpDiv,
OpMod,
OpAnd,
OpOr,
OpXor,
OpNot,
OpEq,
OpCmp,
OpGt,
OpLt,
OpLteq,
OpGteq,
OpLsl,
OpLsr,
OpIf,
OpJmp,
OpCJmp,
OpCall,
OpLoad,
OpStore,
OpNarrow(WidthSpec),
OpWiden(WidthSpec),
OpConst(u64),
OpNop,
OpInvalid,
OpInc,
OpDec,
OpCl, // '}'
}
#[derive(Debug, Clone, Default)]
pub struct MRegInfo {
pub reg_type: String,
pub reg: String,
pub size: usize,
pub alias: String,
pub offset: usize,
}
#[derive(Debug, Clone)]
pub struct MVal {
pub name: String,
pub size: WidthSpec,
pub val_type: MValType,
pub reg_info: Option<MRegInfo>,
pub typeset: u32,
pub as_literal: Option<u64>,
}
// Default for MVal is null.
impl Default for MVal {
fn default() -> Self {
MVal::new("".to_string(), 0, MValType::Null, 0, None)
}
}
// Minor: Change MInst to take Option<MVal> instead. This will allow us to eliminate MVal::null and
// check for `None` instead.
#[derive(Debug, Clone)]
pub struct MInst {
pub addr: MAddr,
pub opcode: MOpcode,
pub dst: MVal,
pub operand_1: MVal,
pub operand_2: MVal,
pub update_flags: bool,
}
impl MOpcode {
pub fn to_inst(&self, dst: MVal, op1: MVal, op2: MVal, addr: Option<MAddr>) -> MInst {
MInst::new(*self, dst, op1, op2, addr)
}
pub fn is_binary(&self) -> bool {
self.arity() == MArity::Binary
}
pub fn is_unary(&self) -> bool {
self.arity() == MArity::Unary
}
pub fn arity(&self) -> MArity {
self.info().1
}
pub fn to_string(&self) -> String {
self.info().0
}
pub fn has_sideeffects(&self) -> bool {
match *self {
MOpcode::OpStore => true,
MOpcode::OpJmp => true,
MOpcode::OpCJmp => true,
MOpcode::OpCall => true,
_ => false,
}
}
pub fn allowed_in_ssa(&self) -> bool {
match *self {
MOpcode::OpJmp => false,
MOpcode::OpCJmp => false,
MOpcode::OpNop => false,
MOpcode::OpInvalid => false,
MOpcode::OpInc => false,
MOpcode::OpDec => false,
MOpcode::OpCl => false,
_ => true,
}
}
fn info(&self) -> (String, MArity) {
let (op, arity) = match *self {
MOpcode::OpAdd => ("+", MArity::Binary),
MOpcode::OpSub => ("-", MArity::Binary),
MOpcode::OpMul => ("*", MArity::Binary),
MOpcode::OpDiv => ("/", MArity::Binary),
MOpcode::OpMod => ("%", MArity::Binary),
MOpcode::OpAnd => ("&", MArity::Binary),
MOpcode::OpOr => ("|", MArity::Binary),
MOpcode::OpXor => ("^", MArity::Binary),
MOpcode::OpNot => ("!", MArity::Unary),
MOpcode::OpEq => ("=", MArity::Binary),
MOpcode::OpCmp => ("==", MArity::Binary),
MOpcode::OpGt => (">", MArity::Binary),
MOpcode::OpLt => ("<", MArity::Binary),
MOpcode::OpLteq => ("<=", MArity::Binary),
MOpcode::OpGteq => (">=", MArity::Binary),
MOpcode::OpLsl => ("<<", MArity::Binary),
MOpcode::OpLsr => (">>", MArity::Binary),
MOpcode::OpIf => ("if", MArity::Unary),
MOpcode::OpLoad => ("load", MArity::Unary),
MOpcode::OpStore => ("store", MArity::Binary),
MOpcode::OpNarrow(_) => ("narrow", MArity::Unary),
MOpcode::OpWiden(_) => ("widen", MArity::Unary),
MOpcode::OpJmp => ("jmp", MArity::Unary),
MOpcode::OpCJmp => ("jmp if", MArity::Binary),
MOpcode::OpCall => ("call", MArity::Unary),
MOpcode::OpConst(_) => ("const", MArity::Zero),
MOpcode::OpNop => ("nop", MArity::Zero),
MOpcode::OpInvalid => ("invalid", MArity::Zero),
MOpcode::OpInc => ("++", MArity::Unary),
MOpcode::OpDec => ("--", MArity::Unary),
MOpcode::OpCl => ("}", MArity::Zero),
};
(String::from(op), arity)
}
}
impl MRegInfo {
pub fn new() -> MRegInfo {
let def: MRegInfo = Default::default();
def
}
}
impl MVal {
pub fn new(name: String, size: WidthSpec, val_type: MValType, typeset: u32, reg_info: Option<MRegInfo>) -> MVal {
MVal {
name: name.clone(),
size: size,
val_type: val_type,
typeset: typeset,
reg_info: reg_info,
as_literal: None
}
}
pub fn null() -> MVal {
MVal::new("".to_string(), 0, MValType::Null, 0, None)
}
pub fn tmp(i: u64, size: WidthSpec) -> MVal {
MVal::new(format!("tmp_{:x}", i), size, MValType::Temporary, 0, None)
}
pub fn esilcur() -> MVal {
MVal::new("".to_string(), 64, MValType::EsilCur, 0, None)
}
pub fn esilold() -> MVal {
MVal::new("".to_string(), 64, MValType::EsilOld, 0, None)
}
pub fn esillastsz() -> MVal {
MVal::new("".to_string(), 64, MValType::Lastsz, 0, None)
}
}
impl MInst {
pub fn new(opcode: MOpcode, dst: MVal, op1: MVal, op2: MVal, _addr: Option<MAddr>) -> MInst {
let addr = _addr.unwrap_or_default();
MInst {
addr: addr,
opcode: opcode,
dst: dst,
operand_1: op1,
operand_2: op2,
update_flags: false,
}
}
}
impl MAddr {
pub fn new(addr: u64) -> MAddr {
MAddr { val: addr }
}
}
|
Binary,
Ternary, // Unused for now. Maybe remove later?
}
#[derive(Debug, Copy, Clone, PartialEq)]
|
random_line_split
|
regions-close-object-into-object-5.rs
|
#![allow(warnings)]
trait A<T>
{
fn get(&self) -> T { panic!() }
}
struct B<'a, T: 'a>(&'a (A<T> + 'a));
trait X { fn foo(&self) {} }
impl<'a, T> X for B<'a, T> {}
fn f<'a, T, U>(v: Box<A<T> +'static>) -> Box<X +'static> {
// oh dear!
|
Box::new(B(&*v)) as Box<dyn X>
//~^ ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
}
fn main() {}
|
random_line_split
|
|
regions-close-object-into-object-5.rs
|
#![allow(warnings)]
trait A<T>
{
fn get(&self) -> T { panic!() }
}
struct B<'a, T: 'a>(&'a (A<T> + 'a));
trait X { fn foo(&self)
|
}
impl<'a, T> X for B<'a, T> {}
fn f<'a, T, U>(v: Box<A<T> +'static>) -> Box<X +'static> {
// oh dear!
Box::new(B(&*v)) as Box<dyn X>
//~^ ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
}
fn main() {}
|
{}
|
identifier_body
|
regions-close-object-into-object-5.rs
|
#![allow(warnings)]
trait A<T>
{
fn get(&self) -> T { panic!() }
}
struct
|
<'a, T: 'a>(&'a (A<T> + 'a));
trait X { fn foo(&self) {} }
impl<'a, T> X for B<'a, T> {}
fn f<'a, T, U>(v: Box<A<T> +'static>) -> Box<X +'static> {
// oh dear!
Box::new(B(&*v)) as Box<dyn X>
//~^ ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
//~| ERROR the parameter type `T` may not live long enough
}
fn main() {}
|
B
|
identifier_name
|
send_str_hashmap.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(collections, into_cow)]
extern crate collections;
use std::collections::HashMap;
use std::borrow::{Cow, IntoCow};
type SendStr = Cow<'static, str>;
pub fn
|
() {
let mut map: HashMap<SendStr, usize> = HashMap::new();
assert!(map.insert("foo".into_cow(), 42).is_none());
assert!(map.insert("foo".to_string().into_cow(), 42).is_some());
assert!(map.insert("foo".into_cow(), 42).is_some());
assert!(map.insert("foo".to_string().into_cow(), 42).is_some());
assert!(map.insert("foo".into_cow(), 43).is_some());
assert!(map.insert("foo".to_string().into_cow(), 44).is_some());
assert!(map.insert("foo".into_cow(), 45).is_some());
assert!(map.insert("foo".to_string().into_cow(), 46).is_some());
let v = 46;
assert_eq!(map.get(&"foo".to_string().into_cow()), Some(&v));
assert_eq!(map.get(&"foo".into_cow()), Some(&v));
let (a, b, c, d) = (50, 51, 52, 53);
assert!(map.insert("abc".into_cow(), a).is_none());
assert!(map.insert("bcd".to_string().into_cow(), b).is_none());
assert!(map.insert("cde".into_cow(), c).is_none());
assert!(map.insert("def".to_string().into_cow(), d).is_none());
assert!(map.insert("abc".into_cow(), a).is_some());
assert!(map.insert("bcd".to_string().into_cow(), b).is_some());
assert!(map.insert("cde".into_cow(), c).is_some());
assert!(map.insert("def".to_string().into_cow(), d).is_some());
assert!(map.insert("abc".to_string().into_cow(), a).is_some());
assert!(map.insert("bcd".into_cow(), b).is_some());
assert!(map.insert("cde".to_string().into_cow(), c).is_some());
assert!(map.insert("def".into_cow(), d).is_some());
assert_eq!(map.get("abc"), Some(&a));
assert_eq!(map.get("bcd"), Some(&b));
assert_eq!(map.get("cde"), Some(&c));
assert_eq!(map.get("def"), Some(&d));
assert_eq!(map.get(&"abc".into_cow()), Some(&a));
assert_eq!(map.get(&"bcd".into_cow()), Some(&b));
assert_eq!(map.get(&"cde".into_cow()), Some(&c));
assert_eq!(map.get(&"def".into_cow()), Some(&d));
}
|
main
|
identifier_name
|
send_str_hashmap.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(collections, into_cow)]
extern crate collections;
use std::collections::HashMap;
use std::borrow::{Cow, IntoCow};
type SendStr = Cow<'static, str>;
|
pub fn main() {
let mut map: HashMap<SendStr, usize> = HashMap::new();
assert!(map.insert("foo".into_cow(), 42).is_none());
assert!(map.insert("foo".to_string().into_cow(), 42).is_some());
assert!(map.insert("foo".into_cow(), 42).is_some());
assert!(map.insert("foo".to_string().into_cow(), 42).is_some());
assert!(map.insert("foo".into_cow(), 43).is_some());
assert!(map.insert("foo".to_string().into_cow(), 44).is_some());
assert!(map.insert("foo".into_cow(), 45).is_some());
assert!(map.insert("foo".to_string().into_cow(), 46).is_some());
let v = 46;
assert_eq!(map.get(&"foo".to_string().into_cow()), Some(&v));
assert_eq!(map.get(&"foo".into_cow()), Some(&v));
let (a, b, c, d) = (50, 51, 52, 53);
assert!(map.insert("abc".into_cow(), a).is_none());
assert!(map.insert("bcd".to_string().into_cow(), b).is_none());
assert!(map.insert("cde".into_cow(), c).is_none());
assert!(map.insert("def".to_string().into_cow(), d).is_none());
assert!(map.insert("abc".into_cow(), a).is_some());
assert!(map.insert("bcd".to_string().into_cow(), b).is_some());
assert!(map.insert("cde".into_cow(), c).is_some());
assert!(map.insert("def".to_string().into_cow(), d).is_some());
assert!(map.insert("abc".to_string().into_cow(), a).is_some());
assert!(map.insert("bcd".into_cow(), b).is_some());
assert!(map.insert("cde".to_string().into_cow(), c).is_some());
assert!(map.insert("def".into_cow(), d).is_some());
assert_eq!(map.get("abc"), Some(&a));
assert_eq!(map.get("bcd"), Some(&b));
assert_eq!(map.get("cde"), Some(&c));
assert_eq!(map.get("def"), Some(&d));
assert_eq!(map.get(&"abc".into_cow()), Some(&a));
assert_eq!(map.get(&"bcd".into_cow()), Some(&b));
assert_eq!(map.get(&"cde".into_cow()), Some(&c));
assert_eq!(map.get(&"def".into_cow()), Some(&d));
}
|
random_line_split
|
|
send_str_hashmap.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(collections, into_cow)]
extern crate collections;
use std::collections::HashMap;
use std::borrow::{Cow, IntoCow};
type SendStr = Cow<'static, str>;
pub fn main()
|
assert!(map.insert("bcd".to_string().into_cow(), b).is_none());
assert!(map.insert("cde".into_cow(), c).is_none());
assert!(map.insert("def".to_string().into_cow(), d).is_none());
assert!(map.insert("abc".into_cow(), a).is_some());
assert!(map.insert("bcd".to_string().into_cow(), b).is_some());
assert!(map.insert("cde".into_cow(), c).is_some());
assert!(map.insert("def".to_string().into_cow(), d).is_some());
assert!(map.insert("abc".to_string().into_cow(), a).is_some());
assert!(map.insert("bcd".into_cow(), b).is_some());
assert!(map.insert("cde".to_string().into_cow(), c).is_some());
assert!(map.insert("def".into_cow(), d).is_some());
assert_eq!(map.get("abc"), Some(&a));
assert_eq!(map.get("bcd"), Some(&b));
assert_eq!(map.get("cde"), Some(&c));
assert_eq!(map.get("def"), Some(&d));
assert_eq!(map.get(&"abc".into_cow()), Some(&a));
assert_eq!(map.get(&"bcd".into_cow()), Some(&b));
assert_eq!(map.get(&"cde".into_cow()), Some(&c));
assert_eq!(map.get(&"def".into_cow()), Some(&d));
}
|
{
let mut map: HashMap<SendStr, usize> = HashMap::new();
assert!(map.insert("foo".into_cow(), 42).is_none());
assert!(map.insert("foo".to_string().into_cow(), 42).is_some());
assert!(map.insert("foo".into_cow(), 42).is_some());
assert!(map.insert("foo".to_string().into_cow(), 42).is_some());
assert!(map.insert("foo".into_cow(), 43).is_some());
assert!(map.insert("foo".to_string().into_cow(), 44).is_some());
assert!(map.insert("foo".into_cow(), 45).is_some());
assert!(map.insert("foo".to_string().into_cow(), 46).is_some());
let v = 46;
assert_eq!(map.get(&"foo".to_string().into_cow()), Some(&v));
assert_eq!(map.get(&"foo".into_cow()), Some(&v));
let (a, b, c, d) = (50, 51, 52, 53);
assert!(map.insert("abc".into_cow(), a).is_none());
|
identifier_body
|
inner-static.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
//
// 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.
// aux-build:inner_static.rs
extern crate inner_static;
pub fn main() {
let a = inner_static::A::<()> { v: () };
let b = inner_static::B::<()> { v: () };
let c = inner_static::test::A::<()> { v: () };
assert_eq!(a.bar(), 2);
assert_eq!(b.bar(), 4);
assert_eq!(c.bar(), 6);
}
|
// http://rust-lang.org/COPYRIGHT.
|
random_line_split
|
inner-static.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.
// aux-build:inner_static.rs
extern crate inner_static;
pub fn
|
() {
let a = inner_static::A::<()> { v: () };
let b = inner_static::B::<()> { v: () };
let c = inner_static::test::A::<()> { v: () };
assert_eq!(a.bar(), 2);
assert_eq!(b.bar(), 4);
assert_eq!(c.bar(), 6);
}
|
main
|
identifier_name
|
inner-static.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.
// aux-build:inner_static.rs
extern crate inner_static;
pub fn main()
|
{
let a = inner_static::A::<()> { v: () };
let b = inner_static::B::<()> { v: () };
let c = inner_static::test::A::<()> { v: () };
assert_eq!(a.bar(), 2);
assert_eq!(b.bar(), 4);
assert_eq!(c.bar(), 6);
}
|
identifier_body
|
|
lib.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.
//! A very simple bit-vector that serves the needs of `primal`.
extern crate hamming;
use std::cmp::{self, Ordering};
use std::fmt;
use std::hash;
use std::iter::repeat;
use std::ops::Index;
const BITS: usize = 64;
static TRUE: bool = true;
static FALSE: bool = false;
/// The bitvector type.
pub struct BitVec {
/// Internal representation of the bit vector
|
nbits: usize
}
impl Index<usize> for BitVec {
type Output = bool;
#[inline]
fn index(&self, i: usize) -> &bool {
if self.get(i).expect("index out of bounds") {
&TRUE
} else {
&FALSE
}
}
}
impl BitVec {
/// An operation might screw up the unused bits in the last block of the
/// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
fn fix_last_block(&mut self) {
let extra_bits = self.len() % BITS;
if extra_bits > 0 {
let mask = (1 << extra_bits) - 1;
let storage_len = self.storage.len();
self.storage[storage_len - 1] &= mask;
}
}
/// Creates an empty `BitVec`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
/// let mut bv = BitVec::new();
/// ```
pub fn new() -> BitVec {
BitVec { storage: Vec::new(), nbits: 0 }
}
pub fn from_u64s(data: Vec<u64>, bits: usize) -> BitVec {
assert!(bits <= data.len() * 64);
let mut ret = BitVec { storage: data, nbits: bits };
ret.fix_last_block();
ret
}
#[inline]
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.storage.as_mut_ptr() as *mut _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(self.storage.as_ptr() as *const _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_u64s(&self) -> &[u64] {
&self.storage
}
/// Count the number of ones for the bits up to but not including
/// the `bit`th bit.
pub fn count_ones_before(&self, bit: usize) -> usize {
assert!(bit <= self.nbits);
let (byte, bit) = (bit / 8, bit % 8);
let mask = (1 << bit) - 1;
let bytes = self.as_bytes();
hamming::weight(&bytes[..byte]) as usize
+ bytes.get(byte).map_or(0, |b| (b & mask).count_ones() as usize)
}
/// Find the index of the `n`th (0-indexed) set bit.
pub fn find_nth_bit(&self, mut n: usize) -> Option<usize> {
n += 1;
let all_bytes = self.as_bytes();
let mut bytes = all_bytes;
while bytes.len() > 240 {
let ix = bytes.len() / 2;
let (first, second) = bytes.split_at(ix);
let count = hamming::weight(first) as usize;
match count.cmp(&n) {
Ordering::Equal | Ordering::Greater => {
bytes = first;
}
Ordering::Less => {
n -= count;
bytes = second;
}
}
}
let mut byte_idx = bytes.as_ptr() as usize - all_bytes.as_ptr() as usize;
let mut b = 0;
for &b_ in bytes {
let count = b_.count_ones() as usize;
if count >= n {
b = b_;
break
}
byte_idx += 1;
n -= count
}
if b == 0 {
None
} else {
// clear the bottom n-1 set bits, so that the lowest one
// is the one we care about
for _ in 1..n {
b = b & (b - 1);
}
assert!(b!= 0);
Some(byte_idx * 8 + b.trailing_zeros() as usize)
}
}
/// Creates a `BitVec` that holds `nbits` elements, setting each element
/// to `bit`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.len(), 10);
/// for x in bv.iter() {
/// assert_eq!(x, false);
/// }
/// ```
pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
let nblocks = nbits.checked_add(BITS - 1).expect("capacity overflow") / BITS;
let mut bit_vec = BitVec {
storage: repeat(if bit {!0 } else { 0 }).take(nblocks).collect(),
nbits: nbits
};
bit_vec.fix_last_block();
bit_vec
}
/// Retrieves the value at index `i`, or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// assert_eq!(bv.get(0), Some(false));
/// assert_eq!(bv.get(1), Some(true));
/// assert_eq!(bv.get(100), None);
///
/// // Can also use array indexing
/// assert_eq!(bv[1], true);
/// ```
#[inline]
pub fn get(&self, i: usize) -> Option<bool> {
if i >= self.nbits {
return None;
}
let w = i / BITS;
let b = i % BITS;
self.storage.get(w).map(|&block|
(block & (1 << b))!= 0
)
}
/// Sets the value of a bit at an index `i`.
///
/// # Panics
///
/// Panics if `i` is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, false);
/// bv.set(3, true);
/// assert_eq!(bv[3], true);
/// ```
#[inline]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
unsafe {
self.set_unchecked(i, x)
}
}
#[inline]
pub unsafe fn set_unchecked(&mut self, i: usize, x: bool) {
//
let w = i / BITS;
let b = i % BITS;
let flag = 1 << b;
let ptr = self.storage.get_unchecked_mut(w);
let val = if x { *ptr | flag } else { *ptr &!flag };
*ptr = val;
}
/// Sets all bits to 1.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// let after = 0b11111111;
///
/// let mut bv = BitVec::from_bytes(&[before]);
/// bv.set_all();
/// assert_eq!(bv, BitVec::from_bytes(&[after]));
/// ```
#[inline]
pub fn set_all(&mut self) {
for w in &mut self.storage { *w =!0; }
self.fix_last_block();
}
/// Returns an iterator over the elements of the vector in order.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
/// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
/// ```
#[inline]
pub fn iter(&self) -> Iter {
Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
}
/// Returns the total number of bits in this vector
#[inline]
pub fn len(&self) -> usize { self.nbits }
/// Returns true if there are no bits in this vector
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears all bits in this vector.
#[inline]
pub fn clear(&mut self) {
for w in &mut self.storage { *w = 0; }
}
}
impl Default for BitVec {
#[inline]
fn default() -> BitVec { BitVec::new() }
}
impl Clone for BitVec {
#[inline]
fn clone(&self) -> BitVec {
BitVec { storage: self.storage.clone(), nbits: self.nbits }
}
#[inline]
fn clone_from(&mut self, source: &BitVec) {
self.nbits = source.nbits;
self.storage.clone_from(&source.storage);
}
}
impl fmt::Debug for BitVec {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self {
try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
}
Ok(())
}
}
impl hash::Hash for BitVec {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.nbits.hash(state);
for elem in self.storage.iter().cloned() {
elem.hash(state);
}
}
}
impl cmp::PartialEq for BitVec {
#[inline]
fn eq(&self, other: &BitVec) -> bool {
if self.nbits!= other.nbits {
return false;
}
self.storage.iter().cloned().zip(other.storage.iter().cloned()).all(|(w1, w2)| w1 == w2)
}
}
impl cmp::Eq for BitVec {}
/// An iterator for `BitVec`.
#[derive(Clone)]
pub struct Iter<'a> {
bit_vec: &'a BitVec,
next_idx: usize,
end_idx: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
let idx = self.next_idx;
self.next_idx += 1;
Some(self.bit_vec[idx])
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.end_idx - self.next_idx;
(rem, Some(rem))
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
#[inline]
fn next_back(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
self.end_idx -= 1;
Some(self.bit_vec[self.end_idx])
} else {
None
}
}
}
impl<'a> ExactSizeIterator for Iter<'a> {}
impl<'a> IntoIterator for &'a BitVec {
type Item = bool;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
#[cfg(test)]
mod tests {
use super::BitVec;
#[test]
fn count_ones_before() {
let len = 10000;
let ones = BitVec::from_elem(len, true);
let zeros = BitVec::from_elem(len, false);
let mut halves = zeros.clone();
for i in 0..len / 2 {
halves.set(i * 2, true);
}
for i in 0..len + 1 {
assert_eq!(ones.count_ones_before(i), i);
assert_eq!(zeros.count_ones_before(i), 0);
assert_eq!(halves.count_ones_before(i), (i + 1) / 2);
}
}
#[test]
fn find_nth_bit() {
let len = 5000;
let ones = BitVec::from_elem(len, true);
let mut halves = BitVec::from_elem(len * 2, false);
for i in 0..len {
halves.set(i * 2, true);
}
for i in 0..len {
assert_eq!(ones.find_nth_bit(i), Some(i));
assert_eq!(halves.find_nth_bit(i), Some(i * 2));
}
assert_eq!(ones.find_nth_bit(len + 1), None);
assert_eq!(halves.find_nth_bit(len + 1), None);
assert_eq!(BitVec::new().find_nth_bit(0), None);
assert_eq!(BitVec::from_elem(len, false).find_nth_bit(0), None);
}
}
|
storage: Vec<u64>,
/// The number of valid bits in the internal representation
|
random_line_split
|
lib.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.
//! A very simple bit-vector that serves the needs of `primal`.
extern crate hamming;
use std::cmp::{self, Ordering};
use std::fmt;
use std::hash;
use std::iter::repeat;
use std::ops::Index;
const BITS: usize = 64;
static TRUE: bool = true;
static FALSE: bool = false;
/// The bitvector type.
pub struct BitVec {
/// Internal representation of the bit vector
storage: Vec<u64>,
/// The number of valid bits in the internal representation
nbits: usize
}
impl Index<usize> for BitVec {
type Output = bool;
#[inline]
fn index(&self, i: usize) -> &bool {
if self.get(i).expect("index out of bounds") {
&TRUE
} else {
&FALSE
}
}
}
impl BitVec {
/// An operation might screw up the unused bits in the last block of the
/// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
fn fix_last_block(&mut self) {
let extra_bits = self.len() % BITS;
if extra_bits > 0 {
let mask = (1 << extra_bits) - 1;
let storage_len = self.storage.len();
self.storage[storage_len - 1] &= mask;
}
}
/// Creates an empty `BitVec`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
/// let mut bv = BitVec::new();
/// ```
pub fn new() -> BitVec {
BitVec { storage: Vec::new(), nbits: 0 }
}
pub fn from_u64s(data: Vec<u64>, bits: usize) -> BitVec {
assert!(bits <= data.len() * 64);
let mut ret = BitVec { storage: data, nbits: bits };
ret.fix_last_block();
ret
}
#[inline]
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.storage.as_mut_ptr() as *mut _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(self.storage.as_ptr() as *const _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_u64s(&self) -> &[u64] {
&self.storage
}
/// Count the number of ones for the bits up to but not including
/// the `bit`th bit.
pub fn count_ones_before(&self, bit: usize) -> usize {
assert!(bit <= self.nbits);
let (byte, bit) = (bit / 8, bit % 8);
let mask = (1 << bit) - 1;
let bytes = self.as_bytes();
hamming::weight(&bytes[..byte]) as usize
+ bytes.get(byte).map_or(0, |b| (b & mask).count_ones() as usize)
}
/// Find the index of the `n`th (0-indexed) set bit.
pub fn find_nth_bit(&self, mut n: usize) -> Option<usize> {
n += 1;
let all_bytes = self.as_bytes();
let mut bytes = all_bytes;
while bytes.len() > 240 {
let ix = bytes.len() / 2;
let (first, second) = bytes.split_at(ix);
let count = hamming::weight(first) as usize;
match count.cmp(&n) {
Ordering::Equal | Ordering::Greater => {
bytes = first;
}
Ordering::Less => {
n -= count;
bytes = second;
}
}
}
let mut byte_idx = bytes.as_ptr() as usize - all_bytes.as_ptr() as usize;
let mut b = 0;
for &b_ in bytes {
let count = b_.count_ones() as usize;
if count >= n {
b = b_;
break
}
byte_idx += 1;
n -= count
}
if b == 0 {
None
} else {
// clear the bottom n-1 set bits, so that the lowest one
// is the one we care about
for _ in 1..n {
b = b & (b - 1);
}
assert!(b!= 0);
Some(byte_idx * 8 + b.trailing_zeros() as usize)
}
}
/// Creates a `BitVec` that holds `nbits` elements, setting each element
/// to `bit`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.len(), 10);
/// for x in bv.iter() {
/// assert_eq!(x, false);
/// }
/// ```
pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
let nblocks = nbits.checked_add(BITS - 1).expect("capacity overflow") / BITS;
let mut bit_vec = BitVec {
storage: repeat(if bit {!0 } else { 0 }).take(nblocks).collect(),
nbits: nbits
};
bit_vec.fix_last_block();
bit_vec
}
/// Retrieves the value at index `i`, or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// assert_eq!(bv.get(0), Some(false));
/// assert_eq!(bv.get(1), Some(true));
/// assert_eq!(bv.get(100), None);
///
/// // Can also use array indexing
/// assert_eq!(bv[1], true);
/// ```
#[inline]
pub fn get(&self, i: usize) -> Option<bool> {
if i >= self.nbits {
return None;
}
let w = i / BITS;
let b = i % BITS;
self.storage.get(w).map(|&block|
(block & (1 << b))!= 0
)
}
/// Sets the value of a bit at an index `i`.
///
/// # Panics
///
/// Panics if `i` is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, false);
/// bv.set(3, true);
/// assert_eq!(bv[3], true);
/// ```
#[inline]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
unsafe {
self.set_unchecked(i, x)
}
}
#[inline]
pub unsafe fn set_unchecked(&mut self, i: usize, x: bool) {
//
let w = i / BITS;
let b = i % BITS;
let flag = 1 << b;
let ptr = self.storage.get_unchecked_mut(w);
let val = if x { *ptr | flag } else { *ptr &!flag };
*ptr = val;
}
/// Sets all bits to 1.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// let after = 0b11111111;
///
/// let mut bv = BitVec::from_bytes(&[before]);
/// bv.set_all();
/// assert_eq!(bv, BitVec::from_bytes(&[after]));
/// ```
#[inline]
pub fn set_all(&mut self) {
for w in &mut self.storage { *w =!0; }
self.fix_last_block();
}
/// Returns an iterator over the elements of the vector in order.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
/// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
/// ```
#[inline]
pub fn iter(&self) -> Iter {
Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
}
/// Returns the total number of bits in this vector
#[inline]
pub fn len(&self) -> usize { self.nbits }
/// Returns true if there are no bits in this vector
#[inline]
pub fn
|
(&self) -> bool { self.len() == 0 }
/// Clears all bits in this vector.
#[inline]
pub fn clear(&mut self) {
for w in &mut self.storage { *w = 0; }
}
}
impl Default for BitVec {
#[inline]
fn default() -> BitVec { BitVec::new() }
}
impl Clone for BitVec {
#[inline]
fn clone(&self) -> BitVec {
BitVec { storage: self.storage.clone(), nbits: self.nbits }
}
#[inline]
fn clone_from(&mut self, source: &BitVec) {
self.nbits = source.nbits;
self.storage.clone_from(&source.storage);
}
}
impl fmt::Debug for BitVec {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self {
try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
}
Ok(())
}
}
impl hash::Hash for BitVec {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.nbits.hash(state);
for elem in self.storage.iter().cloned() {
elem.hash(state);
}
}
}
impl cmp::PartialEq for BitVec {
#[inline]
fn eq(&self, other: &BitVec) -> bool {
if self.nbits!= other.nbits {
return false;
}
self.storage.iter().cloned().zip(other.storage.iter().cloned()).all(|(w1, w2)| w1 == w2)
}
}
impl cmp::Eq for BitVec {}
/// An iterator for `BitVec`.
#[derive(Clone)]
pub struct Iter<'a> {
bit_vec: &'a BitVec,
next_idx: usize,
end_idx: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
let idx = self.next_idx;
self.next_idx += 1;
Some(self.bit_vec[idx])
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.end_idx - self.next_idx;
(rem, Some(rem))
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
#[inline]
fn next_back(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
self.end_idx -= 1;
Some(self.bit_vec[self.end_idx])
} else {
None
}
}
}
impl<'a> ExactSizeIterator for Iter<'a> {}
impl<'a> IntoIterator for &'a BitVec {
type Item = bool;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
#[cfg(test)]
mod tests {
use super::BitVec;
#[test]
fn count_ones_before() {
let len = 10000;
let ones = BitVec::from_elem(len, true);
let zeros = BitVec::from_elem(len, false);
let mut halves = zeros.clone();
for i in 0..len / 2 {
halves.set(i * 2, true);
}
for i in 0..len + 1 {
assert_eq!(ones.count_ones_before(i), i);
assert_eq!(zeros.count_ones_before(i), 0);
assert_eq!(halves.count_ones_before(i), (i + 1) / 2);
}
}
#[test]
fn find_nth_bit() {
let len = 5000;
let ones = BitVec::from_elem(len, true);
let mut halves = BitVec::from_elem(len * 2, false);
for i in 0..len {
halves.set(i * 2, true);
}
for i in 0..len {
assert_eq!(ones.find_nth_bit(i), Some(i));
assert_eq!(halves.find_nth_bit(i), Some(i * 2));
}
assert_eq!(ones.find_nth_bit(len + 1), None);
assert_eq!(halves.find_nth_bit(len + 1), None);
assert_eq!(BitVec::new().find_nth_bit(0), None);
assert_eq!(BitVec::from_elem(len, false).find_nth_bit(0), None);
}
}
|
is_empty
|
identifier_name
|
lib.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.
//! A very simple bit-vector that serves the needs of `primal`.
extern crate hamming;
use std::cmp::{self, Ordering};
use std::fmt;
use std::hash;
use std::iter::repeat;
use std::ops::Index;
const BITS: usize = 64;
static TRUE: bool = true;
static FALSE: bool = false;
/// The bitvector type.
pub struct BitVec {
/// Internal representation of the bit vector
storage: Vec<u64>,
/// The number of valid bits in the internal representation
nbits: usize
}
impl Index<usize> for BitVec {
type Output = bool;
#[inline]
fn index(&self, i: usize) -> &bool {
if self.get(i).expect("index out of bounds") {
&TRUE
} else {
&FALSE
}
}
}
impl BitVec {
/// An operation might screw up the unused bits in the last block of the
/// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
fn fix_last_block(&mut self) {
let extra_bits = self.len() % BITS;
if extra_bits > 0 {
let mask = (1 << extra_bits) - 1;
let storage_len = self.storage.len();
self.storage[storage_len - 1] &= mask;
}
}
/// Creates an empty `BitVec`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
/// let mut bv = BitVec::new();
/// ```
pub fn new() -> BitVec {
BitVec { storage: Vec::new(), nbits: 0 }
}
pub fn from_u64s(data: Vec<u64>, bits: usize) -> BitVec {
assert!(bits <= data.len() * 64);
let mut ret = BitVec { storage: data, nbits: bits };
ret.fix_last_block();
ret
}
#[inline]
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.storage.as_mut_ptr() as *mut _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(self.storage.as_ptr() as *const _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_u64s(&self) -> &[u64] {
&self.storage
}
/// Count the number of ones for the bits up to but not including
/// the `bit`th bit.
pub fn count_ones_before(&self, bit: usize) -> usize {
assert!(bit <= self.nbits);
let (byte, bit) = (bit / 8, bit % 8);
let mask = (1 << bit) - 1;
let bytes = self.as_bytes();
hamming::weight(&bytes[..byte]) as usize
+ bytes.get(byte).map_or(0, |b| (b & mask).count_ones() as usize)
}
/// Find the index of the `n`th (0-indexed) set bit.
pub fn find_nth_bit(&self, mut n: usize) -> Option<usize> {
n += 1;
let all_bytes = self.as_bytes();
let mut bytes = all_bytes;
while bytes.len() > 240 {
let ix = bytes.len() / 2;
let (first, second) = bytes.split_at(ix);
let count = hamming::weight(first) as usize;
match count.cmp(&n) {
Ordering::Equal | Ordering::Greater => {
bytes = first;
}
Ordering::Less => {
n -= count;
bytes = second;
}
}
}
let mut byte_idx = bytes.as_ptr() as usize - all_bytes.as_ptr() as usize;
let mut b = 0;
for &b_ in bytes {
let count = b_.count_ones() as usize;
if count >= n {
b = b_;
break
}
byte_idx += 1;
n -= count
}
if b == 0 {
None
} else {
// clear the bottom n-1 set bits, so that the lowest one
// is the one we care about
for _ in 1..n {
b = b & (b - 1);
}
assert!(b!= 0);
Some(byte_idx * 8 + b.trailing_zeros() as usize)
}
}
/// Creates a `BitVec` that holds `nbits` elements, setting each element
/// to `bit`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.len(), 10);
/// for x in bv.iter() {
/// assert_eq!(x, false);
/// }
/// ```
pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
let nblocks = nbits.checked_add(BITS - 1).expect("capacity overflow") / BITS;
let mut bit_vec = BitVec {
storage: repeat(if bit {!0 } else { 0 }).take(nblocks).collect(),
nbits: nbits
};
bit_vec.fix_last_block();
bit_vec
}
/// Retrieves the value at index `i`, or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// assert_eq!(bv.get(0), Some(false));
/// assert_eq!(bv.get(1), Some(true));
/// assert_eq!(bv.get(100), None);
///
/// // Can also use array indexing
/// assert_eq!(bv[1], true);
/// ```
#[inline]
pub fn get(&self, i: usize) -> Option<bool> {
if i >= self.nbits {
return None;
}
let w = i / BITS;
let b = i % BITS;
self.storage.get(w).map(|&block|
(block & (1 << b))!= 0
)
}
/// Sets the value of a bit at an index `i`.
///
/// # Panics
///
/// Panics if `i` is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, false);
/// bv.set(3, true);
/// assert_eq!(bv[3], true);
/// ```
#[inline]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
unsafe {
self.set_unchecked(i, x)
}
}
#[inline]
pub unsafe fn set_unchecked(&mut self, i: usize, x: bool) {
//
let w = i / BITS;
let b = i % BITS;
let flag = 1 << b;
let ptr = self.storage.get_unchecked_mut(w);
let val = if x { *ptr | flag } else
|
;
*ptr = val;
}
/// Sets all bits to 1.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// let after = 0b11111111;
///
/// let mut bv = BitVec::from_bytes(&[before]);
/// bv.set_all();
/// assert_eq!(bv, BitVec::from_bytes(&[after]));
/// ```
#[inline]
pub fn set_all(&mut self) {
for w in &mut self.storage { *w =!0; }
self.fix_last_block();
}
/// Returns an iterator over the elements of the vector in order.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
/// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
/// ```
#[inline]
pub fn iter(&self) -> Iter {
Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
}
/// Returns the total number of bits in this vector
#[inline]
pub fn len(&self) -> usize { self.nbits }
/// Returns true if there are no bits in this vector
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears all bits in this vector.
#[inline]
pub fn clear(&mut self) {
for w in &mut self.storage { *w = 0; }
}
}
impl Default for BitVec {
#[inline]
fn default() -> BitVec { BitVec::new() }
}
impl Clone for BitVec {
#[inline]
fn clone(&self) -> BitVec {
BitVec { storage: self.storage.clone(), nbits: self.nbits }
}
#[inline]
fn clone_from(&mut self, source: &BitVec) {
self.nbits = source.nbits;
self.storage.clone_from(&source.storage);
}
}
impl fmt::Debug for BitVec {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self {
try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
}
Ok(())
}
}
impl hash::Hash for BitVec {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.nbits.hash(state);
for elem in self.storage.iter().cloned() {
elem.hash(state);
}
}
}
impl cmp::PartialEq for BitVec {
#[inline]
fn eq(&self, other: &BitVec) -> bool {
if self.nbits!= other.nbits {
return false;
}
self.storage.iter().cloned().zip(other.storage.iter().cloned()).all(|(w1, w2)| w1 == w2)
}
}
impl cmp::Eq for BitVec {}
/// An iterator for `BitVec`.
#[derive(Clone)]
pub struct Iter<'a> {
bit_vec: &'a BitVec,
next_idx: usize,
end_idx: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
let idx = self.next_idx;
self.next_idx += 1;
Some(self.bit_vec[idx])
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.end_idx - self.next_idx;
(rem, Some(rem))
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
#[inline]
fn next_back(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
self.end_idx -= 1;
Some(self.bit_vec[self.end_idx])
} else {
None
}
}
}
impl<'a> ExactSizeIterator for Iter<'a> {}
impl<'a> IntoIterator for &'a BitVec {
type Item = bool;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
#[cfg(test)]
mod tests {
use super::BitVec;
#[test]
fn count_ones_before() {
let len = 10000;
let ones = BitVec::from_elem(len, true);
let zeros = BitVec::from_elem(len, false);
let mut halves = zeros.clone();
for i in 0..len / 2 {
halves.set(i * 2, true);
}
for i in 0..len + 1 {
assert_eq!(ones.count_ones_before(i), i);
assert_eq!(zeros.count_ones_before(i), 0);
assert_eq!(halves.count_ones_before(i), (i + 1) / 2);
}
}
#[test]
fn find_nth_bit() {
let len = 5000;
let ones = BitVec::from_elem(len, true);
let mut halves = BitVec::from_elem(len * 2, false);
for i in 0..len {
halves.set(i * 2, true);
}
for i in 0..len {
assert_eq!(ones.find_nth_bit(i), Some(i));
assert_eq!(halves.find_nth_bit(i), Some(i * 2));
}
assert_eq!(ones.find_nth_bit(len + 1), None);
assert_eq!(halves.find_nth_bit(len + 1), None);
assert_eq!(BitVec::new().find_nth_bit(0), None);
assert_eq!(BitVec::from_elem(len, false).find_nth_bit(0), None);
}
}
|
{ *ptr & !flag }
|
conditional_block
|
lib.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.
//! A very simple bit-vector that serves the needs of `primal`.
extern crate hamming;
use std::cmp::{self, Ordering};
use std::fmt;
use std::hash;
use std::iter::repeat;
use std::ops::Index;
const BITS: usize = 64;
static TRUE: bool = true;
static FALSE: bool = false;
/// The bitvector type.
pub struct BitVec {
/// Internal representation of the bit vector
storage: Vec<u64>,
/// The number of valid bits in the internal representation
nbits: usize
}
impl Index<usize> for BitVec {
type Output = bool;
#[inline]
fn index(&self, i: usize) -> &bool {
if self.get(i).expect("index out of bounds") {
&TRUE
} else {
&FALSE
}
}
}
impl BitVec {
/// An operation might screw up the unused bits in the last block of the
/// `BitVec`. As per (3), it's assumed to be all 0s. This method fixes it up.
fn fix_last_block(&mut self) {
let extra_bits = self.len() % BITS;
if extra_bits > 0 {
let mask = (1 << extra_bits) - 1;
let storage_len = self.storage.len();
self.storage[storage_len - 1] &= mask;
}
}
/// Creates an empty `BitVec`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
/// let mut bv = BitVec::new();
/// ```
pub fn new() -> BitVec {
BitVec { storage: Vec::new(), nbits: 0 }
}
pub fn from_u64s(data: Vec<u64>, bits: usize) -> BitVec
|
#[inline]
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.storage.as_mut_ptr() as *mut _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe {
std::slice::from_raw_parts(self.storage.as_ptr() as *const _,
(self.nbits + 7) / 8)
}
}
#[inline]
pub fn as_u64s(&self) -> &[u64] {
&self.storage
}
/// Count the number of ones for the bits up to but not including
/// the `bit`th bit.
pub fn count_ones_before(&self, bit: usize) -> usize {
assert!(bit <= self.nbits);
let (byte, bit) = (bit / 8, bit % 8);
let mask = (1 << bit) - 1;
let bytes = self.as_bytes();
hamming::weight(&bytes[..byte]) as usize
+ bytes.get(byte).map_or(0, |b| (b & mask).count_ones() as usize)
}
/// Find the index of the `n`th (0-indexed) set bit.
pub fn find_nth_bit(&self, mut n: usize) -> Option<usize> {
n += 1;
let all_bytes = self.as_bytes();
let mut bytes = all_bytes;
while bytes.len() > 240 {
let ix = bytes.len() / 2;
let (first, second) = bytes.split_at(ix);
let count = hamming::weight(first) as usize;
match count.cmp(&n) {
Ordering::Equal | Ordering::Greater => {
bytes = first;
}
Ordering::Less => {
n -= count;
bytes = second;
}
}
}
let mut byte_idx = bytes.as_ptr() as usize - all_bytes.as_ptr() as usize;
let mut b = 0;
for &b_ in bytes {
let count = b_.count_ones() as usize;
if count >= n {
b = b_;
break
}
byte_idx += 1;
n -= count
}
if b == 0 {
None
} else {
// clear the bottom n-1 set bits, so that the lowest one
// is the one we care about
for _ in 1..n {
b = b & (b - 1);
}
assert!(b!= 0);
Some(byte_idx * 8 + b.trailing_zeros() as usize)
}
}
/// Creates a `BitVec` that holds `nbits` elements, setting each element
/// to `bit`.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(10, false);
/// assert_eq!(bv.len(), 10);
/// for x in bv.iter() {
/// assert_eq!(x, false);
/// }
/// ```
pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
let nblocks = nbits.checked_add(BITS - 1).expect("capacity overflow") / BITS;
let mut bit_vec = BitVec {
storage: repeat(if bit {!0 } else { 0 }).take(nblocks).collect(),
nbits: nbits
};
bit_vec.fix_last_block();
bit_vec
}
/// Retrieves the value at index `i`, or `None` if the index is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01100000]);
/// assert_eq!(bv.get(0), Some(false));
/// assert_eq!(bv.get(1), Some(true));
/// assert_eq!(bv.get(100), None);
///
/// // Can also use array indexing
/// assert_eq!(bv[1], true);
/// ```
#[inline]
pub fn get(&self, i: usize) -> Option<bool> {
if i >= self.nbits {
return None;
}
let w = i / BITS;
let b = i % BITS;
self.storage.get(w).map(|&block|
(block & (1 << b))!= 0
)
}
/// Sets the value of a bit at an index `i`.
///
/// # Panics
///
/// Panics if `i` is out of bounds.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let mut bv = BitVec::from_elem(5, false);
/// bv.set(3, true);
/// assert_eq!(bv[3], true);
/// ```
#[inline]
pub fn set(&mut self, i: usize, x: bool) {
assert!(i < self.nbits);
unsafe {
self.set_unchecked(i, x)
}
}
#[inline]
pub unsafe fn set_unchecked(&mut self, i: usize, x: bool) {
//
let w = i / BITS;
let b = i % BITS;
let flag = 1 << b;
let ptr = self.storage.get_unchecked_mut(w);
let val = if x { *ptr | flag } else { *ptr &!flag };
*ptr = val;
}
/// Sets all bits to 1.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let before = 0b01100000;
/// let after = 0b11111111;
///
/// let mut bv = BitVec::from_bytes(&[before]);
/// bv.set_all();
/// assert_eq!(bv, BitVec::from_bytes(&[after]));
/// ```
#[inline]
pub fn set_all(&mut self) {
for w in &mut self.storage { *w =!0; }
self.fix_last_block();
}
/// Returns an iterator over the elements of the vector in order.
///
/// # Examples
///
/// ```ignore
/// use std::collections::BitVec;
///
/// let bv = BitVec::from_bytes(&[0b01110100, 0b10010010]);
/// assert_eq!(bv.iter().filter(|x| *x).count(), 7);
/// ```
#[inline]
pub fn iter(&self) -> Iter {
Iter { bit_vec: self, next_idx: 0, end_idx: self.nbits }
}
/// Returns the total number of bits in this vector
#[inline]
pub fn len(&self) -> usize { self.nbits }
/// Returns true if there are no bits in this vector
#[inline]
pub fn is_empty(&self) -> bool { self.len() == 0 }
/// Clears all bits in this vector.
#[inline]
pub fn clear(&mut self) {
for w in &mut self.storage { *w = 0; }
}
}
impl Default for BitVec {
#[inline]
fn default() -> BitVec { BitVec::new() }
}
impl Clone for BitVec {
#[inline]
fn clone(&self) -> BitVec {
BitVec { storage: self.storage.clone(), nbits: self.nbits }
}
#[inline]
fn clone_from(&mut self, source: &BitVec) {
self.nbits = source.nbits;
self.storage.clone_from(&source.storage);
}
}
impl fmt::Debug for BitVec {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for bit in self {
try!(write!(fmt, "{}", if bit { 1 } else { 0 }));
}
Ok(())
}
}
impl hash::Hash for BitVec {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.nbits.hash(state);
for elem in self.storage.iter().cloned() {
elem.hash(state);
}
}
}
impl cmp::PartialEq for BitVec {
#[inline]
fn eq(&self, other: &BitVec) -> bool {
if self.nbits!= other.nbits {
return false;
}
self.storage.iter().cloned().zip(other.storage.iter().cloned()).all(|(w1, w2)| w1 == w2)
}
}
impl cmp::Eq for BitVec {}
/// An iterator for `BitVec`.
#[derive(Clone)]
pub struct Iter<'a> {
bit_vec: &'a BitVec,
next_idx: usize,
end_idx: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = bool;
#[inline]
fn next(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
let idx = self.next_idx;
self.next_idx += 1;
Some(self.bit_vec[idx])
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.end_idx - self.next_idx;
(rem, Some(rem))
}
}
impl<'a> DoubleEndedIterator for Iter<'a> {
#[inline]
fn next_back(&mut self) -> Option<bool> {
if self.next_idx!= self.end_idx {
self.end_idx -= 1;
Some(self.bit_vec[self.end_idx])
} else {
None
}
}
}
impl<'a> ExactSizeIterator for Iter<'a> {}
impl<'a> IntoIterator for &'a BitVec {
type Item = bool;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
#[cfg(test)]
mod tests {
use super::BitVec;
#[test]
fn count_ones_before() {
let len = 10000;
let ones = BitVec::from_elem(len, true);
let zeros = BitVec::from_elem(len, false);
let mut halves = zeros.clone();
for i in 0..len / 2 {
halves.set(i * 2, true);
}
for i in 0..len + 1 {
assert_eq!(ones.count_ones_before(i), i);
assert_eq!(zeros.count_ones_before(i), 0);
assert_eq!(halves.count_ones_before(i), (i + 1) / 2);
}
}
#[test]
fn find_nth_bit() {
let len = 5000;
let ones = BitVec::from_elem(len, true);
let mut halves = BitVec::from_elem(len * 2, false);
for i in 0..len {
halves.set(i * 2, true);
}
for i in 0..len {
assert_eq!(ones.find_nth_bit(i), Some(i));
assert_eq!(halves.find_nth_bit(i), Some(i * 2));
}
assert_eq!(ones.find_nth_bit(len + 1), None);
assert_eq!(halves.find_nth_bit(len + 1), None);
assert_eq!(BitVec::new().find_nth_bit(0), None);
assert_eq!(BitVec::from_elem(len, false).find_nth_bit(0), None);
}
}
|
{
assert!(bits <= data.len() * 64);
let mut ret = BitVec { storage: data, nbits: bits };
ret.fix_last_block();
ret
}
|
identifier_body
|
inherited_table.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %>
${helpers.single_keyword("border-collapse", "separate collapse",
|
${helpers.single_keyword("empty-cells", "show hide",
gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")}
${helpers.single_keyword("caption-side", "top bottom",
extra_gecko_values="right left top-outside bottom-outside",
needs_conversion="True",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")}
<%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True"
spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing">
use app_units::Au;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{AllowQuirks, Length};
pub mod computed_value {
use app_units::Au;
use properties::animated_properties::Animatable;
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T {
pub horizontal: Au,
pub vertical: Au,
}
/// https://drafts.csswg.org/css-transitions/#animtype-simple-list
impl Animatable for T {
#[inline]
fn interpolate(&self, other: &Self, time: f64) -> Result<Self, ()> {
Ok(T {
horizontal: try!(self.horizontal.interpolate(&other.horizontal, time)),
vertical: try!(self.vertical.interpolate(&other.vertical, time)),
})
}
#[inline]
fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
self.compute_squared_distance(other).map(|sd| sd.sqrt())
}
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) +
try!(self.vertical.compute_squared_distance(&other.vertical)))
}
}
}
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
self.horizontal.has_viewport_percentage() ||
self.vertical.as_ref().map_or(false, |v| v.has_viewport_percentage())
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue {
pub horizontal: Length,
pub vertical: Option<Length>,
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
horizontal: Au(0),
vertical: Au(0),
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
try!(self.horizontal.to_css(dest));
if let Some(vertical) = self.vertical.as_ref() {
try!(dest.write_str(" "));
vertical.to_css(dest)?;
}
Ok(())
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
self.vertical.to_css(dest)
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
let horizontal = self.horizontal.to_computed_value(context);
computed_value::T {
horizontal: horizontal,
vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)),
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue {
horizontal: ToComputedValue::from_computed_value(&computed.horizontal),
vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)),
}
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
let mut first = None;
let mut second = None;
match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) {
Err(()) => (),
Ok(length) => {
first = Some(length);
if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) {
second = Some(len);
}
}
}
match (first, second) {
(None, None) => Err(()),
(Some(length), None) => {
Ok(SpecifiedValue {
horizontal: length,
vertical: None,
})
}
(Some(horizontal), Some(vertical)) => {
Ok(SpecifiedValue {
horizontal: horizontal,
vertical: Some(vertical),
})
}
(None, Some(_)) => unreachable!(),
}
}
</%helpers:longhand>
|
gecko_constant_prefix="NS_STYLE_BORDER",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")}
|
random_line_split
|
inherited_table.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %>
${helpers.single_keyword("border-collapse", "separate collapse",
gecko_constant_prefix="NS_STYLE_BORDER",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")}
${helpers.single_keyword("empty-cells", "show hide",
gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")}
${helpers.single_keyword("caption-side", "top bottom",
extra_gecko_values="right left top-outside bottom-outside",
needs_conversion="True",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")}
<%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True"
spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing">
use app_units::Au;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{AllowQuirks, Length};
pub mod computed_value {
use app_units::Au;
use properties::animated_properties::Animatable;
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct
|
{
pub horizontal: Au,
pub vertical: Au,
}
/// https://drafts.csswg.org/css-transitions/#animtype-simple-list
impl Animatable for T {
#[inline]
fn interpolate(&self, other: &Self, time: f64) -> Result<Self, ()> {
Ok(T {
horizontal: try!(self.horizontal.interpolate(&other.horizontal, time)),
vertical: try!(self.vertical.interpolate(&other.vertical, time)),
})
}
#[inline]
fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
self.compute_squared_distance(other).map(|sd| sd.sqrt())
}
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) +
try!(self.vertical.compute_squared_distance(&other.vertical)))
}
}
}
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
self.horizontal.has_viewport_percentage() ||
self.vertical.as_ref().map_or(false, |v| v.has_viewport_percentage())
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue {
pub horizontal: Length,
pub vertical: Option<Length>,
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
horizontal: Au(0),
vertical: Au(0),
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
try!(self.horizontal.to_css(dest));
if let Some(vertical) = self.vertical.as_ref() {
try!(dest.write_str(" "));
vertical.to_css(dest)?;
}
Ok(())
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
self.vertical.to_css(dest)
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
let horizontal = self.horizontal.to_computed_value(context);
computed_value::T {
horizontal: horizontal,
vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)),
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue {
horizontal: ToComputedValue::from_computed_value(&computed.horizontal),
vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)),
}
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
let mut first = None;
let mut second = None;
match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) {
Err(()) => (),
Ok(length) => {
first = Some(length);
if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) {
second = Some(len);
}
}
}
match (first, second) {
(None, None) => Err(()),
(Some(length), None) => {
Ok(SpecifiedValue {
horizontal: length,
vertical: None,
})
}
(Some(horizontal), Some(vertical)) => {
Ok(SpecifiedValue {
horizontal: horizontal,
vertical: Some(vertical),
})
}
(None, Some(_)) => unreachable!(),
}
}
</%helpers:longhand>
|
T
|
identifier_name
|
inherited_table.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True, gecko_name="TableBorder") %>
${helpers.single_keyword("border-collapse", "separate collapse",
gecko_constant_prefix="NS_STYLE_BORDER",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-border-collapse")}
${helpers.single_keyword("empty-cells", "show hide",
gecko_constant_prefix="NS_STYLE_TABLE_EMPTY_CELLS",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-empty-cells")}
${helpers.single_keyword("caption-side", "top bottom",
extra_gecko_values="right left top-outside bottom-outside",
needs_conversion="True",
animation_value_type="none",
spec="https://drafts.csswg.org/css-tables/#propdef-caption-side")}
<%helpers:longhand name="border-spacing" animation_value_type="ComputedValue" boxed="True"
spec="https://drafts.csswg.org/css-tables/#propdef-border-spacing">
use app_units::Au;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{AllowQuirks, Length};
pub mod computed_value {
use app_units::Au;
use properties::animated_properties::Animatable;
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T {
pub horizontal: Au,
pub vertical: Au,
}
/// https://drafts.csswg.org/css-transitions/#animtype-simple-list
impl Animatable for T {
#[inline]
fn interpolate(&self, other: &Self, time: f64) -> Result<Self, ()> {
Ok(T {
horizontal: try!(self.horizontal.interpolate(&other.horizontal, time)),
vertical: try!(self.vertical.interpolate(&other.vertical, time)),
})
}
#[inline]
fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
self.compute_squared_distance(other).map(|sd| sd.sqrt())
}
#[inline]
fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> {
Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) +
try!(self.vertical.compute_squared_distance(&other.vertical)))
}
}
}
impl HasViewportPercentage for SpecifiedValue {
fn has_viewport_percentage(&self) -> bool {
self.horizontal.has_viewport_percentage() ||
self.vertical.as_ref().map_or(false, |v| v.has_viewport_percentage())
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue {
pub horizontal: Length,
pub vertical: Option<Length>,
}
#[inline]
pub fn get_initial_value() -> computed_value::T
|
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
try!(self.horizontal.to_css(dest));
if let Some(vertical) = self.vertical.as_ref() {
try!(dest.write_str(" "));
vertical.to_css(dest)?;
}
Ok(())
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
self.vertical.to_css(dest)
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
let horizontal = self.horizontal.to_computed_value(context);
computed_value::T {
horizontal: horizontal,
vertical: self.vertical.as_ref().map_or(horizontal, |v| v.to_computed_value(context)),
}
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue {
horizontal: ToComputedValue::from_computed_value(&computed.horizontal),
vertical: Some(ToComputedValue::from_computed_value(&computed.vertical)),
}
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
let mut first = None;
let mut second = None;
match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) {
Err(()) => (),
Ok(length) => {
first = Some(length);
if let Ok(len) = input.try(|i| Length::parse_non_negative_quirky(context, i, AllowQuirks::Yes)) {
second = Some(len);
}
}
}
match (first, second) {
(None, None) => Err(()),
(Some(length), None) => {
Ok(SpecifiedValue {
horizontal: length,
vertical: None,
})
}
(Some(horizontal), Some(vertical)) => {
Ok(SpecifiedValue {
horizontal: horizontal,
vertical: Some(vertical),
})
}
(None, Some(_)) => unreachable!(),
}
}
</%helpers:longhand>
|
{
computed_value::T {
horizontal: Au(0),
vertical: Au(0),
}
}
|
identifier_body
|
main.rs
|
// Works under Rust 1.14.0 :)
extern crate rand;
use std::io::prelude::*;
use std::io;
use rand::{thread_rng, Rng};
const MAX_ATTEMPTS:i16 = 5;
fn play(guess:u8, target:u8, remaining_guesses:i16) -> bool
|
fn main() {
println!("
Yo! Welcome to Guess the Number with Rust!
Rust will, like, pick a number between 1 and 100 and, like, you've gotta guess it or whatever.
Oh. And you only get 5 guesses. Bonne chance!
");
let mut rng = thread_rng();
let _number = rng.gen_range::<u8>(1, 100);
let mut _attempt = 1;
// Our game loop
loop {
let position = MAX_ATTEMPTS - _attempt;
if position < 0 {
println!("Ouf. Sorry but you're all out of guesses. You lose =(");
println!("The number you were looking for is {}", _number);
break;
}
// Get input:
let mut input_text = String::new();
print!("Take a guess: ");
io::stdout().flush().ok(); //.expect("Could not flush stdout");
io::stdin().read_line(&mut input_text).unwrap();
match input_text.trim().parse::<u8>().ok() {
Some(i) => if play(i, _number, position) {
break;
} else {
_attempt += 1;
},
None => println!("Enter a number please...")
}
}
}
|
{
if guess == target {
// We won!
println!("Noice! You gone done did good, kid.");
return true;
} else {
if guess < target {
// Go lower
println!("Hmm too low, bro.");
} else if guess > target {
// Go higher
println!("Yo too high, guy.");
}
println!("You have {0} guesses left.
", remaining_guesses);
return false;
}
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.