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 |
---|---|---|---|---|
generic-tuple-style-enum.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:set print union on
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print case1
// gdb-check:$1 = {{RUST$ENUM$DISR = Case1, 0, 31868, 31868, 31868, 31868}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}, {RUST$ENUM$DISR = Case1, 0, 8970181431921507452}}
// gdb-command:print case2
// gdb-check:$2 = {{RUST$ENUM$DISR = Case2, 0, 4369, 4369, 4369, 4369}, {RUST$ENUM$DISR = Case2, 0, 286331153, 286331153}, {RUST$ENUM$DISR = Case2, 0, 1229782938247303441}}
// gdb-command:print case3
// gdb-check:$3 = {{RUST$ENUM$DISR = Case3, 0, 22873, 22873, 22873, 22873}, {RUST$ENUM$DISR = Case3, 0, 1499027801, 1499027801}, {RUST$ENUM$DISR = Case3, 0, 6438275382588823897}}
// gdb-command:print univariant
// gdb-check:$4 = {{-1}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print case1
// lldb-check:[...]$0 = Case1(0, 31868, 31868, 31868, 31868)
// lldb-command:print case2
// lldb-check:[...]$1 = Case2(0, 286331153, 286331153)
// lldb-command:print case3
// lldb-check:[...]$2 = Case3(0, 6438275382588823897)
// lldb-command:print univariant
// lldb-check:[...]$3 = TheOnlyCase(-1)
// NOTE: This is a copy of the non-generic test case. The `Txx` type parameters have to be
// substituted with something of size `xx` bits and the same alignment as an integer type of the
// same size.
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular<T16, T32, T64> {
Case1(T64, T16, T16, T16, T16),
Case2(T64, T32, T32),
Case3(T64, T64)
}
enum Univariant<T64> {
TheOnlyCase(T64)
}
fn main() {
// In order to avoid endianess trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1: Regular<u16, u32, u64> = Case1(0_u64, 31868_u16, 31868_u16, 31868_u16, 31868_u16);
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2: Regular<i16, i32, i64> = Case2(0_i64, 286331153_i32, 286331153_i32);
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3: Regular<i16, i32, i64> = Case3(0_i64, 6438275382588823897_i64);
let univariant = TheOnlyCase(-1_i64);
zzz(); // #break
}
fn
|
() { () }
|
zzz
|
identifier_name
|
compute_squared_distance.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::animate::{AnimationFieldAttrs, AnimationInputAttrs, AnimationVariantAttrs};
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use syn::{DeriveInput, WhereClause};
use synstructure;
pub fn derive(mut input: DeriveInput) -> TokenStream {
let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input);
let no_bound = animation_input_attrs.no_bound.unwrap_or_default();
let mut where_clause = input.generics.where_clause.take();
for param in input.generics.type_params() {
if!no_bound.iter().any(|name| name.is_ident(¶m.ident)) {
cg::add_predicate(
&mut where_clause,
parse_quote!(#param: crate::values::distance::ComputeSquaredDistance),
);
}
}
let (mut match_body, needs_catchall_branch) = {
let s = synstructure::Structure::new(&input);
let needs_catchall_branch = s.variants().len() > 1;
let match_body = s.variants().iter().fold(quote!(), |body, variant| {
let arm = derive_variant_arm(variant, &mut where_clause);
quote! { #body #arm }
});
(match_body, needs_catchall_branch)
};
input.generics.where_clause = where_clause;
if needs_catchall_branch {
// This ideally shouldn't be needed, but see:
// https://github.com/rust-lang/rust/issues/68867
match_body.append_all(quote! { _ => unsafe { debug_unreachable!() } });
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics crate::values::distance::ComputeSquaredDistance for #name #ty_generics #where_clause {
#[allow(unused_variables, unused_imports)]
#[inline]
fn compute_squared_distance(
&self,
other: &Self,
) -> Result<crate::values::distance::SquaredDistance, ()> {
if std::mem::discriminant(self)!= std::mem::discriminant(other) {
return Err(());
}
match (self, other) {
#match_body
}
}
}
}
}
fn derive_variant_arm(
variant: &synstructure::VariantInfo,
mut where_clause: &mut Option<WhereClause>,
) -> TokenStream {
let variant_attrs = cg::parse_variant_attrs_from_ast::<AnimationVariantAttrs>(&variant.ast());
let (this_pattern, this_info) = cg::ref_pattern(&variant, "this");
let (other_pattern, other_info) = cg::ref_pattern(&variant, "other");
if variant_attrs.error {
return quote! {
(&#this_pattern, &#other_pattern) => Err(()),
};
}
let sum = if this_info.is_empty() {
quote! { crate::values::distance::SquaredDistance::from_sqrt(0.) }
} else {
let mut sum = quote!();
sum.append_separated(this_info.iter().zip(&other_info).map(|(this, other)| {
let field_attrs = cg::parse_field_attrs::<DistanceFieldAttrs>(&this.ast());
if field_attrs.field_bound {
let ty = &this.ast().ty;
cg::add_predicate(
&mut where_clause,
parse_quote!(#ty: crate::values::distance::ComputeSquaredDistance),
);
}
let animation_field_attrs =
cg::parse_field_attrs::<AnimationFieldAttrs>(&this.ast());
if animation_field_attrs.constant {
quote! {
{
if #this!= #other {
return Err(());
}
crate::values::distance::SquaredDistance::from_sqrt(0.)
}
}
} else
|
}), quote!(+));
sum
};
return quote! {
(&#this_pattern, &#other_pattern) => Ok(#sum),
};
}
#[derive(Default, FromField)]
#[darling(attributes(distance), default)]
struct DistanceFieldAttrs {
field_bound: bool,
}
|
{
quote! {
crate::values::distance::ComputeSquaredDistance::compute_squared_distance(#this, #other)?
}
}
|
conditional_block
|
compute_squared_distance.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::animate::{AnimationFieldAttrs, AnimationInputAttrs, AnimationVariantAttrs};
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use syn::{DeriveInput, WhereClause};
use synstructure;
pub fn derive(mut input: DeriveInput) -> TokenStream {
let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input);
let no_bound = animation_input_attrs.no_bound.unwrap_or_default();
let mut where_clause = input.generics.where_clause.take();
for param in input.generics.type_params() {
if!no_bound.iter().any(|name| name.is_ident(¶m.ident)) {
cg::add_predicate(
&mut where_clause,
parse_quote!(#param: crate::values::distance::ComputeSquaredDistance),
);
}
}
let (mut match_body, needs_catchall_branch) = {
let s = synstructure::Structure::new(&input);
let needs_catchall_branch = s.variants().len() > 1;
let match_body = s.variants().iter().fold(quote!(), |body, variant| {
let arm = derive_variant_arm(variant, &mut where_clause);
quote! { #body #arm }
});
(match_body, needs_catchall_branch)
};
|
input.generics.where_clause = where_clause;
if needs_catchall_branch {
// This ideally shouldn't be needed, but see:
// https://github.com/rust-lang/rust/issues/68867
match_body.append_all(quote! { _ => unsafe { debug_unreachable!() } });
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics crate::values::distance::ComputeSquaredDistance for #name #ty_generics #where_clause {
#[allow(unused_variables, unused_imports)]
#[inline]
fn compute_squared_distance(
&self,
other: &Self,
) -> Result<crate::values::distance::SquaredDistance, ()> {
if std::mem::discriminant(self)!= std::mem::discriminant(other) {
return Err(());
}
match (self, other) {
#match_body
}
}
}
}
}
fn derive_variant_arm(
variant: &synstructure::VariantInfo,
mut where_clause: &mut Option<WhereClause>,
) -> TokenStream {
let variant_attrs = cg::parse_variant_attrs_from_ast::<AnimationVariantAttrs>(&variant.ast());
let (this_pattern, this_info) = cg::ref_pattern(&variant, "this");
let (other_pattern, other_info) = cg::ref_pattern(&variant, "other");
if variant_attrs.error {
return quote! {
(&#this_pattern, &#other_pattern) => Err(()),
};
}
let sum = if this_info.is_empty() {
quote! { crate::values::distance::SquaredDistance::from_sqrt(0.) }
} else {
let mut sum = quote!();
sum.append_separated(this_info.iter().zip(&other_info).map(|(this, other)| {
let field_attrs = cg::parse_field_attrs::<DistanceFieldAttrs>(&this.ast());
if field_attrs.field_bound {
let ty = &this.ast().ty;
cg::add_predicate(
&mut where_clause,
parse_quote!(#ty: crate::values::distance::ComputeSquaredDistance),
);
}
let animation_field_attrs =
cg::parse_field_attrs::<AnimationFieldAttrs>(&this.ast());
if animation_field_attrs.constant {
quote! {
{
if #this!= #other {
return Err(());
}
crate::values::distance::SquaredDistance::from_sqrt(0.)
}
}
} else {
quote! {
crate::values::distance::ComputeSquaredDistance::compute_squared_distance(#this, #other)?
}
}
}), quote!(+));
sum
};
return quote! {
(&#this_pattern, &#other_pattern) => Ok(#sum),
};
}
#[derive(Default, FromField)]
#[darling(attributes(distance), default)]
struct DistanceFieldAttrs {
field_bound: bool,
}
|
random_line_split
|
|
compute_squared_distance.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::animate::{AnimationFieldAttrs, AnimationInputAttrs, AnimationVariantAttrs};
use derive_common::cg;
use proc_macro2::TokenStream;
use quote::TokenStreamExt;
use syn::{DeriveInput, WhereClause};
use synstructure;
pub fn derive(mut input: DeriveInput) -> TokenStream {
let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input);
let no_bound = animation_input_attrs.no_bound.unwrap_or_default();
let mut where_clause = input.generics.where_clause.take();
for param in input.generics.type_params() {
if!no_bound.iter().any(|name| name.is_ident(¶m.ident)) {
cg::add_predicate(
&mut where_clause,
parse_quote!(#param: crate::values::distance::ComputeSquaredDistance),
);
}
}
let (mut match_body, needs_catchall_branch) = {
let s = synstructure::Structure::new(&input);
let needs_catchall_branch = s.variants().len() > 1;
let match_body = s.variants().iter().fold(quote!(), |body, variant| {
let arm = derive_variant_arm(variant, &mut where_clause);
quote! { #body #arm }
});
(match_body, needs_catchall_branch)
};
input.generics.where_clause = where_clause;
if needs_catchall_branch {
// This ideally shouldn't be needed, but see:
// https://github.com/rust-lang/rust/issues/68867
match_body.append_all(quote! { _ => unsafe { debug_unreachable!() } });
}
let name = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics crate::values::distance::ComputeSquaredDistance for #name #ty_generics #where_clause {
#[allow(unused_variables, unused_imports)]
#[inline]
fn compute_squared_distance(
&self,
other: &Self,
) -> Result<crate::values::distance::SquaredDistance, ()> {
if std::mem::discriminant(self)!= std::mem::discriminant(other) {
return Err(());
}
match (self, other) {
#match_body
}
}
}
}
}
fn
|
(
variant: &synstructure::VariantInfo,
mut where_clause: &mut Option<WhereClause>,
) -> TokenStream {
let variant_attrs = cg::parse_variant_attrs_from_ast::<AnimationVariantAttrs>(&variant.ast());
let (this_pattern, this_info) = cg::ref_pattern(&variant, "this");
let (other_pattern, other_info) = cg::ref_pattern(&variant, "other");
if variant_attrs.error {
return quote! {
(&#this_pattern, &#other_pattern) => Err(()),
};
}
let sum = if this_info.is_empty() {
quote! { crate::values::distance::SquaredDistance::from_sqrt(0.) }
} else {
let mut sum = quote!();
sum.append_separated(this_info.iter().zip(&other_info).map(|(this, other)| {
let field_attrs = cg::parse_field_attrs::<DistanceFieldAttrs>(&this.ast());
if field_attrs.field_bound {
let ty = &this.ast().ty;
cg::add_predicate(
&mut where_clause,
parse_quote!(#ty: crate::values::distance::ComputeSquaredDistance),
);
}
let animation_field_attrs =
cg::parse_field_attrs::<AnimationFieldAttrs>(&this.ast());
if animation_field_attrs.constant {
quote! {
{
if #this!= #other {
return Err(());
}
crate::values::distance::SquaredDistance::from_sqrt(0.)
}
}
} else {
quote! {
crate::values::distance::ComputeSquaredDistance::compute_squared_distance(#this, #other)?
}
}
}), quote!(+));
sum
};
return quote! {
(&#this_pattern, &#other_pattern) => Ok(#sum),
};
}
#[derive(Default, FromField)]
#[darling(attributes(distance), default)]
struct DistanceFieldAttrs {
field_bound: bool,
}
|
derive_variant_arm
|
identifier_name
|
ipv4.rs
|
use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct Ipv4Header {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
pub proto: u8,
pub checksum: Checksum,
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
}
pub struct Ipv4 {
pub header: Ipv4Header,
pub options: Vec<u8>,
pub data: Vec<u8>,
|
impl FromBytes for Ipv4 {
fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
if bytes.len() >= mem::size_of::<Ipv4Header>() {
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
return Some(Ipv4 {
header: header,
options: bytes.get_slice(Some(mem::size_of::<Ipv4Header>()), Some(header_len))
.to_vec(),
data: bytes.get_slice(Some(header_len), None).to_vec(),
});
}
}
None
}
}
impl ToBytes for Ipv4 {
fn to_bytes(&self) -> Vec<u8> {
unsafe {
let header_ptr: *const Ipv4Header = &self.header;
let mut ret = Vec::<u8>::from(slice::from_raw_parts(header_ptr as *const u8,
mem::size_of::<Ipv4Header>()));
ret.push_all(&self.options);
ret.push_all(&self.data);
ret
}
}
}
|
}
|
random_line_split
|
ipv4.rs
|
use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct Ipv4Header {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
pub proto: u8,
pub checksum: Checksum,
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
}
pub struct Ipv4 {
pub header: Ipv4Header,
pub options: Vec<u8>,
pub data: Vec<u8>,
}
impl FromBytes for Ipv4 {
fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
if bytes.len() >= mem::size_of::<Ipv4Header>()
|
None
}
}
impl ToBytes for Ipv4 {
fn to_bytes(&self) -> Vec<u8> {
unsafe {
let header_ptr: *const Ipv4Header = &self.header;
let mut ret = Vec::<u8>::from(slice::from_raw_parts(header_ptr as *const u8,
mem::size_of::<Ipv4Header>()));
ret.push_all(&self.options);
ret.push_all(&self.data);
ret
}
}
}
|
{
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
return Some(Ipv4 {
header: header,
options: bytes.get_slice(Some(mem::size_of::<Ipv4Header>()), Some(header_len))
.to_vec(),
data: bytes.get_slice(Some(header_len), None).to_vec(),
});
}
}
|
conditional_block
|
ipv4.rs
|
use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct
|
{
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
pub proto: u8,
pub checksum: Checksum,
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
}
pub struct Ipv4 {
pub header: Ipv4Header,
pub options: Vec<u8>,
pub data: Vec<u8>,
}
impl FromBytes for Ipv4 {
fn from_bytes(bytes: Vec<u8>) -> Option<Self> {
if bytes.len() >= mem::size_of::<Ipv4Header>() {
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
return Some(Ipv4 {
header: header,
options: bytes.get_slice(Some(mem::size_of::<Ipv4Header>()), Some(header_len))
.to_vec(),
data: bytes.get_slice(Some(header_len), None).to_vec(),
});
}
}
None
}
}
impl ToBytes for Ipv4 {
fn to_bytes(&self) -> Vec<u8> {
unsafe {
let header_ptr: *const Ipv4Header = &self.header;
let mut ret = Vec::<u8>::from(slice::from_raw_parts(header_ptr as *const u8,
mem::size_of::<Ipv4Header>()));
ret.push_all(&self.options);
ret.push_all(&self.data);
ret
}
}
}
|
Ipv4Header
|
identifier_name
|
ipv4.rs
|
use common::get_slice::GetSlice;
use collections::slice;
use collections::vec::Vec;
use core::mem;
use network::common::*;
#[derive(Copy, Clone)]
#[repr(packed)]
pub struct Ipv4Header {
pub ver_hlen: u8,
pub services: u8,
pub len: n16,
pub id: n16,
pub flags_fragment: n16,
pub ttl: u8,
pub proto: u8,
pub checksum: Checksum,
pub src: Ipv4Addr,
pub dst: Ipv4Addr,
}
pub struct Ipv4 {
pub header: Ipv4Header,
pub options: Vec<u8>,
pub data: Vec<u8>,
}
impl FromBytes for Ipv4 {
fn from_bytes(bytes: Vec<u8>) -> Option<Self>
|
}
impl ToBytes for Ipv4 {
fn to_bytes(&self) -> Vec<u8> {
unsafe {
let header_ptr: *const Ipv4Header = &self.header;
let mut ret = Vec::<u8>::from(slice::from_raw_parts(header_ptr as *const u8,
mem::size_of::<Ipv4Header>()));
ret.push_all(&self.options);
ret.push_all(&self.data);
ret
}
}
}
|
{
if bytes.len() >= mem::size_of::<Ipv4Header>() {
unsafe {
let header = *(bytes.as_ptr() as *const Ipv4Header);
let header_len = ((header.ver_hlen & 0xF) << 2) as usize;
return Some(Ipv4 {
header: header,
options: bytes.get_slice(Some(mem::size_of::<Ipv4Header>()), Some(header_len))
.to_vec(),
data: bytes.get_slice(Some(header_len), None).to_vec(),
});
}
}
None
}
|
identifier_body
|
text.rs
|
// The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use std::collections::HashMap;
use common::{insert_attribs, insert_transform};
use transform::Transform;
use SVGEntity;
#[deriving(Show, PartialEq, Clone)]
pub struct
|
{
pub x: i32,
pub y: i32,
pub text: String,
pub attribs: HashMap<String, String>,
pub transform: Option<Transform>
}
impl SVGEntity for Text {
fn gen_output(&self) -> String {
let mut o = String::new();
o.push_str(format!("<text x=\"{}\" y=\"{}\"",
self.x, self.y).as_slice());
o = insert_attribs(insert_transform(o, &self.transform), &self.attribs);
o.push_str(format!(" >{}</text>", self.text).as_slice());
o
}
}
|
Text
|
identifier_name
|
text.rs
|
// The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
use std::collections::HashMap;
use common::{insert_attribs, insert_transform};
use transform::Transform;
use SVGEntity;
#[deriving(Show, PartialEq, Clone)]
pub struct Text {
pub x: i32,
pub y: i32,
pub text: String,
pub attribs: HashMap<String, String>,
pub transform: Option<Transform>
}
impl SVGEntity for Text {
fn gen_output(&self) -> String {
let mut o = String::new();
o.push_str(format!("<text x=\"{}\" y=\"{}\"",
self.x, self.y).as_slice());
o = insert_attribs(insert_transform(o, &self.transform), &self.attribs);
o.push_str(format!(" >{}</text>", self.text).as_slice());
|
}
|
o
}
|
random_line_split
|
du.rs
|
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum
|
{
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
pub struct Entry(pub PathBuf, pub EntryData);
impl Entry {
pub fn size(&self) -> u64 {
let Entry(_, ref data) = *self;
match data {
&EntryData::File{size} => size,
&EntryData::Directory{size,..} => size,
_ => 0
}
}
}
pub fn process_entry(name: &Path, xfs: bool, dev: Option<u64>) -> Entry {
let m = symlink_metadata(name);
let name = PathBuf::from(name);
if let Err(err) = m {
return Entry(name, EntryData::Error(err));
}
let m = m.unwrap();
let mdev = m.dev();
let dev = dev.unwrap_or(if xfs { mdev } else { 0 });
if xfs && mdev!= dev {
return Entry(name, EntryData::OtherFs);
}
if m.is_file() {
return Entry(name, EntryData::File { size: m.len() });
} else if m.is_dir() {
let cwd = env::current_dir().unwrap();
if let Err(err) = env::set_current_dir(&name) {
return Entry(name, EntryData::Error(err));
}
let dir_list = read_dir(".");
if let Err(err) = dir_list {
env::set_current_dir(&cwd).unwrap();
return Entry(name, EntryData::Error(err));
}
let mut v: Vec<Entry> = vec![];
for entry in dir_list.unwrap() {
let entry=entry.unwrap();
let subentry = process_entry(entry.file_name().as_ref(),
xfs,
Some(dev));
v.push(subentry);
}
assert!(env::set_current_dir(cwd).is_ok());
let total_size = v.iter().map(|x| x.size()).sum();
v.sort_by(|a,b| b.size().cmp(&a.size()));
return Entry(name, EntryData::Directory {
size: total_size,
children: v });
} else {
return Entry(name, EntryData::Other);
}
}
|
EntryData
|
identifier_name
|
du.rs
|
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum EntryData {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
pub struct Entry(pub PathBuf, pub EntryData);
impl Entry {
pub fn size(&self) -> u64 {
let Entry(_, ref data) = *self;
match data {
&EntryData::File{size} => size,
&EntryData::Directory{size,..} => size,
_ => 0
}
}
}
pub fn process_entry(name: &Path, xfs: bool, dev: Option<u64>) -> Entry
|
if m.is_file() {
return Entry(name, EntryData::File { size: m.len() });
} else if m.is_dir() {
let cwd = env::current_dir().unwrap();
if let Err(err) = env::set_current_dir(&name) {
return Entry(name, EntryData::Error(err));
}
let dir_list = read_dir(".");
if let Err(err) = dir_list {
env::set_current_dir(&cwd).unwrap();
return Entry(name, EntryData::Error(err));
}
let mut v: Vec<Entry> = vec![];
for entry in dir_list.unwrap() {
let entry=entry.unwrap();
let subentry = process_entry(entry.file_name().as_ref(),
xfs,
Some(dev));
v.push(subentry);
}
assert!(env::set_current_dir(cwd).is_ok());
let total_size = v.iter().map(|x| x.size()).sum();
v.sort_by(|a,b| b.size().cmp(&a.size()));
return Entry(name, EntryData::Directory {
size: total_size,
children: v });
} else {
return Entry(name, EntryData::Other);
}
}
|
{
let m = symlink_metadata(name);
let name = PathBuf::from(name);
if let Err(err) = m {
return Entry(name, EntryData::Error(err));
}
let m = m.unwrap();
let mdev = m.dev();
let dev = dev.unwrap_or(if xfs { mdev } else { 0 });
if xfs && mdev != dev {
return Entry(name, EntryData::OtherFs);
}
|
identifier_body
|
du.rs
|
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum EntryData {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
pub struct Entry(pub PathBuf, pub EntryData);
|
match data {
&EntryData::File{size} => size,
&EntryData::Directory{size,..} => size,
_ => 0
}
}
}
pub fn process_entry(name: &Path, xfs: bool, dev: Option<u64>) -> Entry {
let m = symlink_metadata(name);
let name = PathBuf::from(name);
if let Err(err) = m {
return Entry(name, EntryData::Error(err));
}
let m = m.unwrap();
let mdev = m.dev();
let dev = dev.unwrap_or(if xfs { mdev } else { 0 });
if xfs && mdev!= dev {
return Entry(name, EntryData::OtherFs);
}
if m.is_file() {
return Entry(name, EntryData::File { size: m.len() });
} else if m.is_dir() {
let cwd = env::current_dir().unwrap();
if let Err(err) = env::set_current_dir(&name) {
return Entry(name, EntryData::Error(err));
}
let dir_list = read_dir(".");
if let Err(err) = dir_list {
env::set_current_dir(&cwd).unwrap();
return Entry(name, EntryData::Error(err));
}
let mut v: Vec<Entry> = vec![];
for entry in dir_list.unwrap() {
let entry=entry.unwrap();
let subentry = process_entry(entry.file_name().as_ref(),
xfs,
Some(dev));
v.push(subentry);
}
assert!(env::set_current_dir(cwd).is_ok());
let total_size = v.iter().map(|x| x.size()).sum();
v.sort_by(|a,b| b.size().cmp(&a.size()));
return Entry(name, EntryData::Directory {
size: total_size,
children: v });
} else {
return Entry(name, EntryData::Other);
}
}
|
impl Entry {
pub fn size(&self) -> u64 {
let Entry(_, ref data) = *self;
|
random_line_split
|
du.rs
|
use std::fs::{read_dir, symlink_metadata};
use std::path::{PathBuf, Path};
use std::io;
use std::env;
use std::os::unix::fs::MetadataExt;
#[derive(Debug)]
pub enum EntryData {
File { size: u64 },
Directory { size: u64, children: Vec<Entry> },
OtherFs,
Error(io::Error),
Other,
}
#[derive(Debug)]
pub struct Entry(pub PathBuf, pub EntryData);
impl Entry {
pub fn size(&self) -> u64 {
let Entry(_, ref data) = *self;
match data {
&EntryData::File{size} => size,
&EntryData::Directory{size,..} => size,
_ => 0
}
}
}
pub fn process_entry(name: &Path, xfs: bool, dev: Option<u64>) -> Entry {
let m = symlink_metadata(name);
let name = PathBuf::from(name);
if let Err(err) = m {
return Entry(name, EntryData::Error(err));
}
let m = m.unwrap();
let mdev = m.dev();
let dev = dev.unwrap_or(if xfs { mdev } else { 0 });
if xfs && mdev!= dev {
return Entry(name, EntryData::OtherFs);
}
if m.is_file() {
return Entry(name, EntryData::File { size: m.len() });
} else if m.is_dir() {
let cwd = env::current_dir().unwrap();
if let Err(err) = env::set_current_dir(&name) {
return Entry(name, EntryData::Error(err));
}
let dir_list = read_dir(".");
if let Err(err) = dir_list {
env::set_current_dir(&cwd).unwrap();
return Entry(name, EntryData::Error(err));
}
let mut v: Vec<Entry> = vec![];
for entry in dir_list.unwrap() {
let entry=entry.unwrap();
let subentry = process_entry(entry.file_name().as_ref(),
xfs,
Some(dev));
v.push(subentry);
}
assert!(env::set_current_dir(cwd).is_ok());
let total_size = v.iter().map(|x| x.size()).sum();
v.sort_by(|a,b| b.size().cmp(&a.size()));
return Entry(name, EntryData::Directory {
size: total_size,
children: v });
} else
|
}
|
{
return Entry(name, EntryData::Other);
}
|
conditional_block
|
lib.rs
|
#![allow(unknown_lints)] // Allow clippy lints.
extern crate alga;
extern crate arrayvec;
extern crate decorum;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
#[macro_use]
extern crate lazy_static;
extern crate nalgebra;
extern crate num;
extern crate plexus;
extern crate rand;
extern crate winit;
pub mod clamp;
pub mod cube;
pub mod event;
pub mod framework;
pub mod input;
pub mod math;
pub mod render;
pub mod resource;
pub trait BoolExt: Sized {
fn into_some<T>(self, some: T) -> Option<T>;
}
impl BoolExt for bool {
fn into_some<T>(self, some: T) -> Option<T> {
if self {
Some(some)
}
else {
None
}
}
}
pub trait OptionExt<T> {
fn and_if<F>(self, f: F) -> Self
where
F: Fn(&T) -> bool;
}
impl<T> OptionExt<T> for Option<T> {
fn
|
<F>(mut self, f: F) -> Self
where
F: Fn(&T) -> bool,
{
match self.take() {
Some(value) => if f(&value) {
Some(value)
}
else {
None
},
_ => None,
}
}
}
|
and_if
|
identifier_name
|
lib.rs
|
#![allow(unknown_lints)] // Allow clippy lints.
extern crate alga;
extern crate arrayvec;
extern crate decorum;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
#[macro_use]
extern crate lazy_static;
extern crate nalgebra;
extern crate num;
extern crate plexus;
extern crate rand;
extern crate winit;
pub mod clamp;
pub mod cube;
pub mod event;
pub mod framework;
pub mod input;
pub mod math;
pub mod render;
pub mod resource;
pub trait BoolExt: Sized {
fn into_some<T>(self, some: T) -> Option<T>;
}
impl BoolExt for bool {
fn into_some<T>(self, some: T) -> Option<T> {
if self {
Some(some)
}
else {
None
}
}
}
pub trait OptionExt<T> {
fn and_if<F>(self, f: F) -> Self
where
F: Fn(&T) -> bool;
}
impl<T> OptionExt<T> for Option<T> {
|
Some(value) => if f(&value) {
Some(value)
}
else {
None
},
_ => None,
}
}
}
|
fn and_if<F>(mut self, f: F) -> Self
where
F: Fn(&T) -> bool,
{
match self.take() {
|
random_line_split
|
lib.rs
|
#![allow(unknown_lints)] // Allow clippy lints.
extern crate alga;
extern crate arrayvec;
extern crate decorum;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate image;
#[macro_use]
extern crate lazy_static;
extern crate nalgebra;
extern crate num;
extern crate plexus;
extern crate rand;
extern crate winit;
pub mod clamp;
pub mod cube;
pub mod event;
pub mod framework;
pub mod input;
pub mod math;
pub mod render;
pub mod resource;
pub trait BoolExt: Sized {
fn into_some<T>(self, some: T) -> Option<T>;
}
impl BoolExt for bool {
fn into_some<T>(self, some: T) -> Option<T>
|
}
pub trait OptionExt<T> {
fn and_if<F>(self, f: F) -> Self
where
F: Fn(&T) -> bool;
}
impl<T> OptionExt<T> for Option<T> {
fn and_if<F>(mut self, f: F) -> Self
where
F: Fn(&T) -> bool,
{
match self.take() {
Some(value) => if f(&value) {
Some(value)
}
else {
None
},
_ => None,
}
}
}
|
{
if self {
Some(some)
}
else {
None
}
}
|
identifier_body
|
reentrant.rs
|
//! Module to handle reentrant/recursion limits while deserializing.
use std::cell::Cell;
use std::rc::Rc;
|
/// not do any synchronization -- it is intended purely for single-threaded use.
pub struct ReentrantLimit(Rc<Cell<usize>>);
impl ReentrantLimit {
/// Create a new reentrant limit.
pub fn new(limit: usize) -> Self {
ReentrantLimit(Rc::new(Cell::new(limit)))
}
/// Try to decrease the limit by 1. Return an RAII guard that when freed
/// will increase the limit by 1.
pub fn acquire<S: Into<String>>(&mut self, kind: S) -> Result<ReentrantGuard> {
if self.0.get() == 0 {
bail!(ErrorKind::DeRecursionLimitExceeded(kind.into()));
}
self.0.set(self.0.get() - 1);
Ok(ReentrantGuard(self.0.clone()))
}
}
/// RAII guard for reentrant limits.
pub struct ReentrantGuard(Rc<Cell<usize>>);
impl Drop for ReentrantGuard {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
|
use crate::errors::*;
/// Sets a limit on the amount of recursion during deserialization. This does
|
random_line_split
|
reentrant.rs
|
//! Module to handle reentrant/recursion limits while deserializing.
use std::cell::Cell;
use std::rc::Rc;
use crate::errors::*;
/// Sets a limit on the amount of recursion during deserialization. This does
/// not do any synchronization -- it is intended purely for single-threaded use.
pub struct ReentrantLimit(Rc<Cell<usize>>);
impl ReentrantLimit {
/// Create a new reentrant limit.
pub fn
|
(limit: usize) -> Self {
ReentrantLimit(Rc::new(Cell::new(limit)))
}
/// Try to decrease the limit by 1. Return an RAII guard that when freed
/// will increase the limit by 1.
pub fn acquire<S: Into<String>>(&mut self, kind: S) -> Result<ReentrantGuard> {
if self.0.get() == 0 {
bail!(ErrorKind::DeRecursionLimitExceeded(kind.into()));
}
self.0.set(self.0.get() - 1);
Ok(ReentrantGuard(self.0.clone()))
}
}
/// RAII guard for reentrant limits.
pub struct ReentrantGuard(Rc<Cell<usize>>);
impl Drop for ReentrantGuard {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
|
new
|
identifier_name
|
reentrant.rs
|
//! Module to handle reentrant/recursion limits while deserializing.
use std::cell::Cell;
use std::rc::Rc;
use crate::errors::*;
/// Sets a limit on the amount of recursion during deserialization. This does
/// not do any synchronization -- it is intended purely for single-threaded use.
pub struct ReentrantLimit(Rc<Cell<usize>>);
impl ReentrantLimit {
/// Create a new reentrant limit.
pub fn new(limit: usize) -> Self {
ReentrantLimit(Rc::new(Cell::new(limit)))
}
/// Try to decrease the limit by 1. Return an RAII guard that when freed
/// will increase the limit by 1.
pub fn acquire<S: Into<String>>(&mut self, kind: S) -> Result<ReentrantGuard> {
if self.0.get() == 0
|
self.0.set(self.0.get() - 1);
Ok(ReentrantGuard(self.0.clone()))
}
}
/// RAII guard for reentrant limits.
pub struct ReentrantGuard(Rc<Cell<usize>>);
impl Drop for ReentrantGuard {
fn drop(&mut self) {
self.0.set(self.0.get() + 1);
}
}
|
{
bail!(ErrorKind::DeRecursionLimitExceeded(kind.into()));
}
|
conditional_block
|
method-on-generic-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:rbreak zzz
// gdb-command:run
// STACK BY REF
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$1 = {x = {8888, -8888}}
// gdb-command:print arg1
// gdb-check:$2 = -1
// gdb-command:print arg2
// gdb-check:$3 = -2
// gdb-command:continue
// STACK BY VAL
// gdb-command:finish
// gdb-command:print self
// gdb-check:$4 = {x = {8888, -8888}}
// gdb-command:print arg1
// gdb-check:$5 = -3
// gdb-command:print arg2
// gdb-check:$6 = -4
// gdb-command:continue
// OWNED BY REF
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$7 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$8 = -5
// gdb-command:print arg2
// gdb-check:$9 = -6
// gdb-command:continue
// OWNED BY VAL
// gdb-command:finish
// gdb-command:print self
// gdb-check:$10 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$11 = -7
// gdb-command:print arg2
// gdb-check:$12 = -8
// gdb-command:continue
// OWNED MOVED
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$13 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$14 = -9
// gdb-command:print arg2
// gdb-check:$15 = -10
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// STACK BY REF
// lldb-command:print *self
// lldb-check:[...]$0 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$1 = -1
// lldb-command:print arg2
// lldb-check:[...]$2 = -2
// lldb-command:continue
// STACK BY VAL
// lldb-command:print self
// lldb-check:[...]$3 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$4 = -3
// lldb-command:print arg2
// lldb-check:[...]$5 = -4
// lldb-command:continue
// OWNED BY REF
// lldb-command:print *self
// lldb-check:[...]$6 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$7 = -5
// lldb-command:print arg2
// lldb-check:[...]$8 = -6
// lldb-command:continue
// OWNED BY VAL
// lldb-command:print self
// lldb-check:[...]$9 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$10 = -7
// lldb-command:print arg2
// lldb-check:[...]$11 = -8
// lldb-command:continue
// OWNED MOVED
// lldb-command:print *self
// lldb-check:[...]$12 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$13 = -9
// lldb-command:print arg2
// lldb-check:[...]$14 = -10
// lldb-command:continue
struct Struct<T> {
x: T
}
impl<T> Struct<T> {
fn self_by_ref(&self, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
fn self_by_val(self, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
fn self_owned(self: Box<Struct<T>>, arg1: int, arg2: int) -> int
|
}
fn main() {
let stack = Struct { x: (8888_u32, -8888_i32) };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz() {()}
|
{
zzz(); // #break
arg1 + arg2
}
|
identifier_body
|
method-on-generic-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:rbreak zzz
// gdb-command:run
// STACK BY REF
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$1 = {x = {8888, -8888}}
// gdb-command:print arg1
// gdb-check:$2 = -1
// gdb-command:print arg2
// gdb-check:$3 = -2
// gdb-command:continue
// STACK BY VAL
// gdb-command:finish
// gdb-command:print self
// gdb-check:$4 = {x = {8888, -8888}}
// gdb-command:print arg1
// gdb-check:$5 = -3
// gdb-command:print arg2
// gdb-check:$6 = -4
// gdb-command:continue
// OWNED BY REF
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$7 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$8 = -5
// gdb-command:print arg2
// gdb-check:$9 = -6
// gdb-command:continue
// OWNED BY VAL
// gdb-command:finish
// gdb-command:print self
// gdb-check:$10 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$11 = -7
// gdb-command:print arg2
// gdb-check:$12 = -8
// gdb-command:continue
// OWNED MOVED
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$13 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$14 = -9
// gdb-command:print arg2
// gdb-check:$15 = -10
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// STACK BY REF
// lldb-command:print *self
// lldb-check:[...]$0 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$1 = -1
// lldb-command:print arg2
// lldb-check:[...]$2 = -2
// lldb-command:continue
// STACK BY VAL
// lldb-command:print self
// lldb-check:[...]$3 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$4 = -3
// lldb-command:print arg2
// lldb-check:[...]$5 = -4
// lldb-command:continue
// OWNED BY REF
// lldb-command:print *self
// lldb-check:[...]$6 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$7 = -5
// lldb-command:print arg2
// lldb-check:[...]$8 = -6
// lldb-command:continue
// OWNED BY VAL
// lldb-command:print self
// lldb-check:[...]$9 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$10 = -7
// lldb-command:print arg2
// lldb-check:[...]$11 = -8
// lldb-command:continue
// OWNED MOVED
// lldb-command:print *self
// lldb-check:[...]$12 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$13 = -9
// lldb-command:print arg2
// lldb-check:[...]$14 = -10
// lldb-command:continue
struct Struct<T> {
x: T
}
impl<T> Struct<T> {
fn self_by_ref(&self, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
fn self_by_val(self, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
fn
|
(self: Box<Struct<T>>, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
}
fn main() {
let stack = Struct { x: (8888_u32, -8888_i32) };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz() {()}
|
self_owned
|
identifier_name
|
method-on-generic-struct.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:rbreak zzz
// gdb-command:run
// STACK BY REF
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$1 = {x = {8888, -8888}}
// gdb-command:print arg1
// gdb-check:$2 = -1
// gdb-command:print arg2
// gdb-check:$3 = -2
// gdb-command:continue
// STACK BY VAL
// gdb-command:finish
// gdb-command:print self
// gdb-check:$4 = {x = {8888, -8888}}
// gdb-command:print arg1
// gdb-check:$5 = -3
// gdb-command:print arg2
// gdb-check:$6 = -4
// gdb-command:continue
// OWNED BY REF
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$7 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$8 = -5
// gdb-command:print arg2
// gdb-check:$9 = -6
// gdb-command:continue
// OWNED BY VAL
// gdb-command:finish
// gdb-command:print self
// gdb-check:$10 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$11 = -7
// gdb-command:print arg2
// gdb-check:$12 = -8
// gdb-command:continue
// OWNED MOVED
// gdb-command:finish
// gdb-command:print *self
// gdb-check:$13 = {x = 1234.5}
// gdb-command:print arg1
// gdb-check:$14 = -9
// gdb-command:print arg2
// gdb-check:$15 = -10
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// STACK BY REF
// lldb-command:print *self
// lldb-check:[...]$0 = Struct<(u32, i32)> { x: (8888, -8888) }
|
// lldb-command:continue
// STACK BY VAL
// lldb-command:print self
// lldb-check:[...]$3 = Struct<(u32, i32)> { x: (8888, -8888) }
// lldb-command:print arg1
// lldb-check:[...]$4 = -3
// lldb-command:print arg2
// lldb-check:[...]$5 = -4
// lldb-command:continue
// OWNED BY REF
// lldb-command:print *self
// lldb-check:[...]$6 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$7 = -5
// lldb-command:print arg2
// lldb-check:[...]$8 = -6
// lldb-command:continue
// OWNED BY VAL
// lldb-command:print self
// lldb-check:[...]$9 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$10 = -7
// lldb-command:print arg2
// lldb-check:[...]$11 = -8
// lldb-command:continue
// OWNED MOVED
// lldb-command:print *self
// lldb-check:[...]$12 = Struct<f64> { x: 1234.5 }
// lldb-command:print arg1
// lldb-check:[...]$13 = -9
// lldb-command:print arg2
// lldb-check:[...]$14 = -10
// lldb-command:continue
struct Struct<T> {
x: T
}
impl<T> Struct<T> {
fn self_by_ref(&self, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
fn self_by_val(self, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
fn self_owned(self: Box<Struct<T>>, arg1: int, arg2: int) -> int {
zzz(); // #break
arg1 + arg2
}
}
fn main() {
let stack = Struct { x: (8888_u32, -8888_i32) };
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned = box Struct { x: 1234.5f64 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz() {()}
|
// lldb-command:print arg1
// lldb-check:[...]$1 = -1
// lldb-command:print arg2
// lldb-check:[...]$2 = -2
|
random_line_split
|
web.rs
|
use std::io::Read;
use std::{thread, time};
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use hyper::Ok;
use kuchiki;
use kuchiki::traits::TendrilSink;
fn fetch_url(url: &str) -> impl Read
|
pub fn fetch_html(url: &str) -> kuchiki::NodeRef {
let mut response = fetch_url(url);
kuchiki::parse_html()
.from_utf8()
.read_from(&mut response)
.unwrap()
}
pub fn fetch_string(url: &str) -> String {
let mut response = fetch_url(url);
let mut response_string = String::new();
response.read_to_string(&mut response_string).unwrap();
response_string
}
|
{
//we're going to be nice to the maintainers of the donation tracker
//to avoid DDOSing them, add a delay between each request
let delay_milliseconds = 100;
thread::sleep(time::Duration::from_millis(delay_milliseconds));
//perform the request and read the repsonse into a string
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
let client = Client::with_connector(connector);
let response = client.get(url).send().unwrap();
assert_eq!(response.status, Ok);
response
}
|
identifier_body
|
web.rs
|
use std::io::Read;
use std::{thread, time};
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use hyper::Ok;
use kuchiki;
use kuchiki::traits::TendrilSink;
fn fetch_url(url: &str) -> impl Read {
//we're going to be nice to the maintainers of the donation tracker
//to avoid DDOSing them, add a delay between each request
let delay_milliseconds = 100;
thread::sleep(time::Duration::from_millis(delay_milliseconds));
//perform the request and read the repsonse into a string
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
let client = Client::with_connector(connector);
let response = client.get(url).send().unwrap();
assert_eq!(response.status, Ok);
response
}
pub fn fetch_html(url: &str) -> kuchiki::NodeRef {
let mut response = fetch_url(url);
kuchiki::parse_html()
.from_utf8()
.read_from(&mut response)
.unwrap()
}
pub fn
|
(url: &str) -> String {
let mut response = fetch_url(url);
let mut response_string = String::new();
response.read_to_string(&mut response_string).unwrap();
response_string
}
|
fetch_string
|
identifier_name
|
web.rs
|
use std::io::Read;
use std::{thread, time};
use hyper::Client;
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use hyper::Ok;
use kuchiki;
use kuchiki::traits::TendrilSink;
fn fetch_url(url: &str) -> impl Read {
//we're going to be nice to the maintainers of the donation tracker
//to avoid DDOSing them, add a delay between each request
let delay_milliseconds = 100;
thread::sleep(time::Duration::from_millis(delay_milliseconds));
//perform the request and read the repsonse into a string
let ssl = NativeTlsClient::new().unwrap();
let connector = HttpsConnector::new(ssl);
let client = Client::with_connector(connector);
let response = client.get(url).send().unwrap();
assert_eq!(response.status, Ok);
|
}
pub fn fetch_html(url: &str) -> kuchiki::NodeRef {
let mut response = fetch_url(url);
kuchiki::parse_html()
.from_utf8()
.read_from(&mut response)
.unwrap()
}
pub fn fetch_string(url: &str) -> String {
let mut response = fetch_url(url);
let mut response_string = String::new();
response.read_to_string(&mut response_string).unwrap();
response_string
}
|
response
|
random_line_split
|
mozjs-error.rs
|
// run-pass
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
struct CustomAutoRooterVFTable {
trace: unsafe extern "C" fn(this: *mut i32, trc: *mut u32),
}
unsafe trait CustomAutoTraceable: Sized {
const vftable: CustomAutoRooterVFTable = CustomAutoRooterVFTable {
trace: Self::trace,
};
unsafe extern "C" fn trace(this: *mut i32, trc: *mut u32) {
let this = this as *const Self;
let this = this.as_ref().unwrap();
Self::do_trace(this, trc);
}
fn do_trace(&self, trc: *mut u32);
}
unsafe impl CustomAutoTraceable for () {
fn do_trace(&self, _: *mut u32) {
// nop
}
}
|
fn main() {
let _ = <()>::vftable;
}
|
random_line_split
|
|
mozjs-error.rs
|
// run-pass
#![allow(dead_code)]
#![allow(non_upper_case_globals)]
struct CustomAutoRooterVFTable {
trace: unsafe extern "C" fn(this: *mut i32, trc: *mut u32),
}
unsafe trait CustomAutoTraceable: Sized {
const vftable: CustomAutoRooterVFTable = CustomAutoRooterVFTable {
trace: Self::trace,
};
unsafe extern "C" fn trace(this: *mut i32, trc: *mut u32) {
let this = this as *const Self;
let this = this.as_ref().unwrap();
Self::do_trace(this, trc);
}
fn do_trace(&self, trc: *mut u32);
}
unsafe impl CustomAutoTraceable for () {
fn do_trace(&self, _: *mut u32) {
// nop
}
}
fn
|
() {
let _ = <()>::vftable;
}
|
main
|
identifier_name
|
run-pass.rs
|
// run-pass
#![feature(if_let_guard)]
enum Foo {
Bar,
Baz,
Qux(u8),
}
fn bar(x: bool) -> Foo {
if x { Foo::Baz } else { Foo::Bar }
}
fn baz(x: u8) -> Foo {
if x % 2 == 0 { Foo::Bar } else { Foo::Baz }
}
fn qux(x: u8) -> Foo {
Foo::Qux(x.rotate_left(1))
}
fn main() {
match Some((true, 3)) {
Some((x, _)) if let Foo::Bar = bar(x) => panic!(),
Some((_, x)) if let Foo::Baz = baz(x) => {},
_ => panic!(),
}
|
match Some(42) {
Some(x) if let Foo::Qux(y) = qux(x) => assert_eq!(y, 84),
_ => panic!(),
}
}
|
random_line_split
|
|
run-pass.rs
|
// run-pass
#![feature(if_let_guard)]
enum Foo {
Bar,
Baz,
Qux(u8),
}
fn bar(x: bool) -> Foo {
if x { Foo::Baz } else { Foo::Bar }
}
fn baz(x: u8) -> Foo {
if x % 2 == 0
|
else { Foo::Baz }
}
fn qux(x: u8) -> Foo {
Foo::Qux(x.rotate_left(1))
}
fn main() {
match Some((true, 3)) {
Some((x, _)) if let Foo::Bar = bar(x) => panic!(),
Some((_, x)) if let Foo::Baz = baz(x) => {},
_ => panic!(),
}
match Some(42) {
Some(x) if let Foo::Qux(y) = qux(x) => assert_eq!(y, 84),
_ => panic!(),
}
}
|
{ Foo::Bar }
|
conditional_block
|
run-pass.rs
|
// run-pass
#![feature(if_let_guard)]
enum Foo {
Bar,
Baz,
Qux(u8),
}
fn
|
(x: bool) -> Foo {
if x { Foo::Baz } else { Foo::Bar }
}
fn baz(x: u8) -> Foo {
if x % 2 == 0 { Foo::Bar } else { Foo::Baz }
}
fn qux(x: u8) -> Foo {
Foo::Qux(x.rotate_left(1))
}
fn main() {
match Some((true, 3)) {
Some((x, _)) if let Foo::Bar = bar(x) => panic!(),
Some((_, x)) if let Foo::Baz = baz(x) => {},
_ => panic!(),
}
match Some(42) {
Some(x) if let Foo::Qux(y) = qux(x) => assert_eq!(y, 84),
_ => panic!(),
}
}
|
bar
|
identifier_name
|
run-pass.rs
|
// run-pass
#![feature(if_let_guard)]
enum Foo {
Bar,
Baz,
Qux(u8),
}
fn bar(x: bool) -> Foo {
if x { Foo::Baz } else { Foo::Bar }
}
fn baz(x: u8) -> Foo {
if x % 2 == 0 { Foo::Bar } else { Foo::Baz }
}
fn qux(x: u8) -> Foo
|
fn main() {
match Some((true, 3)) {
Some((x, _)) if let Foo::Bar = bar(x) => panic!(),
Some((_, x)) if let Foo::Baz = baz(x) => {},
_ => panic!(),
}
match Some(42) {
Some(x) if let Foo::Qux(y) = qux(x) => assert_eq!(y, 84),
_ => panic!(),
}
}
|
{
Foo::Qux(x.rotate_left(1))
}
|
identifier_body
|
errors.rs
|
use toml;
use std::error;
use std::fmt::{self, Display};
#[derive(Debug)]
pub enum Error {
Parsing(Vec<toml::ParserError>),
MissingKey(String),
ExpectedType(&'static str, String),
PackageNotFound(String),
TargetNotFound(String),
MissingRoot,
UnsupportedVersion(String),
}
impl error::Error for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
Parsing(_) => "error parsing manifest",
MissingKey(_) => "missing key",
ExpectedType(_, _) => "expected type",
PackageNotFound(_) => "package not found",
TargetNotFound(_) => "target not found",
MissingRoot => "manifest has no root package",
UnsupportedVersion(_) => "unsupported manifest version",
}
}
fn
|
(&self) -> Option<&error::Error> {
None
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
use self::Error::*;
match *self {
Parsing(ref n) => {
for e in n {
try!(e.fmt(f));
try!(writeln!(f, ""));
}
Ok(())
}
MissingKey(ref n) => write!(f, "missing key: '{}'", n),
ExpectedType(ref t, ref n) => write!(f, "expected type: '{}' for '{}'", t, n),
PackageNotFound(ref n) => write!(f, "package not found: '{}'", n),
TargetNotFound(ref n) => write!(f, "target not found: '{}'", n),
MissingRoot => write!(f, "manifest has no root package"),
UnsupportedVersion(ref v) => write!(f, "manifest version '{}' is not supported", v),
}
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
|
cause
|
identifier_name
|
errors.rs
|
use toml;
|
use std::error;
use std::fmt::{self, Display};
#[derive(Debug)]
pub enum Error {
Parsing(Vec<toml::ParserError>),
MissingKey(String),
ExpectedType(&'static str, String),
PackageNotFound(String),
TargetNotFound(String),
MissingRoot,
UnsupportedVersion(String),
}
impl error::Error for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
Parsing(_) => "error parsing manifest",
MissingKey(_) => "missing key",
ExpectedType(_, _) => "expected type",
PackageNotFound(_) => "package not found",
TargetNotFound(_) => "target not found",
MissingRoot => "manifest has no root package",
UnsupportedVersion(_) => "unsupported manifest version",
}
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> {
use self::Error::*;
match *self {
Parsing(ref n) => {
for e in n {
try!(e.fmt(f));
try!(writeln!(f, ""));
}
Ok(())
}
MissingKey(ref n) => write!(f, "missing key: '{}'", n),
ExpectedType(ref t, ref n) => write!(f, "expected type: '{}' for '{}'", t, n),
PackageNotFound(ref n) => write!(f, "package not found: '{}'", n),
TargetNotFound(ref n) => write!(f, "target not found: '{}'", n),
MissingRoot => write!(f, "manifest has no root package"),
UnsupportedVersion(ref v) => write!(f, "manifest version '{}' is not supported", v),
}
}
}
pub type Result<T> = ::std::result::Result<T, Error>;
|
random_line_split
|
|
main.rs
|
use std::fs;
use std::io;
use std::io::Read;
use clap::{App, Arg};
mod llvm_runner;
mod optimizer;
mod parser;
mod runner;
mod structs;
#[cfg(feature = "llvm")]
use llvm_runner::LlvmState;
use parser::parse;
use runner::State;
use structs::OpStream;
fn
|
() {
let app = App::new("BrainRust")
.arg(
Arg::with_name("dry-run")
.short("n")
.long("dry-run")
.help("Don't actually execute the program"),
)
.arg(
Arg::with_name("no-optimize")
.short("0")
.long("no-optimize")
.help("Don't optimize before running"),
)
.arg(Arg::with_name("FILES").min_values(1).required(true));
#[cfg(feature = "llvm")]
let app = app.arg(
Arg::with_name("llvm")
.short("l")
.long("llvm")
.help("Execute using LLVM JIT"),
);
let matches = app.get_matches();
let dry_run = matches.is_present("dryrun");
let no_optimize = matches.is_present("no-optimize");
let use_llvm = cfg!(feature = "llvm") && matches.is_present("llvm");
for filename in matches.values_of("FILES").unwrap() {
let buffer = match read_file(filename) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while reading {}: {}", filename, e);
continue;
}
};
let ops = match parse(&buffer) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while parsing {}: {}", filename, e);
continue;
}
};
let mut opstream = OpStream { ops };
if!(use_llvm || no_optimize) {
opstream.optimize();
}
if!dry_run {
if use_llvm {
#[cfg(feature = "llvm")]
LlvmState::new(&mut io::stdin(), &mut io::stdout(),!no_optimize)
.run(opstream.get());
} else {
State::new(&mut io::stdin(), &mut io::stdout()).run(opstream.get());
};
}
}
}
fn read_file(filename: &str) -> Result<Vec<u8>, io::Error> {
let mut buffer = Vec::new();
fs::File::open(filename)?.read_to_end(&mut buffer)?;
Ok(buffer)
}
|
main
|
identifier_name
|
main.rs
|
use std::fs;
use std::io;
use std::io::Read;
use clap::{App, Arg};
mod llvm_runner;
mod optimizer;
mod parser;
mod runner;
mod structs;
#[cfg(feature = "llvm")]
use llvm_runner::LlvmState;
use parser::parse;
use runner::State;
use structs::OpStream;
fn main() {
let app = App::new("BrainRust")
.arg(
Arg::with_name("dry-run")
.short("n")
.long("dry-run")
.help("Don't actually execute the program"),
)
.arg(
Arg::with_name("no-optimize")
.short("0")
.long("no-optimize")
.help("Don't optimize before running"),
)
.arg(Arg::with_name("FILES").min_values(1).required(true));
#[cfg(feature = "llvm")]
let app = app.arg(
Arg::with_name("llvm")
.short("l")
.long("llvm")
.help("Execute using LLVM JIT"),
);
let matches = app.get_matches();
let dry_run = matches.is_present("dryrun");
let no_optimize = matches.is_present("no-optimize");
let use_llvm = cfg!(feature = "llvm") && matches.is_present("llvm");
|
for filename in matches.values_of("FILES").unwrap() {
let buffer = match read_file(filename) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while reading {}: {}", filename, e);
continue;
}
};
let ops = match parse(&buffer) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while parsing {}: {}", filename, e);
continue;
}
};
let mut opstream = OpStream { ops };
if!(use_llvm || no_optimize) {
opstream.optimize();
}
if!dry_run {
if use_llvm {
#[cfg(feature = "llvm")]
LlvmState::new(&mut io::stdin(), &mut io::stdout(),!no_optimize)
.run(opstream.get());
} else {
State::new(&mut io::stdin(), &mut io::stdout()).run(opstream.get());
};
}
}
}
fn read_file(filename: &str) -> Result<Vec<u8>, io::Error> {
let mut buffer = Vec::new();
fs::File::open(filename)?.read_to_end(&mut buffer)?;
Ok(buffer)
}
|
random_line_split
|
|
main.rs
|
use std::fs;
use std::io;
use std::io::Read;
use clap::{App, Arg};
mod llvm_runner;
mod optimizer;
mod parser;
mod runner;
mod structs;
#[cfg(feature = "llvm")]
use llvm_runner::LlvmState;
use parser::parse;
use runner::State;
use structs::OpStream;
fn main()
|
.long("llvm")
.help("Execute using LLVM JIT"),
);
let matches = app.get_matches();
let dry_run = matches.is_present("dryrun");
let no_optimize = matches.is_present("no-optimize");
let use_llvm = cfg!(feature = "llvm") && matches.is_present("llvm");
for filename in matches.values_of("FILES").unwrap() {
let buffer = match read_file(filename) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while reading {}: {}", filename, e);
continue;
}
};
let ops = match parse(&buffer) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while parsing {}: {}", filename, e);
continue;
}
};
let mut opstream = OpStream { ops };
if!(use_llvm || no_optimize) {
opstream.optimize();
}
if!dry_run {
if use_llvm {
#[cfg(feature = "llvm")]
LlvmState::new(&mut io::stdin(), &mut io::stdout(),!no_optimize)
.run(opstream.get());
} else {
State::new(&mut io::stdin(), &mut io::stdout()).run(opstream.get());
};
}
}
}
fn read_file(filename: &str) -> Result<Vec<u8>, io::Error> {
let mut buffer = Vec::new();
fs::File::open(filename)?.read_to_end(&mut buffer)?;
Ok(buffer)
}
|
{
let app = App::new("BrainRust")
.arg(
Arg::with_name("dry-run")
.short("n")
.long("dry-run")
.help("Don't actually execute the program"),
)
.arg(
Arg::with_name("no-optimize")
.short("0")
.long("no-optimize")
.help("Don't optimize before running"),
)
.arg(Arg::with_name("FILES").min_values(1).required(true));
#[cfg(feature = "llvm")]
let app = app.arg(
Arg::with_name("llvm")
.short("l")
|
identifier_body
|
main.rs
|
use std::fs;
use std::io;
use std::io::Read;
use clap::{App, Arg};
mod llvm_runner;
mod optimizer;
mod parser;
mod runner;
mod structs;
#[cfg(feature = "llvm")]
use llvm_runner::LlvmState;
use parser::parse;
use runner::State;
use structs::OpStream;
fn main() {
let app = App::new("BrainRust")
.arg(
Arg::with_name("dry-run")
.short("n")
.long("dry-run")
.help("Don't actually execute the program"),
)
.arg(
Arg::with_name("no-optimize")
.short("0")
.long("no-optimize")
.help("Don't optimize before running"),
)
.arg(Arg::with_name("FILES").min_values(1).required(true));
#[cfg(feature = "llvm")]
let app = app.arg(
Arg::with_name("llvm")
.short("l")
.long("llvm")
.help("Execute using LLVM JIT"),
);
let matches = app.get_matches();
let dry_run = matches.is_present("dryrun");
let no_optimize = matches.is_present("no-optimize");
let use_llvm = cfg!(feature = "llvm") && matches.is_present("llvm");
for filename in matches.values_of("FILES").unwrap() {
let buffer = match read_file(filename) {
Ok(v) => v,
Err(e) => {
eprintln!("Error while reading {}: {}", filename, e);
continue;
}
};
let ops = match parse(&buffer) {
Ok(v) => v,
Err(e) =>
|
};
let mut opstream = OpStream { ops };
if!(use_llvm || no_optimize) {
opstream.optimize();
}
if!dry_run {
if use_llvm {
#[cfg(feature = "llvm")]
LlvmState::new(&mut io::stdin(), &mut io::stdout(),!no_optimize)
.run(opstream.get());
} else {
State::new(&mut io::stdin(), &mut io::stdout()).run(opstream.get());
};
}
}
}
fn read_file(filename: &str) -> Result<Vec<u8>, io::Error> {
let mut buffer = Vec::new();
fs::File::open(filename)?.read_to_end(&mut buffer)?;
Ok(buffer)
}
|
{
eprintln!("Error while parsing {}: {}", filename, e);
continue;
}
|
conditional_block
|
text_renderer.rs
|
use std::default::Default;
use gfx::{
BlendPreset,
BufferHandle,
BufferUsage,
Device,
DeviceExt,
DrawState,
Frame,
Graphics,
Mesh,
PrimitiveType,
ProgramError,
ProgramHandle,
Resources,
Slice,
SliceKind,
VertexCount,
TextureHandle,
};
use gfx::tex::{SamplerInfo, FilterMethod, WrapMode};
use gfx::batch::{
Error,
RefBatch,
};
use gfx::shade::TextureParam;
use gfx_device_gl::{
GlDevice,
GlResources,
};
use bitmap_font::BitmapFont;
use utils::{grow_buffer, MAT4_ID};
pub struct TextRenderer {
program: ProgramHandle<GlResources>,
state: DrawState,
bitmap_font: BitmapFont,
vertex_data: Vec<Vertex>,
index_data: Vec<u32>,
vertex_buffer: BufferHandle<GlResources, Vertex>,
index_buffer: BufferHandle<GlResources, u32>,
params: TextShaderParams<GlResources>,
}
impl TextRenderer {
pub fn new(
graphics: &mut Graphics<GlDevice>,
frame_size: [u32; 2],
initial_buffer_size: usize,
bitmap_font: BitmapFont,
font_texture: TextureHandle<GlResources>,
) -> Result<TextRenderer, ProgramError> {
let program = match graphics.device.link_program(VERTEX_SRC.clone(), FRAGMENT_SRC.clone()) {
Ok(program_handle) => program_handle,
Err(e) => return Err(e),
};
let vertex_buffer = graphics.device.create_buffer::<Vertex>(initial_buffer_size, BufferUsage::Dynamic);
let index_buffer = graphics.device.create_buffer::<u32>(initial_buffer_size, BufferUsage::Dynamic);
let sampler = graphics.device.create_sampler(
SamplerInfo::new(
FilterMethod::Scale,
WrapMode::Clamp
)
);
let state = DrawState::new().blend(BlendPreset::Alpha);
Ok(TextRenderer {
vertex_data: Vec::new(),
index_data: Vec::new(),
bitmap_font: bitmap_font,
program: program,
state: state,
vertex_buffer: vertex_buffer,
index_buffer: index_buffer,
params: TextShaderParams {
u_model_view_proj: MAT4_ID,
u_screen_size: [frame_size[0] as f32, frame_size[1] as f32],
u_tex_font: (font_texture, Some(sampler)),
},
})
}
///
/// Respond to a change in window size
///
pub fn resize(&mut self, width: u32, height: u32) {
self.params.u_screen_size = [width as f32, height as f32];
}
pub fn draw_text_at_position(
&mut self,
text: &str,
world_position: [f32; 3],
color: [f32; 4],
) {
self.draw_text(text, [0, 0], world_position, 0, color);
}
pub fn draw_text_on_screen(
&mut self,
text: &str,
screen_position: [i32; 2],
color: [f32; 4],
) {
self.draw_text(text, screen_position, [0.0, 0.0, 0.0], 1, color);
}
fn draw_text(
&mut self,
text: &str,
screen_position: [i32; 2],
world_position: [f32; 3],
screen_relative: i32,
color: [f32; 4],
) {
let [mut x, y] = screen_position;
let scale_w = self.bitmap_font.scale_w as f32;
let scale_h = self.bitmap_font.scale_h as f32;
// placeholder for characters missing from font
let default_character = Default::default();
for character in text.chars() {
let bc = match self.bitmap_font.characters.get(&character) {
Some(c) => c,
None => &default_character,
};
// Push quad vertices in CCW direction
let index = self.vertex_data.len();
let x_offset = (bc.xoffset as i32 + x) as f32;
let y_offset = (bc.yoffset as i32 + y) as f32;
// 0 - top left
self.vertex_data.push(Vertex {
position: [
x_offset,
y_offset,
],
color: color,
texcoords: [
bc.x as f32 / scale_w,
bc.y as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// 1 - bottom left
self.vertex_data.push(Vertex{
position: [
x_offset,
bc.height as f32 + y_offset
],
color: color,
texcoords: [
bc.x as f32 / scale_w,
(bc.y + bc.height) as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// 2 - bottom right
self.vertex_data.push(Vertex{
position: [
bc.width as f32 + x_offset,
bc.height as f32 + y_offset,
],
color: color,
texcoords: [
(bc.x + bc.width) as f32 / scale_w,
(bc.y + bc.height) as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// 3 - top right
self.vertex_data.push(Vertex{
position: [
bc.width as f32 + x_offset,
y_offset,
],
color: color,
texcoords: [
(bc.x + bc.width) as f32 / scale_w,
bc.y as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// Top-left triangle
self.index_data.push((index + 0) as u32);
self.index_data.push((index + 1) as u32);
self.index_data.push((index + 3) as u32);
// Bottom-right triangle
self.index_data.push((index + 3) as u32);
self.index_data.push((index + 1) as u32);
self.index_data.push((index + 2) as u32);
x += bc.xadvance as i32;
}
}
///
/// Draw and clear the current batch of lines
///
pub fn render(
&mut self,
graphics: &mut Graphics<GlDevice>,
frame: &Frame<GlResources>,
projection: [[f32; 4]; 4],
) {
self.params.u_model_view_proj = projection;
if self.vertex_data.len() > self.vertex_buffer.len() {
self.vertex_buffer = grow_buffer(graphics, self.vertex_buffer, self.vertex_data.len());
}
if self.index_data.len() > self.index_buffer.len() {
self.index_buffer = grow_buffer(graphics, self.index_buffer, self.index_data.len());
}
graphics.device.update_buffer(self.vertex_buffer.clone(), &self.vertex_data[..], 0);
graphics.device.update_buffer(self.index_buffer.clone(), &self.index_data[..], 0);
match self.make_batch(graphics) {
Ok(batch) => {
graphics.draw(&batch, &self.params, frame).unwrap();
},
Err(e) => {
println!("Error creating debug render batch: {:?}", e);
},
}
self.vertex_data.clear();
self.index_data.clear();
}
///
/// Construct a new ref batch for the current number of vertices
///
fn make_batch(&mut self, graphics: &mut Graphics<GlDevice>) -> Result<RefBatch<TextShaderParams<GlResources>>, Error> {
let mesh = Mesh::from_format(
self.vertex_buffer.clone(),
self.vertex_data.len() as VertexCount
);
let slice = Slice {
start: 0,
end: self.index_data.len() as u32,
prim_type: PrimitiveType::TriangleList,
kind: SliceKind::Index32(self.index_buffer.clone(), 0),
};
graphics.make_batch(&self.program, &mesh, slice, &self.state)
}
}
static VERTEX_SRC: &'static [u8] = b"
#version 150 core
uniform vec2 u_screen_size;
uniform mat4 u_model_view_proj;
in vec2 position;
in vec4 world_position;
in int screen_relative;
in vec4 color;
in vec2 texcoords;
out vec4 v_color;
out vec2 v_TexCoord;
void main() {
// on-screen offset from text origin
vec2 screen_offset = vec2(
2 * position.x / u_screen_size.x - 1,
1 - 2 * position.y / u_screen_size.y
);
vec4 screen_position = u_model_view_proj * world_position;
// perspective divide to get normalized device coords
vec2 world_offset = vec2(
screen_position.x / screen_position.z + 1,
screen_position.y / screen_position.z - 1
);
// on-screen offset accounting for world_position
world_offset = screen_relative == 0? world_offset : vec2(0.0, 0.0);
gl_Position = vec4(world_offset + screen_offset, 0, 1.0);
v_TexCoord = texcoords;
v_color = color;
}
";
static FRAGMENT_SRC: &'static [u8] = b"
#version 150
uniform sampler2D u_tex_font;
in vec4 v_color;
in vec2 v_TexCoord;
out vec4 out_color;
void main() {
vec4 font_color = texture(u_tex_font, v_TexCoord);
out_color = vec4(v_color.xyz, font_color.a * v_color.a);
}
";
#[vertex_format]
|
struct Vertex {
position: [f32; 2],
texcoords: [f32; 2],
world_position: [f32; 3],
screen_relative: i32,
color: [f32; 4],
}
#[shader_param]
struct TextShaderParams<R: Resources> {
u_model_view_proj: [[f32; 4]; 4],
u_screen_size: [f32; 2],
u_tex_font: TextureParam<R>,
}
|
#[derive(Copy)]
#[derive(Clone)]
#[derive(Debug)]
|
random_line_split
|
text_renderer.rs
|
use std::default::Default;
use gfx::{
BlendPreset,
BufferHandle,
BufferUsage,
Device,
DeviceExt,
DrawState,
Frame,
Graphics,
Mesh,
PrimitiveType,
ProgramError,
ProgramHandle,
Resources,
Slice,
SliceKind,
VertexCount,
TextureHandle,
};
use gfx::tex::{SamplerInfo, FilterMethod, WrapMode};
use gfx::batch::{
Error,
RefBatch,
};
use gfx::shade::TextureParam;
use gfx_device_gl::{
GlDevice,
GlResources,
};
use bitmap_font::BitmapFont;
use utils::{grow_buffer, MAT4_ID};
pub struct TextRenderer {
program: ProgramHandle<GlResources>,
state: DrawState,
bitmap_font: BitmapFont,
vertex_data: Vec<Vertex>,
index_data: Vec<u32>,
vertex_buffer: BufferHandle<GlResources, Vertex>,
index_buffer: BufferHandle<GlResources, u32>,
params: TextShaderParams<GlResources>,
}
impl TextRenderer {
pub fn new(
graphics: &mut Graphics<GlDevice>,
frame_size: [u32; 2],
initial_buffer_size: usize,
bitmap_font: BitmapFont,
font_texture: TextureHandle<GlResources>,
) -> Result<TextRenderer, ProgramError> {
let program = match graphics.device.link_program(VERTEX_SRC.clone(), FRAGMENT_SRC.clone()) {
Ok(program_handle) => program_handle,
Err(e) => return Err(e),
};
let vertex_buffer = graphics.device.create_buffer::<Vertex>(initial_buffer_size, BufferUsage::Dynamic);
let index_buffer = graphics.device.create_buffer::<u32>(initial_buffer_size, BufferUsage::Dynamic);
let sampler = graphics.device.create_sampler(
SamplerInfo::new(
FilterMethod::Scale,
WrapMode::Clamp
)
);
let state = DrawState::new().blend(BlendPreset::Alpha);
Ok(TextRenderer {
vertex_data: Vec::new(),
index_data: Vec::new(),
bitmap_font: bitmap_font,
program: program,
state: state,
vertex_buffer: vertex_buffer,
index_buffer: index_buffer,
params: TextShaderParams {
u_model_view_proj: MAT4_ID,
u_screen_size: [frame_size[0] as f32, frame_size[1] as f32],
u_tex_font: (font_texture, Some(sampler)),
},
})
}
///
/// Respond to a change in window size
///
pub fn
|
(&mut self, width: u32, height: u32) {
self.params.u_screen_size = [width as f32, height as f32];
}
pub fn draw_text_at_position(
&mut self,
text: &str,
world_position: [f32; 3],
color: [f32; 4],
) {
self.draw_text(text, [0, 0], world_position, 0, color);
}
pub fn draw_text_on_screen(
&mut self,
text: &str,
screen_position: [i32; 2],
color: [f32; 4],
) {
self.draw_text(text, screen_position, [0.0, 0.0, 0.0], 1, color);
}
fn draw_text(
&mut self,
text: &str,
screen_position: [i32; 2],
world_position: [f32; 3],
screen_relative: i32,
color: [f32; 4],
) {
let [mut x, y] = screen_position;
let scale_w = self.bitmap_font.scale_w as f32;
let scale_h = self.bitmap_font.scale_h as f32;
// placeholder for characters missing from font
let default_character = Default::default();
for character in text.chars() {
let bc = match self.bitmap_font.characters.get(&character) {
Some(c) => c,
None => &default_character,
};
// Push quad vertices in CCW direction
let index = self.vertex_data.len();
let x_offset = (bc.xoffset as i32 + x) as f32;
let y_offset = (bc.yoffset as i32 + y) as f32;
// 0 - top left
self.vertex_data.push(Vertex {
position: [
x_offset,
y_offset,
],
color: color,
texcoords: [
bc.x as f32 / scale_w,
bc.y as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// 1 - bottom left
self.vertex_data.push(Vertex{
position: [
x_offset,
bc.height as f32 + y_offset
],
color: color,
texcoords: [
bc.x as f32 / scale_w,
(bc.y + bc.height) as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// 2 - bottom right
self.vertex_data.push(Vertex{
position: [
bc.width as f32 + x_offset,
bc.height as f32 + y_offset,
],
color: color,
texcoords: [
(bc.x + bc.width) as f32 / scale_w,
(bc.y + bc.height) as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// 3 - top right
self.vertex_data.push(Vertex{
position: [
bc.width as f32 + x_offset,
y_offset,
],
color: color,
texcoords: [
(bc.x + bc.width) as f32 / scale_w,
bc.y as f32 / scale_h,
],
world_position: world_position,
screen_relative: screen_relative,
});
// Top-left triangle
self.index_data.push((index + 0) as u32);
self.index_data.push((index + 1) as u32);
self.index_data.push((index + 3) as u32);
// Bottom-right triangle
self.index_data.push((index + 3) as u32);
self.index_data.push((index + 1) as u32);
self.index_data.push((index + 2) as u32);
x += bc.xadvance as i32;
}
}
///
/// Draw and clear the current batch of lines
///
pub fn render(
&mut self,
graphics: &mut Graphics<GlDevice>,
frame: &Frame<GlResources>,
projection: [[f32; 4]; 4],
) {
self.params.u_model_view_proj = projection;
if self.vertex_data.len() > self.vertex_buffer.len() {
self.vertex_buffer = grow_buffer(graphics, self.vertex_buffer, self.vertex_data.len());
}
if self.index_data.len() > self.index_buffer.len() {
self.index_buffer = grow_buffer(graphics, self.index_buffer, self.index_data.len());
}
graphics.device.update_buffer(self.vertex_buffer.clone(), &self.vertex_data[..], 0);
graphics.device.update_buffer(self.index_buffer.clone(), &self.index_data[..], 0);
match self.make_batch(graphics) {
Ok(batch) => {
graphics.draw(&batch, &self.params, frame).unwrap();
},
Err(e) => {
println!("Error creating debug render batch: {:?}", e);
},
}
self.vertex_data.clear();
self.index_data.clear();
}
///
/// Construct a new ref batch for the current number of vertices
///
fn make_batch(&mut self, graphics: &mut Graphics<GlDevice>) -> Result<RefBatch<TextShaderParams<GlResources>>, Error> {
let mesh = Mesh::from_format(
self.vertex_buffer.clone(),
self.vertex_data.len() as VertexCount
);
let slice = Slice {
start: 0,
end: self.index_data.len() as u32,
prim_type: PrimitiveType::TriangleList,
kind: SliceKind::Index32(self.index_buffer.clone(), 0),
};
graphics.make_batch(&self.program, &mesh, slice, &self.state)
}
}
static VERTEX_SRC: &'static [u8] = b"
#version 150 core
uniform vec2 u_screen_size;
uniform mat4 u_model_view_proj;
in vec2 position;
in vec4 world_position;
in int screen_relative;
in vec4 color;
in vec2 texcoords;
out vec4 v_color;
out vec2 v_TexCoord;
void main() {
// on-screen offset from text origin
vec2 screen_offset = vec2(
2 * position.x / u_screen_size.x - 1,
1 - 2 * position.y / u_screen_size.y
);
vec4 screen_position = u_model_view_proj * world_position;
// perspective divide to get normalized device coords
vec2 world_offset = vec2(
screen_position.x / screen_position.z + 1,
screen_position.y / screen_position.z - 1
);
// on-screen offset accounting for world_position
world_offset = screen_relative == 0? world_offset : vec2(0.0, 0.0);
gl_Position = vec4(world_offset + screen_offset, 0, 1.0);
v_TexCoord = texcoords;
v_color = color;
}
";
static FRAGMENT_SRC: &'static [u8] = b"
#version 150
uniform sampler2D u_tex_font;
in vec4 v_color;
in vec2 v_TexCoord;
out vec4 out_color;
void main() {
vec4 font_color = texture(u_tex_font, v_TexCoord);
out_color = vec4(v_color.xyz, font_color.a * v_color.a);
}
";
#[vertex_format]
#[derive(Copy)]
#[derive(Clone)]
#[derive(Debug)]
struct Vertex {
position: [f32; 2],
texcoords: [f32; 2],
world_position: [f32; 3],
screen_relative: i32,
color: [f32; 4],
}
#[shader_param]
struct TextShaderParams<R: Resources> {
u_model_view_proj: [[f32; 4]; 4],
u_screen_size: [f32; 2],
u_tex_font: TextureParam<R>,
}
|
resize
|
identifier_name
|
http.rs
|
extern crate websocket;
extern crate hyper;
extern crate serde_json;
use std::thread;
use self::hyper::header::{ContentLength, ContentType};
use self::hyper::mime::{Mime, TopLevel, SubLevel};
use self::hyper::server::{Request, Response};
use self::hyper::status::StatusCode;
use self::hyper::uri::RequestUri;
const HEADER: &'static str = include_str!("html/index.html");
const SCRIPT: &'static str = include_str!("html/script.js");
pub fn start_thread() -> thread::JoinHandle<()> {
thread::spawn(|| {
let addr = format!("0.0.0.0:{}", port());
let server = hyper::Server::http(addr).unwrap();
let index = format!("{}<script>{}</script>", HEADER, SCRIPT);
server
.handle(move |req: Request, mut res: Response| {
let get_response = match req.uri {
RequestUri::AbsolutePath(path) => {
match path.as_ref() {
"/" => index.as_bytes(),
"/favicon.ico" => {
res.headers_mut()
.set(ContentType(Mime(TopLevel::Image,
SubLevel::Ext("x-icon".to_string()),
vec![])));
include_bytes!("html/favicon.ico")
}
_ => {
*res.status_mut() = StatusCode::NotFound;
b"404"
}
}
}
_ =>
|
};
res.headers_mut()
.set(ContentLength(get_response.len() as u64));
res.send(get_response).unwrap();
})
.unwrap();
})
}
pub fn port() -> i32 {
8080
}
|
{
*res.status_mut() = StatusCode::MethodNotAllowed;
b"502"
}
|
conditional_block
|
http.rs
|
extern crate websocket;
extern crate hyper;
extern crate serde_json;
use std::thread;
use self::hyper::header::{ContentLength, ContentType};
use self::hyper::mime::{Mime, TopLevel, SubLevel};
use self::hyper::server::{Request, Response};
use self::hyper::status::StatusCode;
use self::hyper::uri::RequestUri;
const HEADER: &'static str = include_str!("html/index.html");
const SCRIPT: &'static str = include_str!("html/script.js");
pub fn
|
() -> thread::JoinHandle<()> {
thread::spawn(|| {
let addr = format!("0.0.0.0:{}", port());
let server = hyper::Server::http(addr).unwrap();
let index = format!("{}<script>{}</script>", HEADER, SCRIPT);
server
.handle(move |req: Request, mut res: Response| {
let get_response = match req.uri {
RequestUri::AbsolutePath(path) => {
match path.as_ref() {
"/" => index.as_bytes(),
"/favicon.ico" => {
res.headers_mut()
.set(ContentType(Mime(TopLevel::Image,
SubLevel::Ext("x-icon".to_string()),
vec![])));
include_bytes!("html/favicon.ico")
}
_ => {
*res.status_mut() = StatusCode::NotFound;
b"404"
}
}
}
_ => {
*res.status_mut() = StatusCode::MethodNotAllowed;
b"502"
}
};
res.headers_mut()
.set(ContentLength(get_response.len() as u64));
res.send(get_response).unwrap();
})
.unwrap();
})
}
pub fn port() -> i32 {
8080
}
|
start_thread
|
identifier_name
|
http.rs
|
extern crate websocket;
extern crate hyper;
extern crate serde_json;
use std::thread;
use self::hyper::header::{ContentLength, ContentType};
use self::hyper::mime::{Mime, TopLevel, SubLevel};
use self::hyper::server::{Request, Response};
use self::hyper::status::StatusCode;
use self::hyper::uri::RequestUri;
const HEADER: &'static str = include_str!("html/index.html");
const SCRIPT: &'static str = include_str!("html/script.js");
pub fn start_thread() -> thread::JoinHandle<()> {
thread::spawn(|| {
let addr = format!("0.0.0.0:{}", port());
let server = hyper::Server::http(addr).unwrap();
let index = format!("{}<script>{}</script>", HEADER, SCRIPT);
server
.handle(move |req: Request, mut res: Response| {
let get_response = match req.uri {
RequestUri::AbsolutePath(path) => {
match path.as_ref() {
"/" => index.as_bytes(),
"/favicon.ico" => {
res.headers_mut()
.set(ContentType(Mime(TopLevel::Image,
SubLevel::Ext("x-icon".to_string()),
vec![])));
include_bytes!("html/favicon.ico")
}
_ => {
*res.status_mut() = StatusCode::NotFound;
b"404"
}
}
}
_ => {
*res.status_mut() = StatusCode::MethodNotAllowed;
b"502"
}
};
res.headers_mut()
.set(ContentLength(get_response.len() as u64));
res.send(get_response).unwrap();
})
.unwrap();
})
}
pub fn port() -> i32
|
{
8080
}
|
identifier_body
|
|
http.rs
|
extern crate websocket;
extern crate hyper;
extern crate serde_json;
use std::thread;
use self::hyper::header::{ContentLength, ContentType};
use self::hyper::mime::{Mime, TopLevel, SubLevel};
use self::hyper::server::{Request, Response};
use self::hyper::status::StatusCode;
use self::hyper::uri::RequestUri;
const HEADER: &'static str = include_str!("html/index.html");
const SCRIPT: &'static str = include_str!("html/script.js");
pub fn start_thread() -> thread::JoinHandle<()> {
thread::spawn(|| {
let addr = format!("0.0.0.0:{}", port());
let server = hyper::Server::http(addr).unwrap();
let index = format!("{}<script>{}</script>", HEADER, SCRIPT);
server
.handle(move |req: Request, mut res: Response| {
let get_response = match req.uri {
RequestUri::AbsolutePath(path) => {
match path.as_ref() {
"/" => index.as_bytes(),
"/favicon.ico" => {
res.headers_mut()
|
vec![])));
include_bytes!("html/favicon.ico")
}
_ => {
*res.status_mut() = StatusCode::NotFound;
b"404"
}
}
}
_ => {
*res.status_mut() = StatusCode::MethodNotAllowed;
b"502"
}
};
res.headers_mut()
.set(ContentLength(get_response.len() as u64));
res.send(get_response).unwrap();
})
.unwrap();
})
}
pub fn port() -> i32 {
8080
}
|
.set(ContentType(Mime(TopLevel::Image,
SubLevel::Ext("x-icon".to_string()),
|
random_line_split
|
compositor_thread.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/. */
//! Communication with the compositor thread.
use SendableFrameTree;
use compositor::CompositingReason;
use euclid::point::Point2D;
use euclid::size::Size2D;
use gfx_traits::ScrollRootId;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::{Key, KeyModifiers, KeyState, PipelineId};
use net_traits::image::base::Image;
use profile_traits::mem;
use profile_traits::time;
use script_traits::{AnimationState, ConstellationMsg, EventResult};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::sync::mpsc::{Receiver, Sender};
use style_traits::cursor::Cursor;
use style_traits::viewport::ViewportConstraints;
use webrender;
use webrender_traits;
/// Sends messages to the compositor. This is a trait supplied by the port because the method used
/// to communicate with the compositor may have to kick OS event loops awake, communicate cross-
/// process, and so forth.
pub trait CompositorProxy :'static + Send {
/// Sends a message to the compositor.
fn send(&self, msg: Msg);
/// Clones the compositor proxy.
fn clone_compositor_proxy(&self) -> Box<CompositorProxy +'static + Send>;
}
/// The port that the compositor receives messages on. As above, this is a trait supplied by the
/// Servo port.
pub trait CompositorReceiver :'static {
/// Receives the next message inbound for the compositor. This must not block.
fn try_recv_compositor_msg(&mut self) -> Option<Msg>;
/// Synchronously waits for, and returns, the next message inbound for the compositor.
fn recv_compositor_msg(&mut self) -> Msg;
}
/// A convenience implementation of `CompositorReceiver` for a plain old Rust `Receiver`.
impl CompositorReceiver for Receiver<Msg> {
fn
|
(&mut self) -> Option<Msg> {
self.try_recv().ok()
}
fn recv_compositor_msg(&mut self) -> Msg {
self.recv().unwrap()
}
}
pub trait RenderListener {
fn recomposite(&mut self, reason: CompositingReason);
}
impl RenderListener for Box<CompositorProxy +'static> {
fn recomposite(&mut self, reason: CompositingReason) {
self.send(Msg::Recomposite(reason));
}
}
/// Messages from the painting thread and the constellation thread to the compositor thread.
pub enum Msg {
/// Requests that the compositor shut down.
Exit,
/// Informs the compositor that the constellation has completed shutdown.
/// Required because the constellation can have pending calls to make
/// (e.g. SetFrameTree) at the time that we send it an ExitMsg.
ShutdownComplete,
/// Scroll a page in a window
ScrollFragmentPoint(PipelineId, ScrollRootId, Point2D<f32>, bool),
/// Alerts the compositor that the current page has changed its title.
ChangePageTitle(PipelineId, Option<String>),
/// Alerts the compositor that the current page has changed its URL.
ChangePageUrl(PipelineId, ServoUrl),
/// Alerts the compositor that the given pipeline has changed whether it is running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Replaces the current frame tree, typically called during main frame navigation.
SetFrameTree(SendableFrameTree, IpcSender<()>),
/// The load of a page has begun: (can go back, can go forward).
LoadStart(bool, bool),
/// The load of a page has completed: (can go back, can go forward, is root frame).
LoadComplete(bool, bool, bool),
/// Wether or not to follow a link
AllowNavigation(ServoUrl, IpcSender<bool>),
/// We hit the delayed composition timeout. (See `delayed_composition.rs`.)
DelayedCompositionTimeout(u64),
/// Composite.
Recomposite(CompositingReason),
/// Sends an unconsumed key event back to the compositor.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// Changes the cursor.
SetCursor(Cursor),
/// Composite to a PNG file and return the Image over a passed channel.
CreatePng(IpcSender<Option<Image>>),
/// Alerts the compositor that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
/// A reply to the compositor asking if the output image is stable.
IsReadyToSaveImageReply(bool),
/// A favicon was detected
NewFavicon(ServoUrl),
/// <head> tag finished parsing
HeadParsed,
/// A status message to be displayed by the browser chrome.
Status(Option<String>),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(Size2D<u32>, Point2D<i32>)>),
/// Move the window to a point
MoveTo(Point2D<i32>),
/// Resize the window to size
ResizeTo(Size2D<u32>),
/// Pipeline visibility changed
PipelineVisibilityChanged(PipelineId, bool),
/// WebRender has successfully processed a scroll. The boolean specifies whether a composite is
/// needed.
NewScrollFrameReady(bool),
/// A pipeline was shut down.
// This message acts as a synchronization point between the constellation,
// when it shuts down a pipeline, to the compositor; when the compositor
// sends a reply on the IpcSender, the constellation knows it's safe to
// tear down the other threads associated with this pipeline.
PipelineExited(PipelineId, IpcSender<()>),
/// Runs a closure in the compositor thread.
/// It's used to dispatch functions from webrender to the main thread's event loop.
/// Required to allow WGL GLContext sharing in Windows.
Dispatch(Box<Fn() + Send>),
/// Enter or exit fullscreen
SetFullscreenState(bool),
}
impl Debug for Msg {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
Msg::Exit => write!(f, "Exit"),
Msg::ShutdownComplete => write!(f, "ShutdownComplete"),
Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"),
Msg::ChangeRunningAnimationsState(..) => write!(f, "ChangeRunningAnimationsState"),
Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"),
Msg::ChangePageUrl(..) => write!(f, "ChangePageUrl"),
Msg::SetFrameTree(..) => write!(f, "SetFrameTree"),
Msg::LoadComplete(..) => write!(f, "LoadComplete"),
Msg::AllowNavigation(..) => write!(f, "AllowNavigation"),
Msg::LoadStart(..) => write!(f, "LoadStart"),
Msg::DelayedCompositionTimeout(..) => write!(f, "DelayedCompositionTimeout"),
Msg::Recomposite(..) => write!(f, "Recomposite"),
Msg::KeyEvent(..) => write!(f, "KeyEvent"),
Msg::TouchEventProcessed(..) => write!(f, "TouchEventProcessed"),
Msg::SetCursor(..) => write!(f, "SetCursor"),
Msg::CreatePng(..) => write!(f, "CreatePng"),
Msg::ViewportConstrained(..) => write!(f, "ViewportConstrained"),
Msg::IsReadyToSaveImageReply(..) => write!(f, "IsReadyToSaveImageReply"),
Msg::NewFavicon(..) => write!(f, "NewFavicon"),
Msg::HeadParsed => write!(f, "HeadParsed"),
Msg::Status(..) => write!(f, "Status"),
Msg::GetClientWindow(..) => write!(f, "GetClientWindow"),
Msg::MoveTo(..) => write!(f, "MoveTo"),
Msg::ResizeTo(..) => write!(f, "ResizeTo"),
Msg::PipelineVisibilityChanged(..) => write!(f, "PipelineVisibilityChanged"),
Msg::PipelineExited(..) => write!(f, "PipelineExited"),
Msg::NewScrollFrameReady(..) => write!(f, "NewScrollFrameReady"),
Msg::Dispatch(..) => write!(f, "Dispatch"),
Msg::SetFullscreenState(..) => write!(f, "SetFullscreenState"),
}
}
}
/// Data used to construct a compositor.
pub struct InitialCompositorState {
/// A channel to the compositor.
pub sender: Box<CompositorProxy + Send>,
/// A port on which messages inbound to the compositor can be received.
pub receiver: Box<CompositorReceiver>,
/// A channel to the constellation.
pub constellation_chan: Sender<ConstellationMsg>,
/// A channel to the time profiler thread.
pub time_profiler_chan: time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// Instance of webrender API
pub webrender: webrender::Renderer,
pub webrender_api_sender: webrender_traits::RenderApiSender,
}
|
try_recv_compositor_msg
|
identifier_name
|
compositor_thread.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/. */
//! Communication with the compositor thread.
use SendableFrameTree;
use compositor::CompositingReason;
use euclid::point::Point2D;
use euclid::size::Size2D;
use gfx_traits::ScrollRootId;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::{Key, KeyModifiers, KeyState, PipelineId};
use net_traits::image::base::Image;
use profile_traits::mem;
use profile_traits::time;
use script_traits::{AnimationState, ConstellationMsg, EventResult};
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::sync::mpsc::{Receiver, Sender};
use style_traits::cursor::Cursor;
use style_traits::viewport::ViewportConstraints;
use webrender;
use webrender_traits;
/// Sends messages to the compositor. This is a trait supplied by the port because the method used
/// to communicate with the compositor may have to kick OS event loops awake, communicate cross-
/// process, and so forth.
pub trait CompositorProxy :'static + Send {
/// Sends a message to the compositor.
fn send(&self, msg: Msg);
/// Clones the compositor proxy.
fn clone_compositor_proxy(&self) -> Box<CompositorProxy +'static + Send>;
}
/// The port that the compositor receives messages on. As above, this is a trait supplied by the
/// Servo port.
pub trait CompositorReceiver :'static {
/// Receives the next message inbound for the compositor. This must not block.
fn try_recv_compositor_msg(&mut self) -> Option<Msg>;
/// Synchronously waits for, and returns, the next message inbound for the compositor.
fn recv_compositor_msg(&mut self) -> Msg;
}
/// A convenience implementation of `CompositorReceiver` for a plain old Rust `Receiver`.
impl CompositorReceiver for Receiver<Msg> {
fn try_recv_compositor_msg(&mut self) -> Option<Msg> {
self.try_recv().ok()
}
fn recv_compositor_msg(&mut self) -> Msg {
self.recv().unwrap()
}
}
pub trait RenderListener {
fn recomposite(&mut self, reason: CompositingReason);
}
impl RenderListener for Box<CompositorProxy +'static> {
fn recomposite(&mut self, reason: CompositingReason) {
self.send(Msg::Recomposite(reason));
}
}
/// Messages from the painting thread and the constellation thread to the compositor thread.
pub enum Msg {
/// Requests that the compositor shut down.
Exit,
/// Informs the compositor that the constellation has completed shutdown.
/// Required because the constellation can have pending calls to make
/// (e.g. SetFrameTree) at the time that we send it an ExitMsg.
ShutdownComplete,
/// Scroll a page in a window
ScrollFragmentPoint(PipelineId, ScrollRootId, Point2D<f32>, bool),
/// Alerts the compositor that the current page has changed its title.
ChangePageTitle(PipelineId, Option<String>),
/// Alerts the compositor that the current page has changed its URL.
ChangePageUrl(PipelineId, ServoUrl),
/// Alerts the compositor that the given pipeline has changed whether it is running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Replaces the current frame tree, typically called during main frame navigation.
SetFrameTree(SendableFrameTree, IpcSender<()>),
/// The load of a page has begun: (can go back, can go forward).
LoadStart(bool, bool),
/// The load of a page has completed: (can go back, can go forward, is root frame).
LoadComplete(bool, bool, bool),
/// Wether or not to follow a link
AllowNavigation(ServoUrl, IpcSender<bool>),
/// We hit the delayed composition timeout. (See `delayed_composition.rs`.)
DelayedCompositionTimeout(u64),
/// Composite.
Recomposite(CompositingReason),
/// Sends an unconsumed key event back to the compositor.
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// Changes the cursor.
SetCursor(Cursor),
/// Composite to a PNG file and return the Image over a passed channel.
|
CreatePng(IpcSender<Option<Image>>),
/// Alerts the compositor that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
/// A reply to the compositor asking if the output image is stable.
IsReadyToSaveImageReply(bool),
/// A favicon was detected
NewFavicon(ServoUrl),
/// <head> tag finished parsing
HeadParsed,
/// A status message to be displayed by the browser chrome.
Status(Option<String>),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(Size2D<u32>, Point2D<i32>)>),
/// Move the window to a point
MoveTo(Point2D<i32>),
/// Resize the window to size
ResizeTo(Size2D<u32>),
/// Pipeline visibility changed
PipelineVisibilityChanged(PipelineId, bool),
/// WebRender has successfully processed a scroll. The boolean specifies whether a composite is
/// needed.
NewScrollFrameReady(bool),
/// A pipeline was shut down.
// This message acts as a synchronization point between the constellation,
// when it shuts down a pipeline, to the compositor; when the compositor
// sends a reply on the IpcSender, the constellation knows it's safe to
// tear down the other threads associated with this pipeline.
PipelineExited(PipelineId, IpcSender<()>),
/// Runs a closure in the compositor thread.
/// It's used to dispatch functions from webrender to the main thread's event loop.
/// Required to allow WGL GLContext sharing in Windows.
Dispatch(Box<Fn() + Send>),
/// Enter or exit fullscreen
SetFullscreenState(bool),
}
impl Debug for Msg {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
Msg::Exit => write!(f, "Exit"),
Msg::ShutdownComplete => write!(f, "ShutdownComplete"),
Msg::ScrollFragmentPoint(..) => write!(f, "ScrollFragmentPoint"),
Msg::ChangeRunningAnimationsState(..) => write!(f, "ChangeRunningAnimationsState"),
Msg::ChangePageTitle(..) => write!(f, "ChangePageTitle"),
Msg::ChangePageUrl(..) => write!(f, "ChangePageUrl"),
Msg::SetFrameTree(..) => write!(f, "SetFrameTree"),
Msg::LoadComplete(..) => write!(f, "LoadComplete"),
Msg::AllowNavigation(..) => write!(f, "AllowNavigation"),
Msg::LoadStart(..) => write!(f, "LoadStart"),
Msg::DelayedCompositionTimeout(..) => write!(f, "DelayedCompositionTimeout"),
Msg::Recomposite(..) => write!(f, "Recomposite"),
Msg::KeyEvent(..) => write!(f, "KeyEvent"),
Msg::TouchEventProcessed(..) => write!(f, "TouchEventProcessed"),
Msg::SetCursor(..) => write!(f, "SetCursor"),
Msg::CreatePng(..) => write!(f, "CreatePng"),
Msg::ViewportConstrained(..) => write!(f, "ViewportConstrained"),
Msg::IsReadyToSaveImageReply(..) => write!(f, "IsReadyToSaveImageReply"),
Msg::NewFavicon(..) => write!(f, "NewFavicon"),
Msg::HeadParsed => write!(f, "HeadParsed"),
Msg::Status(..) => write!(f, "Status"),
Msg::GetClientWindow(..) => write!(f, "GetClientWindow"),
Msg::MoveTo(..) => write!(f, "MoveTo"),
Msg::ResizeTo(..) => write!(f, "ResizeTo"),
Msg::PipelineVisibilityChanged(..) => write!(f, "PipelineVisibilityChanged"),
Msg::PipelineExited(..) => write!(f, "PipelineExited"),
Msg::NewScrollFrameReady(..) => write!(f, "NewScrollFrameReady"),
Msg::Dispatch(..) => write!(f, "Dispatch"),
Msg::SetFullscreenState(..) => write!(f, "SetFullscreenState"),
}
}
}
/// Data used to construct a compositor.
pub struct InitialCompositorState {
/// A channel to the compositor.
pub sender: Box<CompositorProxy + Send>,
/// A port on which messages inbound to the compositor can be received.
pub receiver: Box<CompositorReceiver>,
/// A channel to the constellation.
pub constellation_chan: Sender<ConstellationMsg>,
/// A channel to the time profiler thread.
pub time_profiler_chan: time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// Instance of webrender API
pub webrender: webrender::Renderer,
pub webrender_api_sender: webrender_traits::RenderApiSender,
}
|
random_line_split
|
|
vec-res-add.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.
struct
|
{
i:int
}
fn r(i:int) -> r { r { i: i } }
impl Drop for r {
fn drop(&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR not implemented
println!("{}", j);
//~^ ERROR not implemented
}
|
r
|
identifier_name
|
vec-res-add.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.
struct r {
i:int
}
fn r(i:int) -> r { r { i: i } }
impl Drop for r {
fn drop(&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR not implemented
println!("{}", j);
//~^ ERROR not implemented
|
}
|
random_line_split
|
|
vec-res-add.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.
struct r {
i:int
}
fn r(i:int) -> r { r { i: i } }
impl Drop for r {
fn drop(&mut self) {}
}
fn main()
|
{
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR not implemented
println!("{}", j);
//~^ ERROR not implemented
}
|
identifier_body
|
|
function-arg-initialization.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.
// min-lldb-version: 310
// This test case checks if function arguments already have the correct value when breaking at the
// first line of the function, that is if the function prologue has already been executed at the
// first line. Note that because of the __morestack part of the prologue GDB incorrectly breaks at
// before the arguments have been properly loaded when setting the breakpoint via the function name.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$1 = 1
// gdb-command:print b
// gdb-check:$2 = true
// gdb-command:print c
// gdb-check:$3 = 2.5
// gdb-command:continue
// NON IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$4 = {a = 3, b = 4, c = 5, d = 6, e = 7, f = 8, g = 9, h = 10}
// gdb-command:print b
// gdb-check:$5 = {a = 11, b = 12, c = 13, d = 14, e = 15, f = 16, g = 17, h = 18}
// gdb-command:continue
// BINDING
// gdb-command:print a
// gdb-check:$6 = 19
// gdb-command:print b
// gdb-check:$7 = 20
// gdb-command:print c
// gdb-check:$8 = 21.5
// gdb-command:continue
// ASSIGNMENT
// gdb-command:print a
// gdb-check:$9 = 22
// gdb-command:print b
// gdb-check:$10 = 23
// gdb-command:print c
// gdb-check:$11 = 24.5
// gdb-command:continue
// FUNCTION CALL
// gdb-command:print x
// gdb-check:$12 = 25
// gdb-command:print y
// gdb-check:$13 = 26
// gdb-command:print z
// gdb-check:$14 = 27.5
// gdb-command:continue
// EXPR
// gdb-command:print x
// gdb-check:$15 = 28
// gdb-command:print y
// gdb-check:$16 = 29
// gdb-command:print z
// gdb-check:$17 = 30.5
// gdb-command:continue
// RETURN EXPR
// gdb-command:print x
// gdb-check:$18 = 31
// gdb-command:print y
// gdb-check:$19 = 32
// gdb-command:print z
// gdb-check:$20 = 33.5
// gdb-command:continue
// ARITHMETIC EXPR
// gdb-command:print x
// gdb-check:$21 = 34
// gdb-command:print y
// gdb-check:$22 = 35
// gdb-command:print z
// gdb-check:$23 = 36.5
// gdb-command:continue
// IF EXPR
// gdb-command:print x
// gdb-check:$24 = 37
// gdb-command:print y
// gdb-check:$25 = 38
// gdb-command:print z
// gdb-check:$26 = 39.5
// gdb-command:continue
// WHILE EXPR
// gdb-command:print x
// gdb-check:$27 = 40
// gdb-command:print y
// gdb-check:$28 = 41
// gdb-command:print z
// gdb-check:$29 = 42
// gdb-command:continue
// LOOP EXPR
// gdb-command:print x
// gdb-check:$30 = 43
// gdb-command:print y
// gdb-check:$31 = 44
// gdb-command:print z
// gdb-check:$32 = 45
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
|
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: int, b: bool, c: f64) {
::std::old_io::print("") // #break
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
::std::old_io::print("") // #break
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0; // #break
::std::old_io::print("")
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b; // #break
::std::old_io::print("")
}
fn function_call(x: u64, y: u64, z: f64) {
std::old_io::stdio::print("Hi!") // #break
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x // #break
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x; // #break
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y // #break
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 { // #break
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y > 1000 { // #break
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop { // #break
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main() {
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
// lldb-command:print a
// lldb-check:[...]$8 = 22
|
random_line_split
|
function-arg-initialization.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.
// min-lldb-version: 310
// This test case checks if function arguments already have the correct value when breaking at the
// first line of the function, that is if the function prologue has already been executed at the
// first line. Note that because of the __morestack part of the prologue GDB incorrectly breaks at
// before the arguments have been properly loaded when setting the breakpoint via the function name.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$1 = 1
// gdb-command:print b
// gdb-check:$2 = true
// gdb-command:print c
// gdb-check:$3 = 2.5
// gdb-command:continue
// NON IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$4 = {a = 3, b = 4, c = 5, d = 6, e = 7, f = 8, g = 9, h = 10}
// gdb-command:print b
// gdb-check:$5 = {a = 11, b = 12, c = 13, d = 14, e = 15, f = 16, g = 17, h = 18}
// gdb-command:continue
// BINDING
// gdb-command:print a
// gdb-check:$6 = 19
// gdb-command:print b
// gdb-check:$7 = 20
// gdb-command:print c
// gdb-check:$8 = 21.5
// gdb-command:continue
// ASSIGNMENT
// gdb-command:print a
// gdb-check:$9 = 22
// gdb-command:print b
// gdb-check:$10 = 23
// gdb-command:print c
// gdb-check:$11 = 24.5
// gdb-command:continue
// FUNCTION CALL
// gdb-command:print x
// gdb-check:$12 = 25
// gdb-command:print y
// gdb-check:$13 = 26
// gdb-command:print z
// gdb-check:$14 = 27.5
// gdb-command:continue
// EXPR
// gdb-command:print x
// gdb-check:$15 = 28
// gdb-command:print y
// gdb-check:$16 = 29
// gdb-command:print z
// gdb-check:$17 = 30.5
// gdb-command:continue
// RETURN EXPR
// gdb-command:print x
// gdb-check:$18 = 31
// gdb-command:print y
// gdb-check:$19 = 32
// gdb-command:print z
// gdb-check:$20 = 33.5
// gdb-command:continue
// ARITHMETIC EXPR
// gdb-command:print x
// gdb-check:$21 = 34
// gdb-command:print y
// gdb-check:$22 = 35
// gdb-command:print z
// gdb-check:$23 = 36.5
// gdb-command:continue
// IF EXPR
// gdb-command:print x
// gdb-check:$24 = 37
// gdb-command:print y
// gdb-check:$25 = 38
// gdb-command:print z
// gdb-check:$26 = 39.5
// gdb-command:continue
// WHILE EXPR
// gdb-command:print x
// gdb-check:$27 = 40
// gdb-command:print y
// gdb-check:$28 = 41
// gdb-command:print z
// gdb-check:$29 = 42
// gdb-command:continue
// LOOP EXPR
// gdb-command:print x
// gdb-check:$30 = 43
// gdb-command:print y
// gdb-check:$31 = 44
// gdb-command:print z
// gdb-check:$32 = 45
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn
|
(a: int, b: bool, c: f64) {
::std::old_io::print("") // #break
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
::std::old_io::print("") // #break
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0; // #break
::std::old_io::print("")
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b; // #break
::std::old_io::print("")
}
fn function_call(x: u64, y: u64, z: f64) {
std::old_io::stdio::print("Hi!") // #break
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x // #break
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x; // #break
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y // #break
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 { // #break
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y > 1000 { // #break
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop { // #break
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main() {
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
immediate_args
|
identifier_name
|
function-arg-initialization.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.
// min-lldb-version: 310
// This test case checks if function arguments already have the correct value when breaking at the
// first line of the function, that is if the function prologue has already been executed at the
// first line. Note that because of the __morestack part of the prologue GDB incorrectly breaks at
// before the arguments have been properly loaded when setting the breakpoint via the function name.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$1 = 1
// gdb-command:print b
// gdb-check:$2 = true
// gdb-command:print c
// gdb-check:$3 = 2.5
// gdb-command:continue
// NON IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$4 = {a = 3, b = 4, c = 5, d = 6, e = 7, f = 8, g = 9, h = 10}
// gdb-command:print b
// gdb-check:$5 = {a = 11, b = 12, c = 13, d = 14, e = 15, f = 16, g = 17, h = 18}
// gdb-command:continue
// BINDING
// gdb-command:print a
// gdb-check:$6 = 19
// gdb-command:print b
// gdb-check:$7 = 20
// gdb-command:print c
// gdb-check:$8 = 21.5
// gdb-command:continue
// ASSIGNMENT
// gdb-command:print a
// gdb-check:$9 = 22
// gdb-command:print b
// gdb-check:$10 = 23
// gdb-command:print c
// gdb-check:$11 = 24.5
// gdb-command:continue
// FUNCTION CALL
// gdb-command:print x
// gdb-check:$12 = 25
// gdb-command:print y
// gdb-check:$13 = 26
// gdb-command:print z
// gdb-check:$14 = 27.5
// gdb-command:continue
// EXPR
// gdb-command:print x
// gdb-check:$15 = 28
// gdb-command:print y
// gdb-check:$16 = 29
// gdb-command:print z
// gdb-check:$17 = 30.5
// gdb-command:continue
// RETURN EXPR
// gdb-command:print x
// gdb-check:$18 = 31
// gdb-command:print y
// gdb-check:$19 = 32
// gdb-command:print z
// gdb-check:$20 = 33.5
// gdb-command:continue
// ARITHMETIC EXPR
// gdb-command:print x
// gdb-check:$21 = 34
// gdb-command:print y
// gdb-check:$22 = 35
// gdb-command:print z
// gdb-check:$23 = 36.5
// gdb-command:continue
// IF EXPR
// gdb-command:print x
// gdb-check:$24 = 37
// gdb-command:print y
// gdb-check:$25 = 38
// gdb-command:print z
// gdb-check:$26 = 39.5
// gdb-command:continue
// WHILE EXPR
// gdb-command:print x
// gdb-check:$27 = 40
// gdb-command:print y
// gdb-check:$28 = 41
// gdb-command:print z
// gdb-check:$29 = 42
// gdb-command:continue
// LOOP EXPR
// gdb-command:print x
// gdb-check:$30 = 43
// gdb-command:print y
// gdb-check:$31 = 44
// gdb-command:print z
// gdb-check:$32 = 45
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: int, b: bool, c: f64) {
::std::old_io::print("") // #break
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
::std::old_io::print("") // #break
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0; // #break
::std::old_io::print("")
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b; // #break
::std::old_io::print("")
}
fn function_call(x: u64, y: u64, z: f64) {
std::old_io::stdio::print("Hi!") // #break
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x // #break
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x; // #break
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y // #break
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 { // #break
x
} else {
y
}
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y > 1000 { // #break
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop { // #break
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main()
|
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
{
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
|
identifier_body
|
function-arg-initialization.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.
// min-lldb-version: 310
// This test case checks if function arguments already have the correct value when breaking at the
// first line of the function, that is if the function prologue has already been executed at the
// first line. Note that because of the __morestack part of the prologue GDB incorrectly breaks at
// before the arguments have been properly loaded when setting the breakpoint via the function name.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$1 = 1
// gdb-command:print b
// gdb-check:$2 = true
// gdb-command:print c
// gdb-check:$3 = 2.5
// gdb-command:continue
// NON IMMEDIATE ARGS
// gdb-command:print a
// gdb-check:$4 = {a = 3, b = 4, c = 5, d = 6, e = 7, f = 8, g = 9, h = 10}
// gdb-command:print b
// gdb-check:$5 = {a = 11, b = 12, c = 13, d = 14, e = 15, f = 16, g = 17, h = 18}
// gdb-command:continue
// BINDING
// gdb-command:print a
// gdb-check:$6 = 19
// gdb-command:print b
// gdb-check:$7 = 20
// gdb-command:print c
// gdb-check:$8 = 21.5
// gdb-command:continue
// ASSIGNMENT
// gdb-command:print a
// gdb-check:$9 = 22
// gdb-command:print b
// gdb-check:$10 = 23
// gdb-command:print c
// gdb-check:$11 = 24.5
// gdb-command:continue
// FUNCTION CALL
// gdb-command:print x
// gdb-check:$12 = 25
// gdb-command:print y
// gdb-check:$13 = 26
// gdb-command:print z
// gdb-check:$14 = 27.5
// gdb-command:continue
// EXPR
// gdb-command:print x
// gdb-check:$15 = 28
// gdb-command:print y
// gdb-check:$16 = 29
// gdb-command:print z
// gdb-check:$17 = 30.5
// gdb-command:continue
// RETURN EXPR
// gdb-command:print x
// gdb-check:$18 = 31
// gdb-command:print y
// gdb-check:$19 = 32
// gdb-command:print z
// gdb-check:$20 = 33.5
// gdb-command:continue
// ARITHMETIC EXPR
// gdb-command:print x
// gdb-check:$21 = 34
// gdb-command:print y
// gdb-check:$22 = 35
// gdb-command:print z
// gdb-check:$23 = 36.5
// gdb-command:continue
// IF EXPR
// gdb-command:print x
// gdb-check:$24 = 37
// gdb-command:print y
// gdb-check:$25 = 38
// gdb-command:print z
// gdb-check:$26 = 39.5
// gdb-command:continue
// WHILE EXPR
// gdb-command:print x
// gdb-check:$27 = 40
// gdb-command:print y
// gdb-check:$28 = 41
// gdb-command:print z
// gdb-check:$29 = 42
// gdb-command:continue
// LOOP EXPR
// gdb-command:print x
// gdb-check:$30 = 43
// gdb-command:print y
// gdb-check:$31 = 44
// gdb-command:print z
// gdb-check:$32 = 45
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$0 = 1
// lldb-command:print b
// lldb-check:[...]$1 = true
// lldb-command:print c
// lldb-check:[...]$2 = 2.5
// lldb-command:continue
// NON IMMEDIATE ARGS
// lldb-command:print a
// lldb-check:[...]$3 = BigStruct { a: 3, b: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
// lldb-command:print b
// lldb-check:[...]$4 = BigStruct { a: 11, b: 12, c: 13, d: 14, e: 15, f: 16, g: 17, h: 18 }
// lldb-command:continue
// BINDING
// lldb-command:print a
// lldb-check:[...]$5 = 19
// lldb-command:print b
// lldb-check:[...]$6 = 20
// lldb-command:print c
// lldb-check:[...]$7 = 21.5
// lldb-command:continue
// ASSIGNMENT
// lldb-command:print a
// lldb-check:[...]$8 = 22
// lldb-command:print b
// lldb-check:[...]$9 = 23
// lldb-command:print c
// lldb-check:[...]$10 = 24.5
// lldb-command:continue
// FUNCTION CALL
// lldb-command:print x
// lldb-check:[...]$11 = 25
// lldb-command:print y
// lldb-check:[...]$12 = 26
// lldb-command:print z
// lldb-check:[...]$13 = 27.5
// lldb-command:continue
// EXPR
// lldb-command:print x
// lldb-check:[...]$14 = 28
// lldb-command:print y
// lldb-check:[...]$15 = 29
// lldb-command:print z
// lldb-check:[...]$16 = 30.5
// lldb-command:continue
// RETURN EXPR
// lldb-command:print x
// lldb-check:[...]$17 = 31
// lldb-command:print y
// lldb-check:[...]$18 = 32
// lldb-command:print z
// lldb-check:[...]$19 = 33.5
// lldb-command:continue
// ARITHMETIC EXPR
// lldb-command:print x
// lldb-check:[...]$20 = 34
// lldb-command:print y
// lldb-check:[...]$21 = 35
// lldb-command:print z
// lldb-check:[...]$22 = 36.5
// lldb-command:continue
// IF EXPR
// lldb-command:print x
// lldb-check:[...]$23 = 37
// lldb-command:print y
// lldb-check:[...]$24 = 38
// lldb-command:print z
// lldb-check:[...]$25 = 39.5
// lldb-command:continue
// WHILE EXPR
// lldb-command:print x
// lldb-check:[...]$26 = 40
// lldb-command:print y
// lldb-check:[...]$27 = 41
// lldb-command:print z
// lldb-check:[...]$28 = 42
// lldb-command:continue
// LOOP EXPR
// lldb-command:print x
// lldb-check:[...]$29 = 43
// lldb-command:print y
// lldb-check:[...]$30 = 44
// lldb-command:print z
// lldb-check:[...]$31 = 45
// lldb-command:continue
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
fn immediate_args(a: int, b: bool, c: f64) {
::std::old_io::print("") // #break
}
struct BigStruct {
a: u64,
b: u64,
c: u64,
d: u64,
e: u64,
f: u64,
g: u64,
h: u64
}
fn non_immediate_args(a: BigStruct, b: BigStruct) {
::std::old_io::print("") // #break
}
fn binding(a: i64, b: u64, c: f64) {
let x = 0; // #break
::std::old_io::print("")
}
fn assignment(mut a: u64, b: u64, c: f64) {
a = b; // #break
::std::old_io::print("")
}
fn function_call(x: u64, y: u64, z: f64) {
std::old_io::stdio::print("Hi!") // #break
}
fn identifier(x: u64, y: u64, z: f64) -> u64 {
x // #break
}
fn return_expr(x: u64, y: u64, z: f64) -> u64 {
return x; // #break
}
fn arithmetic_expr(x: u64, y: u64, z: f64) -> u64 {
x + y // #break
}
fn if_expr(x: u64, y: u64, z: f64) -> u64 {
if x + y < 1000 { // #break
x
} else
|
}
fn while_expr(mut x: u64, y: u64, z: u64) -> u64 {
while x + y > 1000 { // #break
x += z
}
return x;
}
fn loop_expr(mut x: u64, y: u64, z: u64) -> u64 {
loop { // #break
x += z;
if x + y > 1000 {
return x;
}
}
}
fn main() {
immediate_args(1, true, 2.5);
non_immediate_args(
BigStruct {
a: 3,
b: 4,
c: 5,
d: 6,
e: 7,
f: 8,
g: 9,
h: 10
},
BigStruct {
a: 11,
b: 12,
c: 13,
d: 14,
e: 15,
f: 16,
g: 17,
h: 18
}
);
binding(19, 20, 21.5);
assignment(22, 23, 24.5);
function_call(25, 26, 27.5);
identifier(28, 29, 30.5);
return_expr(31, 32, 33.5);
arithmetic_expr(34, 35, 36.5);
if_expr(37, 38, 39.5);
while_expr(40, 41, 42);
loop_expr(43, 44, 45);
}
|
{
y
}
|
conditional_block
|
lib.rs
|
#[macro_use] extern crate lazy_static;
extern crate regex;
extern crate rusqlite;
pub mod weblog;
use regex::Regex;
use weblog::Weblog;
use rusqlite::Connection;
// Take an unprocessed string representing a single line of an Apache log,
// attempt to match the various components of the string, and generate a Weblog
// struct from them. Returns None on error.
pub fn parse_weblog(line: &str) -> Option<Weblog> {
lazy_static! {
static ref RE: Regex = Regex::new("(?x)
(\\S+)\\s
(\\S+)\\s
(\\S+)\\s
\\[(\\d{2}/\\w+/\\d{4}:\\d{2}:\\d{2}:\\d{2}\\s+.+?)\\]\\s
\"(\\w+\\s\\S+\\s\\w+/\\d+\\.\\d+)\"\\s
(\\d+)\\s
(\\d+)\\s
|
\"(.+)\"
").expect("Unable to compile Regex");
}
// This used to print to stdout before returning None, but the calling
// program should do the printing.
let cap = match RE.captures(line) {
Some(x) => x,
None => {
return None;
}
};
let logline = Weblog::new(
cap[1].to_string(),
cap[4].to_string(),
cap[5].to_string(),
cap[6].parse::<i32>().unwrap_or(0),
cap[7].parse::<i32>().unwrap_or(0),
cap[8].to_string(),
cap[9].to_string()
);
Some(logline)
}
// Given a Weblog struct, connect to the database and create a new entry.
// Returns true on success, false on failure.
// TODO: Abstract out the connection part so the DB name isn't hard-coded
pub fn create(log: &Weblog) -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("INSERT INTO weblogs
(ipaddr, date, request, code, size, referer, agent)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[&log.ip, &log.date, &log.req, &log.code,
&log.size, &log.referer, &log.agent]) {
Ok(_) => return true,
Err(err) => {
println!("Insert failed: {}", err);
return false;
}
}
}
// Given an integer, connect to the database and retrieve that number of
// entries. Returns a Vec of Weblog structs.
pub fn fetch(count: i32) -> Vec<Weblog> {
let conn = Connection::open("test.db").expect("Cannot open database?");
let mut stmt = conn.prepare("SELECT * FROM weblogs LIMIT (?)")
.expect("Unable to prepare SELECT statement");
let log_iter = stmt.query_map(&[&count], |row| {
Weblog {
ip: row.get(0),
date: row.get(1),
req: row.get(2),
code: row.get(3),
size: row.get(4),
referer: row.get(5),
agent: row.get(6)
}
}).expect("Something went terribly wrong!");
let mut v: Vec<Weblog> = vec![];
for log in log_iter {
v.push(log.unwrap());
}
v
}
// Connect to the database and create the weblogs table
pub fn create_table() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("CREATE TABLE weblogs (
ipaddr varchar(50) not null,
date varchar(50) not null,
request varchar(255) not null,
code int not null,
size int not null default 0,
referer varchar(255) not null,
agent varchar(255) not null,
primary key (ipaddr, date))", &[]) {
Ok(_) => {
println!("Created table 'weblogs'.");
true
},
Err(e) => {
println!("Error creating table: {}", e);
false
}
}
}
// Connect to the database and drop the weblogs table
pub fn drop_table() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("DROP TABLE weblogs", &[]) {
Ok(_) => {
println!("Dropped table 'weblogs'.");
true
},
Err(e) => {
println!("Error dropping table: {}", e);
false
}
}
}
// Check the status of the database
pub fn db_status() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
// Just grab a count from the weblogs table
match conn.query_row::<i32, _>("SELECT COUNT(*) FROM weblogs", &[], |row| { row.get(0) }) {
Ok(x) => {
println!("Database OK! Found {} rows in weblogs table", x);
return true;
},
Err(e) => {
println!("Error checking status: {}", e);
return false;
}
};
}
|
\"(\\S+)\"\\s
|
random_line_split
|
lib.rs
|
#[macro_use] extern crate lazy_static;
extern crate regex;
extern crate rusqlite;
pub mod weblog;
use regex::Regex;
use weblog::Weblog;
use rusqlite::Connection;
// Take an unprocessed string representing a single line of an Apache log,
// attempt to match the various components of the string, and generate a Weblog
// struct from them. Returns None on error.
pub fn parse_weblog(line: &str) -> Option<Weblog>
|
return None;
}
};
let logline = Weblog::new(
cap[1].to_string(),
cap[4].to_string(),
cap[5].to_string(),
cap[6].parse::<i32>().unwrap_or(0),
cap[7].parse::<i32>().unwrap_or(0),
cap[8].to_string(),
cap[9].to_string()
);
Some(logline)
}
// Given a Weblog struct, connect to the database and create a new entry.
// Returns true on success, false on failure.
// TODO: Abstract out the connection part so the DB name isn't hard-coded
pub fn create(log: &Weblog) -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("INSERT INTO weblogs
(ipaddr, date, request, code, size, referer, agent)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[&log.ip, &log.date, &log.req, &log.code,
&log.size, &log.referer, &log.agent]) {
Ok(_) => return true,
Err(err) => {
println!("Insert failed: {}", err);
return false;
}
}
}
// Given an integer, connect to the database and retrieve that number of
// entries. Returns a Vec of Weblog structs.
pub fn fetch(count: i32) -> Vec<Weblog> {
let conn = Connection::open("test.db").expect("Cannot open database?");
let mut stmt = conn.prepare("SELECT * FROM weblogs LIMIT (?)")
.expect("Unable to prepare SELECT statement");
let log_iter = stmt.query_map(&[&count], |row| {
Weblog {
ip: row.get(0),
date: row.get(1),
req: row.get(2),
code: row.get(3),
size: row.get(4),
referer: row.get(5),
agent: row.get(6)
}
}).expect("Something went terribly wrong!");
let mut v: Vec<Weblog> = vec![];
for log in log_iter {
v.push(log.unwrap());
}
v
}
// Connect to the database and create the weblogs table
pub fn create_table() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("CREATE TABLE weblogs (
ipaddr varchar(50) not null,
date varchar(50) not null,
request varchar(255) not null,
code int not null,
size int not null default 0,
referer varchar(255) not null,
agent varchar(255) not null,
primary key (ipaddr, date))", &[]) {
Ok(_) => {
println!("Created table 'weblogs'.");
true
},
Err(e) => {
println!("Error creating table: {}", e);
false
}
}
}
// Connect to the database and drop the weblogs table
pub fn drop_table() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("DROP TABLE weblogs", &[]) {
Ok(_) => {
println!("Dropped table 'weblogs'.");
true
},
Err(e) => {
println!("Error dropping table: {}", e);
false
}
}
}
// Check the status of the database
pub fn db_status() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
// Just grab a count from the weblogs table
match conn.query_row::<i32, _>("SELECT COUNT(*) FROM weblogs", &[], |row| { row.get(0) }) {
Ok(x) => {
println!("Database OK! Found {} rows in weblogs table", x);
return true;
},
Err(e) => {
println!("Error checking status: {}", e);
return false;
}
};
}
|
{
lazy_static! {
static ref RE: Regex = Regex::new("(?x)
(\\S+)\\s
(\\S+)\\s
(\\S+)\\s
\\[(\\d{2}/\\w+/\\d{4}:\\d{2}:\\d{2}:\\d{2}\\s+.+?)\\]\\s
\"(\\w+\\s\\S+\\s\\w+/\\d+\\.\\d+)\"\\s
(\\d+)\\s
(\\d+)\\s
\"(\\S+)\"\\s
\"(.+)\"
").expect("Unable to compile Regex");
}
// This used to print to stdout before returning None, but the calling
// program should do the printing.
let cap = match RE.captures(line) {
Some(x) => x,
None => {
|
identifier_body
|
lib.rs
|
#[macro_use] extern crate lazy_static;
extern crate regex;
extern crate rusqlite;
pub mod weblog;
use regex::Regex;
use weblog::Weblog;
use rusqlite::Connection;
// Take an unprocessed string representing a single line of an Apache log,
// attempt to match the various components of the string, and generate a Weblog
// struct from them. Returns None on error.
pub fn parse_weblog(line: &str) -> Option<Weblog> {
lazy_static! {
static ref RE: Regex = Regex::new("(?x)
(\\S+)\\s
(\\S+)\\s
(\\S+)\\s
\\[(\\d{2}/\\w+/\\d{4}:\\d{2}:\\d{2}:\\d{2}\\s+.+?)\\]\\s
\"(\\w+\\s\\S+\\s\\w+/\\d+\\.\\d+)\"\\s
(\\d+)\\s
(\\d+)\\s
\"(\\S+)\"\\s
\"(.+)\"
").expect("Unable to compile Regex");
}
// This used to print to stdout before returning None, but the calling
// program should do the printing.
let cap = match RE.captures(line) {
Some(x) => x,
None => {
return None;
}
};
let logline = Weblog::new(
cap[1].to_string(),
cap[4].to_string(),
cap[5].to_string(),
cap[6].parse::<i32>().unwrap_or(0),
cap[7].parse::<i32>().unwrap_or(0),
cap[8].to_string(),
cap[9].to_string()
);
Some(logline)
}
// Given a Weblog struct, connect to the database and create a new entry.
// Returns true on success, false on failure.
// TODO: Abstract out the connection part so the DB name isn't hard-coded
pub fn create(log: &Weblog) -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("INSERT INTO weblogs
(ipaddr, date, request, code, size, referer, agent)
VALUES ($1, $2, $3, $4, $5, $6, $7)",
&[&log.ip, &log.date, &log.req, &log.code,
&log.size, &log.referer, &log.agent]) {
Ok(_) => return true,
Err(err) => {
println!("Insert failed: {}", err);
return false;
}
}
}
// Given an integer, connect to the database and retrieve that number of
// entries. Returns a Vec of Weblog structs.
pub fn
|
(count: i32) -> Vec<Weblog> {
let conn = Connection::open("test.db").expect("Cannot open database?");
let mut stmt = conn.prepare("SELECT * FROM weblogs LIMIT (?)")
.expect("Unable to prepare SELECT statement");
let log_iter = stmt.query_map(&[&count], |row| {
Weblog {
ip: row.get(0),
date: row.get(1),
req: row.get(2),
code: row.get(3),
size: row.get(4),
referer: row.get(5),
agent: row.get(6)
}
}).expect("Something went terribly wrong!");
let mut v: Vec<Weblog> = vec![];
for log in log_iter {
v.push(log.unwrap());
}
v
}
// Connect to the database and create the weblogs table
pub fn create_table() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("CREATE TABLE weblogs (
ipaddr varchar(50) not null,
date varchar(50) not null,
request varchar(255) not null,
code int not null,
size int not null default 0,
referer varchar(255) not null,
agent varchar(255) not null,
primary key (ipaddr, date))", &[]) {
Ok(_) => {
println!("Created table 'weblogs'.");
true
},
Err(e) => {
println!("Error creating table: {}", e);
false
}
}
}
// Connect to the database and drop the weblogs table
pub fn drop_table() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
match conn.execute("DROP TABLE weblogs", &[]) {
Ok(_) => {
println!("Dropped table 'weblogs'.");
true
},
Err(e) => {
println!("Error dropping table: {}", e);
false
}
}
}
// Check the status of the database
pub fn db_status() -> bool {
let conn = Connection::open("test.db").expect("Cannot open database?");
// Just grab a count from the weblogs table
match conn.query_row::<i32, _>("SELECT COUNT(*) FROM weblogs", &[], |row| { row.get(0) }) {
Ok(x) => {
println!("Database OK! Found {} rows in weblogs table", x);
return true;
},
Err(e) => {
println!("Error checking status: {}", e);
return false;
}
};
}
|
fetch
|
identifier_name
|
compile.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.
// Enable this to squash warnings due to exporting pieces of the representation
// for use with the regex! macro. See lib.rs for explanation.
use std::cmp;
use parse;
use parse::{
Flags, FLAG_EMPTY,
Nothing, Literal, Dot, AstClass, Begin, End, WordBoundary, Capture, Cat, Alt,
Rep,
ZeroOne, ZeroMore, OneMore,
};
type InstIdx = uint;
#[deriving(Show, Clone)]
pub enum Inst {
// When a Match instruction is executed, the current thread is successful.
Match,
// The OneChar instruction matches a literal character.
// The flags indicate whether to do a case insensitive match.
OneChar(char, Flags),
// The CharClass instruction tries to match one input character against
// the range of characters given.
// The flags indicate whether to do a case insensitive match and whether
// the character class is negated or not.
CharClass(Vec<(char, char)>, Flags),
// Matches any character except new lines.
// The flags indicate whether to include the '\n' character.
Any(Flags),
// Matches the beginning of the string, consumes no characters.
// The flags indicate whether it matches if the preceding character
// is a new line.
EmptyBegin(Flags),
// Matches the end of the string, consumes no characters.
// The flags indicate whether it matches if the proceeding character
// is a new line.
EmptyEnd(Flags),
// Matches a word boundary (\w on one side and \W \A or \z on the other),
// and consumes no character.
// The flags indicate whether this matches a word boundary or something
// that isn't a word boundary.
EmptyWordBoundary(Flags),
// Saves the current position in the input string to the Nth save slot.
Save(uint),
// Jumps to the instruction at the index given.
Jump(InstIdx),
// Jumps to the instruction at the first index given. If that leads to
// a failing state, then the instruction at the second index given is
// tried.
Split(InstIdx, InstIdx),
}
/// Program represents a compiled regular expression. Once an expression is
/// compiled, its representation is immutable and will never change.
///
/// All of the data in a compiled expression is wrapped in "MaybeStatic" or
/// "MaybeOwned" types so that a `Program` can be represented as static data.
/// (This makes it convenient and efficient for use with the `regex!` macro.)
#[deriving(Clone)]
pub struct Program {
/// A sequence of instructions.
pub insts: Vec<Inst>,
/// If the regular expression requires a literal prefix in order to have a
/// match, that prefix is stored here. (It's used in the VM to implement
/// an optimization.)
pub prefix: String,
}
impl Program {
/// Compiles a Regex given its AST.
pub fn new(ast: parse::Ast) -> (Program, Vec<Option<String>>) {
let mut c = Compiler {
insts: Vec::with_capacity(100),
names: Vec::with_capacity(10),
};
c.insts.push(Save(0));
c.compile(ast);
c.insts.push(Save(1));
c.insts.push(Match);
// Try to discover a literal string prefix.
// This is a bit hacky since we have to skip over the initial
// 'Save' instruction.
let mut pre = String::with_capacity(5);
for inst in c.insts.slice_from(1).iter() {
match *inst {
OneChar(c, FLAG_EMPTY) => pre.push(c),
_ => break
}
}
let Compiler { insts, names } = c;
let prog = Program {
insts: insts,
prefix: pre,
};
(prog, names)
}
/// Returns the total number of capture groups in the regular expression.
/// This includes the zeroth capture.
pub fn num_captures(&self) -> uint {
let mut n = 0;
for inst in self.insts.iter() {
match *inst {
Save(c) => n = cmp::max(n, c+1),
_ => {}
}
}
// There's exactly 2 Save slots for every capture.
n / 2
}
}
struct Compiler<'r> {
insts: Vec<Inst>,
names: Vec<Option<String>>,
}
// The compiler implemented here is extremely simple. Most of the complexity
// in this crate is in the parser or the VM.
// The only tricky thing here is patching jump/split instructions to point to
// the right instruction.
impl<'r> Compiler<'r> {
fn compile(&mut self, ast: parse::Ast) {
match ast {
Nothing => {},
Literal(c, flags) => self.push(OneChar(c, flags)),
Dot(nl) => self.push(Any(nl)),
AstClass(ranges, flags) =>
self.push(CharClass(ranges, flags)),
Begin(flags) => self.push(EmptyBegin(flags)),
End(flags) => self.push(EmptyEnd(flags)),
WordBoundary(flags) => self.push(EmptyWordBoundary(flags)),
Capture(cap, name, x) => {
let len = self.names.len();
if cap >= len {
self.names.grow(10 + cap - len, None)
}
*self.names.get_mut(cap) = name;
self.push(Save(2 * cap));
self.compile(*x);
self.push(Save(2 * cap + 1));
}
Cat(xs) => {
for x in xs.into_iter() {
self.compile(x)
}
}
Alt(x, y) => {
let split = self.empty_split(); // push: split 0, 0
let j1 = self.insts.len();
self.compile(*x); // push: insts for x
let jmp = self.empty_jump(); // push: jmp 0
let j2 = self.insts.len();
self.compile(*y); // push: insts for y
let j3 = self.insts.len();
self.set_split(split, j1, j2); // split 0, 0 -> split j1, j2
self.set_jump(jmp, j3); // jmp 0 -> jmp j3
}
Rep(x, ZeroOne, g) =>
|
Rep(x, ZeroMore, g) => {
let j1 = self.insts.len();
let split = self.empty_split();
let j2 = self.insts.len();
self.compile(*x);
let jmp = self.empty_jump();
let j3 = self.insts.len();
self.set_jump(jmp, j1);
if g.is_greedy() {
self.set_split(split, j2, j3);
} else {
self.set_split(split, j3, j2);
}
}
Rep(x, OneMore, g) => {
let j1 = self.insts.len();
self.compile(*x);
let split = self.empty_split();
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
}
}
/// Appends the given instruction to the program.
#[inline]
fn push(&mut self, x: Inst) {
self.insts.push(x)
}
/// Appends an *empty* `Split` instruction to the program and returns
/// the index of that instruction. (The index can then be used to "patch"
/// the actual locations of the split in later.)
#[inline]
fn empty_split(&mut self) -> InstIdx {
self.insts.push(Split(0, 0));
self.insts.len() - 1
}
/// Sets the left and right locations of a `Split` instruction at index
/// `i` to `pc1` and `pc2`, respectively.
/// If the instruction at index `i` isn't a `Split` instruction, then
/// `fail!` is called.
#[inline]
fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) {
let split = self.insts.get_mut(i);
match *split {
Split(_, _) => *split = Split(pc1, pc2),
_ => fail!("BUG: Invalid split index."),
}
}
/// Appends an *empty* `Jump` instruction to the program and returns the
/// index of that instruction.
#[inline]
fn empty_jump(&mut self) -> InstIdx {
self.insts.push(Jump(0));
self.insts.len() - 1
}
/// Sets the location of a `Jump` instruction at index `i` to `pc`.
/// If the instruction at index `i` isn't a `Jump` instruction, then
/// `fail!` is called.
#[inline]
fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
let jmp = self.insts.get_mut(i);
match *jmp {
Jump(_) => *jmp = Jump(pc),
_ => fail!("BUG: Invalid jump index."),
}
}
}
|
{
let split = self.empty_split();
let j1 = self.insts.len();
self.compile(*x);
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
|
conditional_block
|
compile.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.
// Enable this to squash warnings due to exporting pieces of the representation
// for use with the regex! macro. See lib.rs for explanation.
use std::cmp;
use parse;
use parse::{
Flags, FLAG_EMPTY,
Nothing, Literal, Dot, AstClass, Begin, End, WordBoundary, Capture, Cat, Alt,
Rep,
ZeroOne, ZeroMore, OneMore,
};
type InstIdx = uint;
#[deriving(Show, Clone)]
pub enum Inst {
// When a Match instruction is executed, the current thread is successful.
Match,
// The OneChar instruction matches a literal character.
// The flags indicate whether to do a case insensitive match.
OneChar(char, Flags),
// The CharClass instruction tries to match one input character against
// the range of characters given.
// The flags indicate whether to do a case insensitive match and whether
// the character class is negated or not.
CharClass(Vec<(char, char)>, Flags),
// Matches any character except new lines.
// The flags indicate whether to include the '\n' character.
Any(Flags),
// Matches the beginning of the string, consumes no characters.
// The flags indicate whether it matches if the preceding character
// is a new line.
|
EmptyEnd(Flags),
// Matches a word boundary (\w on one side and \W \A or \z on the other),
// and consumes no character.
// The flags indicate whether this matches a word boundary or something
// that isn't a word boundary.
EmptyWordBoundary(Flags),
// Saves the current position in the input string to the Nth save slot.
Save(uint),
// Jumps to the instruction at the index given.
Jump(InstIdx),
// Jumps to the instruction at the first index given. If that leads to
// a failing state, then the instruction at the second index given is
// tried.
Split(InstIdx, InstIdx),
}
/// Program represents a compiled regular expression. Once an expression is
/// compiled, its representation is immutable and will never change.
///
/// All of the data in a compiled expression is wrapped in "MaybeStatic" or
/// "MaybeOwned" types so that a `Program` can be represented as static data.
/// (This makes it convenient and efficient for use with the `regex!` macro.)
#[deriving(Clone)]
pub struct Program {
/// A sequence of instructions.
pub insts: Vec<Inst>,
/// If the regular expression requires a literal prefix in order to have a
/// match, that prefix is stored here. (It's used in the VM to implement
/// an optimization.)
pub prefix: String,
}
impl Program {
/// Compiles a Regex given its AST.
pub fn new(ast: parse::Ast) -> (Program, Vec<Option<String>>) {
let mut c = Compiler {
insts: Vec::with_capacity(100),
names: Vec::with_capacity(10),
};
c.insts.push(Save(0));
c.compile(ast);
c.insts.push(Save(1));
c.insts.push(Match);
// Try to discover a literal string prefix.
// This is a bit hacky since we have to skip over the initial
// 'Save' instruction.
let mut pre = String::with_capacity(5);
for inst in c.insts.slice_from(1).iter() {
match *inst {
OneChar(c, FLAG_EMPTY) => pre.push(c),
_ => break
}
}
let Compiler { insts, names } = c;
let prog = Program {
insts: insts,
prefix: pre,
};
(prog, names)
}
/// Returns the total number of capture groups in the regular expression.
/// This includes the zeroth capture.
pub fn num_captures(&self) -> uint {
let mut n = 0;
for inst in self.insts.iter() {
match *inst {
Save(c) => n = cmp::max(n, c+1),
_ => {}
}
}
// There's exactly 2 Save slots for every capture.
n / 2
}
}
struct Compiler<'r> {
insts: Vec<Inst>,
names: Vec<Option<String>>,
}
// The compiler implemented here is extremely simple. Most of the complexity
// in this crate is in the parser or the VM.
// The only tricky thing here is patching jump/split instructions to point to
// the right instruction.
impl<'r> Compiler<'r> {
fn compile(&mut self, ast: parse::Ast) {
match ast {
Nothing => {},
Literal(c, flags) => self.push(OneChar(c, flags)),
Dot(nl) => self.push(Any(nl)),
AstClass(ranges, flags) =>
self.push(CharClass(ranges, flags)),
Begin(flags) => self.push(EmptyBegin(flags)),
End(flags) => self.push(EmptyEnd(flags)),
WordBoundary(flags) => self.push(EmptyWordBoundary(flags)),
Capture(cap, name, x) => {
let len = self.names.len();
if cap >= len {
self.names.grow(10 + cap - len, None)
}
*self.names.get_mut(cap) = name;
self.push(Save(2 * cap));
self.compile(*x);
self.push(Save(2 * cap + 1));
}
Cat(xs) => {
for x in xs.into_iter() {
self.compile(x)
}
}
Alt(x, y) => {
let split = self.empty_split(); // push: split 0, 0
let j1 = self.insts.len();
self.compile(*x); // push: insts for x
let jmp = self.empty_jump(); // push: jmp 0
let j2 = self.insts.len();
self.compile(*y); // push: insts for y
let j3 = self.insts.len();
self.set_split(split, j1, j2); // split 0, 0 -> split j1, j2
self.set_jump(jmp, j3); // jmp 0 -> jmp j3
}
Rep(x, ZeroOne, g) => {
let split = self.empty_split();
let j1 = self.insts.len();
self.compile(*x);
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
Rep(x, ZeroMore, g) => {
let j1 = self.insts.len();
let split = self.empty_split();
let j2 = self.insts.len();
self.compile(*x);
let jmp = self.empty_jump();
let j3 = self.insts.len();
self.set_jump(jmp, j1);
if g.is_greedy() {
self.set_split(split, j2, j3);
} else {
self.set_split(split, j3, j2);
}
}
Rep(x, OneMore, g) => {
let j1 = self.insts.len();
self.compile(*x);
let split = self.empty_split();
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
}
}
/// Appends the given instruction to the program.
#[inline]
fn push(&mut self, x: Inst) {
self.insts.push(x)
}
/// Appends an *empty* `Split` instruction to the program and returns
/// the index of that instruction. (The index can then be used to "patch"
/// the actual locations of the split in later.)
#[inline]
fn empty_split(&mut self) -> InstIdx {
self.insts.push(Split(0, 0));
self.insts.len() - 1
}
/// Sets the left and right locations of a `Split` instruction at index
/// `i` to `pc1` and `pc2`, respectively.
/// If the instruction at index `i` isn't a `Split` instruction, then
/// `fail!` is called.
#[inline]
fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) {
let split = self.insts.get_mut(i);
match *split {
Split(_, _) => *split = Split(pc1, pc2),
_ => fail!("BUG: Invalid split index."),
}
}
/// Appends an *empty* `Jump` instruction to the program and returns the
/// index of that instruction.
#[inline]
fn empty_jump(&mut self) -> InstIdx {
self.insts.push(Jump(0));
self.insts.len() - 1
}
/// Sets the location of a `Jump` instruction at index `i` to `pc`.
/// If the instruction at index `i` isn't a `Jump` instruction, then
/// `fail!` is called.
#[inline]
fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
let jmp = self.insts.get_mut(i);
match *jmp {
Jump(_) => *jmp = Jump(pc),
_ => fail!("BUG: Invalid jump index."),
}
}
}
|
EmptyBegin(Flags),
// Matches the end of the string, consumes no characters.
// The flags indicate whether it matches if the proceeding character
// is a new line.
|
random_line_split
|
compile.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.
// Enable this to squash warnings due to exporting pieces of the representation
// for use with the regex! macro. See lib.rs for explanation.
use std::cmp;
use parse;
use parse::{
Flags, FLAG_EMPTY,
Nothing, Literal, Dot, AstClass, Begin, End, WordBoundary, Capture, Cat, Alt,
Rep,
ZeroOne, ZeroMore, OneMore,
};
type InstIdx = uint;
#[deriving(Show, Clone)]
pub enum Inst {
// When a Match instruction is executed, the current thread is successful.
Match,
// The OneChar instruction matches a literal character.
// The flags indicate whether to do a case insensitive match.
OneChar(char, Flags),
// The CharClass instruction tries to match one input character against
// the range of characters given.
// The flags indicate whether to do a case insensitive match and whether
// the character class is negated or not.
CharClass(Vec<(char, char)>, Flags),
// Matches any character except new lines.
// The flags indicate whether to include the '\n' character.
Any(Flags),
// Matches the beginning of the string, consumes no characters.
// The flags indicate whether it matches if the preceding character
// is a new line.
EmptyBegin(Flags),
// Matches the end of the string, consumes no characters.
// The flags indicate whether it matches if the proceeding character
// is a new line.
EmptyEnd(Flags),
// Matches a word boundary (\w on one side and \W \A or \z on the other),
// and consumes no character.
// The flags indicate whether this matches a word boundary or something
// that isn't a word boundary.
EmptyWordBoundary(Flags),
// Saves the current position in the input string to the Nth save slot.
Save(uint),
// Jumps to the instruction at the index given.
Jump(InstIdx),
// Jumps to the instruction at the first index given. If that leads to
// a failing state, then the instruction at the second index given is
// tried.
Split(InstIdx, InstIdx),
}
/// Program represents a compiled regular expression. Once an expression is
/// compiled, its representation is immutable and will never change.
///
/// All of the data in a compiled expression is wrapped in "MaybeStatic" or
/// "MaybeOwned" types so that a `Program` can be represented as static data.
/// (This makes it convenient and efficient for use with the `regex!` macro.)
#[deriving(Clone)]
pub struct Program {
/// A sequence of instructions.
pub insts: Vec<Inst>,
/// If the regular expression requires a literal prefix in order to have a
/// match, that prefix is stored here. (It's used in the VM to implement
/// an optimization.)
pub prefix: String,
}
impl Program {
/// Compiles a Regex given its AST.
pub fn new(ast: parse::Ast) -> (Program, Vec<Option<String>>) {
let mut c = Compiler {
insts: Vec::with_capacity(100),
names: Vec::with_capacity(10),
};
c.insts.push(Save(0));
c.compile(ast);
c.insts.push(Save(1));
c.insts.push(Match);
// Try to discover a literal string prefix.
// This is a bit hacky since we have to skip over the initial
// 'Save' instruction.
let mut pre = String::with_capacity(5);
for inst in c.insts.slice_from(1).iter() {
match *inst {
OneChar(c, FLAG_EMPTY) => pre.push(c),
_ => break
}
}
let Compiler { insts, names } = c;
let prog = Program {
insts: insts,
prefix: pre,
};
(prog, names)
}
/// Returns the total number of capture groups in the regular expression.
/// This includes the zeroth capture.
pub fn num_captures(&self) -> uint {
let mut n = 0;
for inst in self.insts.iter() {
match *inst {
Save(c) => n = cmp::max(n, c+1),
_ => {}
}
}
// There's exactly 2 Save slots for every capture.
n / 2
}
}
struct Compiler<'r> {
insts: Vec<Inst>,
names: Vec<Option<String>>,
}
// The compiler implemented here is extremely simple. Most of the complexity
// in this crate is in the parser or the VM.
// The only tricky thing here is patching jump/split instructions to point to
// the right instruction.
impl<'r> Compiler<'r> {
fn compile(&mut self, ast: parse::Ast) {
match ast {
Nothing => {},
Literal(c, flags) => self.push(OneChar(c, flags)),
Dot(nl) => self.push(Any(nl)),
AstClass(ranges, flags) =>
self.push(CharClass(ranges, flags)),
Begin(flags) => self.push(EmptyBegin(flags)),
End(flags) => self.push(EmptyEnd(flags)),
WordBoundary(flags) => self.push(EmptyWordBoundary(flags)),
Capture(cap, name, x) => {
let len = self.names.len();
if cap >= len {
self.names.grow(10 + cap - len, None)
}
*self.names.get_mut(cap) = name;
self.push(Save(2 * cap));
self.compile(*x);
self.push(Save(2 * cap + 1));
}
Cat(xs) => {
for x in xs.into_iter() {
self.compile(x)
}
}
Alt(x, y) => {
let split = self.empty_split(); // push: split 0, 0
let j1 = self.insts.len();
self.compile(*x); // push: insts for x
let jmp = self.empty_jump(); // push: jmp 0
let j2 = self.insts.len();
self.compile(*y); // push: insts for y
let j3 = self.insts.len();
self.set_split(split, j1, j2); // split 0, 0 -> split j1, j2
self.set_jump(jmp, j3); // jmp 0 -> jmp j3
}
Rep(x, ZeroOne, g) => {
let split = self.empty_split();
let j1 = self.insts.len();
self.compile(*x);
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
Rep(x, ZeroMore, g) => {
let j1 = self.insts.len();
let split = self.empty_split();
let j2 = self.insts.len();
self.compile(*x);
let jmp = self.empty_jump();
let j3 = self.insts.len();
self.set_jump(jmp, j1);
if g.is_greedy() {
self.set_split(split, j2, j3);
} else {
self.set_split(split, j3, j2);
}
}
Rep(x, OneMore, g) => {
let j1 = self.insts.len();
self.compile(*x);
let split = self.empty_split();
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
}
}
/// Appends the given instruction to the program.
#[inline]
fn push(&mut self, x: Inst) {
self.insts.push(x)
}
/// Appends an *empty* `Split` instruction to the program and returns
/// the index of that instruction. (The index can then be used to "patch"
/// the actual locations of the split in later.)
#[inline]
fn empty_split(&mut self) -> InstIdx {
self.insts.push(Split(0, 0));
self.insts.len() - 1
}
/// Sets the left and right locations of a `Split` instruction at index
/// `i` to `pc1` and `pc2`, respectively.
/// If the instruction at index `i` isn't a `Split` instruction, then
/// `fail!` is called.
#[inline]
fn set_split(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx)
|
/// Appends an *empty* `Jump` instruction to the program and returns the
/// index of that instruction.
#[inline]
fn empty_jump(&mut self) -> InstIdx {
self.insts.push(Jump(0));
self.insts.len() - 1
}
/// Sets the location of a `Jump` instruction at index `i` to `pc`.
/// If the instruction at index `i` isn't a `Jump` instruction, then
/// `fail!` is called.
#[inline]
fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
let jmp = self.insts.get_mut(i);
match *jmp {
Jump(_) => *jmp = Jump(pc),
_ => fail!("BUG: Invalid jump index."),
}
}
}
|
{
let split = self.insts.get_mut(i);
match *split {
Split(_, _) => *split = Split(pc1, pc2),
_ => fail!("BUG: Invalid split index."),
}
}
|
identifier_body
|
compile.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.
// Enable this to squash warnings due to exporting pieces of the representation
// for use with the regex! macro. See lib.rs for explanation.
use std::cmp;
use parse;
use parse::{
Flags, FLAG_EMPTY,
Nothing, Literal, Dot, AstClass, Begin, End, WordBoundary, Capture, Cat, Alt,
Rep,
ZeroOne, ZeroMore, OneMore,
};
type InstIdx = uint;
#[deriving(Show, Clone)]
pub enum Inst {
// When a Match instruction is executed, the current thread is successful.
Match,
// The OneChar instruction matches a literal character.
// The flags indicate whether to do a case insensitive match.
OneChar(char, Flags),
// The CharClass instruction tries to match one input character against
// the range of characters given.
// The flags indicate whether to do a case insensitive match and whether
// the character class is negated or not.
CharClass(Vec<(char, char)>, Flags),
// Matches any character except new lines.
// The flags indicate whether to include the '\n' character.
Any(Flags),
// Matches the beginning of the string, consumes no characters.
// The flags indicate whether it matches if the preceding character
// is a new line.
EmptyBegin(Flags),
// Matches the end of the string, consumes no characters.
// The flags indicate whether it matches if the proceeding character
// is a new line.
EmptyEnd(Flags),
// Matches a word boundary (\w on one side and \W \A or \z on the other),
// and consumes no character.
// The flags indicate whether this matches a word boundary or something
// that isn't a word boundary.
EmptyWordBoundary(Flags),
// Saves the current position in the input string to the Nth save slot.
Save(uint),
// Jumps to the instruction at the index given.
Jump(InstIdx),
// Jumps to the instruction at the first index given. If that leads to
// a failing state, then the instruction at the second index given is
// tried.
Split(InstIdx, InstIdx),
}
/// Program represents a compiled regular expression. Once an expression is
/// compiled, its representation is immutable and will never change.
///
/// All of the data in a compiled expression is wrapped in "MaybeStatic" or
/// "MaybeOwned" types so that a `Program` can be represented as static data.
/// (This makes it convenient and efficient for use with the `regex!` macro.)
#[deriving(Clone)]
pub struct Program {
/// A sequence of instructions.
pub insts: Vec<Inst>,
/// If the regular expression requires a literal prefix in order to have a
/// match, that prefix is stored here. (It's used in the VM to implement
/// an optimization.)
pub prefix: String,
}
impl Program {
/// Compiles a Regex given its AST.
pub fn new(ast: parse::Ast) -> (Program, Vec<Option<String>>) {
let mut c = Compiler {
insts: Vec::with_capacity(100),
names: Vec::with_capacity(10),
};
c.insts.push(Save(0));
c.compile(ast);
c.insts.push(Save(1));
c.insts.push(Match);
// Try to discover a literal string prefix.
// This is a bit hacky since we have to skip over the initial
// 'Save' instruction.
let mut pre = String::with_capacity(5);
for inst in c.insts.slice_from(1).iter() {
match *inst {
OneChar(c, FLAG_EMPTY) => pre.push(c),
_ => break
}
}
let Compiler { insts, names } = c;
let prog = Program {
insts: insts,
prefix: pre,
};
(prog, names)
}
/// Returns the total number of capture groups in the regular expression.
/// This includes the zeroth capture.
pub fn num_captures(&self) -> uint {
let mut n = 0;
for inst in self.insts.iter() {
match *inst {
Save(c) => n = cmp::max(n, c+1),
_ => {}
}
}
// There's exactly 2 Save slots for every capture.
n / 2
}
}
struct Compiler<'r> {
insts: Vec<Inst>,
names: Vec<Option<String>>,
}
// The compiler implemented here is extremely simple. Most of the complexity
// in this crate is in the parser or the VM.
// The only tricky thing here is patching jump/split instructions to point to
// the right instruction.
impl<'r> Compiler<'r> {
fn compile(&mut self, ast: parse::Ast) {
match ast {
Nothing => {},
Literal(c, flags) => self.push(OneChar(c, flags)),
Dot(nl) => self.push(Any(nl)),
AstClass(ranges, flags) =>
self.push(CharClass(ranges, flags)),
Begin(flags) => self.push(EmptyBegin(flags)),
End(flags) => self.push(EmptyEnd(flags)),
WordBoundary(flags) => self.push(EmptyWordBoundary(flags)),
Capture(cap, name, x) => {
let len = self.names.len();
if cap >= len {
self.names.grow(10 + cap - len, None)
}
*self.names.get_mut(cap) = name;
self.push(Save(2 * cap));
self.compile(*x);
self.push(Save(2 * cap + 1));
}
Cat(xs) => {
for x in xs.into_iter() {
self.compile(x)
}
}
Alt(x, y) => {
let split = self.empty_split(); // push: split 0, 0
let j1 = self.insts.len();
self.compile(*x); // push: insts for x
let jmp = self.empty_jump(); // push: jmp 0
let j2 = self.insts.len();
self.compile(*y); // push: insts for y
let j3 = self.insts.len();
self.set_split(split, j1, j2); // split 0, 0 -> split j1, j2
self.set_jump(jmp, j3); // jmp 0 -> jmp j3
}
Rep(x, ZeroOne, g) => {
let split = self.empty_split();
let j1 = self.insts.len();
self.compile(*x);
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
Rep(x, ZeroMore, g) => {
let j1 = self.insts.len();
let split = self.empty_split();
let j2 = self.insts.len();
self.compile(*x);
let jmp = self.empty_jump();
let j3 = self.insts.len();
self.set_jump(jmp, j1);
if g.is_greedy() {
self.set_split(split, j2, j3);
} else {
self.set_split(split, j3, j2);
}
}
Rep(x, OneMore, g) => {
let j1 = self.insts.len();
self.compile(*x);
let split = self.empty_split();
let j2 = self.insts.len();
if g.is_greedy() {
self.set_split(split, j1, j2);
} else {
self.set_split(split, j2, j1);
}
}
}
}
/// Appends the given instruction to the program.
#[inline]
fn push(&mut self, x: Inst) {
self.insts.push(x)
}
/// Appends an *empty* `Split` instruction to the program and returns
/// the index of that instruction. (The index can then be used to "patch"
/// the actual locations of the split in later.)
#[inline]
fn empty_split(&mut self) -> InstIdx {
self.insts.push(Split(0, 0));
self.insts.len() - 1
}
/// Sets the left and right locations of a `Split` instruction at index
/// `i` to `pc1` and `pc2`, respectively.
/// If the instruction at index `i` isn't a `Split` instruction, then
/// `fail!` is called.
#[inline]
fn
|
(&mut self, i: InstIdx, pc1: InstIdx, pc2: InstIdx) {
let split = self.insts.get_mut(i);
match *split {
Split(_, _) => *split = Split(pc1, pc2),
_ => fail!("BUG: Invalid split index."),
}
}
/// Appends an *empty* `Jump` instruction to the program and returns the
/// index of that instruction.
#[inline]
fn empty_jump(&mut self) -> InstIdx {
self.insts.push(Jump(0));
self.insts.len() - 1
}
/// Sets the location of a `Jump` instruction at index `i` to `pc`.
/// If the instruction at index `i` isn't a `Jump` instruction, then
/// `fail!` is called.
#[inline]
fn set_jump(&mut self, i: InstIdx, pc: InstIdx) {
let jmp = self.insts.get_mut(i);
match *jmp {
Jump(_) => *jmp = Jump(pc),
_ => fail!("BUG: Invalid jump index."),
}
}
}
|
set_split
|
identifier_name
|
ring_buffer.rs
|
use common::*;
use libc::{self, c_void, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::cmp::min;
use std::ffi::CString;
use std::io;
use std::io::Write;
use std::ptr;
use std::slice;
use uuid::*;
/// A ring buffer which can be used to insert and read ordered data.
pub struct RingBuffer {
/// Head, signifies where a consumer should read from.
head: usize,
/// Tail, signifies where a producer should write.
tail: usize,
/// Size of the ring buffer.
size: usize,
/// Used for computing circular things.
mask: usize,
/// Things for shm.
bottom_map: *mut c_void,
top_map: *mut c_void,
/// rust buffer.
buf: *mut u8,
}
unsafe impl Send for RingBuffer {}
impl Drop for RingBuffer {
fn drop(&mut self) {
unsafe {
munmap(self.bottom_map, self.size);
munmap(self.top_map, self.size);
}
}
}
#[cfg_attr(feature = "dev", allow(len_without_is_empty))]
impl RingBuffer {
unsafe fn allocate(pages: usize) -> Result<RingBuffer> {
if pages & (pages - 1)!= 0 {
// We need pages to be a power of 2.
return Err(ErrorKind::InvalidRingSize(pages).into());
}
let bytes = pages << 12;
let alloc_bytes = bytes * 2;
// First open a SHM region.
let name = CString::new(Uuid::new(UuidVersion::Random).unwrap().simple().to_string()).unwrap();
let fd = shm_open(name.as_ptr(), libc::O_CREAT | libc::O_RDWR, 0o700);
if fd < 0 {
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if ftruncate(fd, bytes as i64)!= 0 {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
// First get a big enough chunk of virtual memory. Fortunately for us this does not actually commit any physical
// pages. We allocate twice as much memory so as to mirror the ring buffer.
let address = mmap(ptr::null_mut(),
alloc_bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if address == libc::MAP_FAILED {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
};
assert!((address as usize) % 4096 == 0);
if shm_unlink(name.as_ptr())!= 0 {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
let bottom = (address as *mut u8).offset(bytes as isize) as *mut libc::c_void;
let bottom_address = mmap(bottom,
bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_FIXED | libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if bottom_address == libc::MAP_FAILED {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if bottom_address!= bottom {
munmap(address, bytes);
munmap(bottom_address, bytes);
return Err(ErrorKind::RingDuplicationFailure.into());
}
libc::close(fd);
Ok(RingBuffer {
head: 0,
tail: 0,
size: bytes,
mask: bytes - 1,
bottom_map: bottom,
top_map: address,
buf: address as *mut u8,
})
}
/// Create a new wrapping ring buffer. The ring buffer size is specified in page size (4KB) and must be a power of
/// 2. This only works on Linux, and can panic should any of the syscalls fail.
pub fn new(pages: usize) -> Result<RingBuffer>
|
/// Produce an immutable slice at an offset. The nice thing about our implementation is that we can produce slices
/// despite using a circular ring buffer.
#[inline]
fn slice_at_offset(&self, offset: usize, len: usize) -> &[u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts(begin, len)
}
}
/// Produce a mutable slice.
#[inline]
fn mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `mut_slice_at_offset` for use when writing to the tail of the ring buffer.
#[inline]
fn unsafe_mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `slice_at_offset` for use when reading from head of the ring buffer.
#[inline]
fn unsafe_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Write data at an offset of the buffer. Do not use this function if you use `write_at_tail`/`read_from_head`.
#[inline]
pub fn write_at_offset(&mut self, offset: usize, data: &[u8]) -> usize {
self.mut_slice_at_offset(offset, data.len()).write(data).unwrap()
}
/// Read data from offset of the buffer. Do not use if using `write_at_tail`/`read_from_head`
#[inline]
pub fn read_from_offset(&mut self, offset: usize, mut data: &mut [u8]) -> usize {
let write_size = min(data.len(), self.size);
data.write(self.slice_at_offset(offset, write_size)).unwrap()
}
/// Write data at the end of the buffer. The amount of data written might be smaller than input.
#[inline]
pub fn write_at_tail(&mut self, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
let write = min(data.len(), available);
if write!= data.len() {
println!("Not writing all, available {}", available);
}
let offset = self.tail & self.mask;
self.seek_tail(write);
self.unsafe_mut_slice_at_offset(offset, write).write(&data[0..write]).unwrap()
}
/// Write at an offset from the tail, useful when dealing with out-of-order data. Note, the caller is responsible
/// for progressing the tail sufficiently (using `seek_tail`) when gaps are filled.
#[inline]
pub fn write_at_offset_from_tail(&mut self, offset: usize, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
if available < offset {
0 // The offset lies beyond where we can safely write.
} else {
let offset_tail = self.tail.wrapping_add(offset);
let available_at_offset = self.mask.wrapping_add(self.head).wrapping_sub(offset_tail);
let write = min(data.len(), available_at_offset);
let index = offset_tail & self.mask;
self.unsafe_mut_slice_at_offset(index, write).write(&data[0..write]).unwrap()
}
}
/// Data available to be read.
#[inline]
pub fn available(&self) -> usize {
self.tail.wrapping_sub(self.head)
}
#[inline]
fn read_offset(&self) -> usize {
self.head & self.mask
}
/// Read from the buffer, incrementing the read head by `increment` bytes. Returns bytes read.
#[inline]
pub fn read_from_head_with_increment(&mut self, mut data: &mut [u8], increment: usize) -> usize {
let offset = self.read_offset();
let to_read = min(self.available(), data.len());
self.head = self.head.wrapping_add(min(increment, to_read));
(&mut data[0..to_read]).write(self.unsafe_slice_at_offset(offset, to_read)).unwrap()
}
/// Read from the buffer, incrementing the read head. Returns bytes read.
#[inline]
pub fn read_from_head(&mut self, mut data: &mut [u8]) -> usize {
let len = data.len();
self.read_from_head_with_increment(data, len)
}
/// Peek data from the read head. Note, that this slice is only valid until the next `read` or `write` operation.
#[inline]
pub fn peek_from_head(&self, len: usize) -> &[u8] {
let offset = self.read_offset();
let to_read = min(len, self.available());
self.unsafe_slice_at_offset(offset, to_read)
}
/// Seek the read head by `seek` bytes (without actually reading any data). `seek` must be less-than-or-equal to the
/// number of available bytes.
#[inline]
pub fn seek_head(&mut self, seek: usize) {
let available = self.available();
assert!(available >= seek, "Seek beyond available bytes.");
self.head = self.head.wrapping_add(seek);
}
/// Length of the ring buffer.
#[inline]
pub fn len(&self) -> usize {
self.size
}
/// In cases with out-of-order data this allows the write head (and hence the amount of available data) to be
/// progressed without writing anything.
#[inline]
pub fn seek_tail(&mut self, increment_by: usize) {
self.tail = self.tail.wrapping_add(increment_by);
}
#[inline]
pub fn clear(&mut self) {
self.head = 0;
self.tail = 0;
}
}
|
{
unsafe { RingBuffer::allocate(pages) }
}
|
identifier_body
|
ring_buffer.rs
|
use common::*;
use libc::{self, c_void, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::cmp::min;
use std::ffi::CString;
use std::io;
use std::io::Write;
use std::ptr;
use std::slice;
use uuid::*;
/// A ring buffer which can be used to insert and read ordered data.
pub struct RingBuffer {
/// Head, signifies where a consumer should read from.
head: usize,
/// Tail, signifies where a producer should write.
tail: usize,
/// Size of the ring buffer.
size: usize,
/// Used for computing circular things.
mask: usize,
/// Things for shm.
bottom_map: *mut c_void,
top_map: *mut c_void,
/// rust buffer.
buf: *mut u8,
}
unsafe impl Send for RingBuffer {}
impl Drop for RingBuffer {
fn drop(&mut self) {
unsafe {
munmap(self.bottom_map, self.size);
munmap(self.top_map, self.size);
}
}
}
#[cfg_attr(feature = "dev", allow(len_without_is_empty))]
impl RingBuffer {
unsafe fn allocate(pages: usize) -> Result<RingBuffer> {
if pages & (pages - 1)!= 0 {
// We need pages to be a power of 2.
return Err(ErrorKind::InvalidRingSize(pages).into());
}
let bytes = pages << 12;
let alloc_bytes = bytes * 2;
// First open a SHM region.
let name = CString::new(Uuid::new(UuidVersion::Random).unwrap().simple().to_string()).unwrap();
let fd = shm_open(name.as_ptr(), libc::O_CREAT | libc::O_RDWR, 0o700);
if fd < 0 {
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if ftruncate(fd, bytes as i64)!= 0 {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
// First get a big enough chunk of virtual memory. Fortunately for us this does not actually commit any physical
// pages. We allocate twice as much memory so as to mirror the ring buffer.
let address = mmap(ptr::null_mut(),
alloc_bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if address == libc::MAP_FAILED {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
};
assert!((address as usize) % 4096 == 0);
if shm_unlink(name.as_ptr())!= 0 {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
let bottom = (address as *mut u8).offset(bytes as isize) as *mut libc::c_void;
let bottom_address = mmap(bottom,
bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_FIXED | libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if bottom_address == libc::MAP_FAILED {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if bottom_address!= bottom {
munmap(address, bytes);
munmap(bottom_address, bytes);
return Err(ErrorKind::RingDuplicationFailure.into());
}
libc::close(fd);
Ok(RingBuffer {
head: 0,
tail: 0,
size: bytes,
mask: bytes - 1,
bottom_map: bottom,
top_map: address,
buf: address as *mut u8,
})
}
/// Create a new wrapping ring buffer. The ring buffer size is specified in page size (4KB) and must be a power of
/// 2. This only works on Linux, and can panic should any of the syscalls fail.
pub fn new(pages: usize) -> Result<RingBuffer> {
unsafe { RingBuffer::allocate(pages) }
}
/// Produce an immutable slice at an offset. The nice thing about our implementation is that we can produce slices
/// despite using a circular ring buffer.
#[inline]
fn slice_at_offset(&self, offset: usize, len: usize) -> &[u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts(begin, len)
}
}
/// Produce a mutable slice.
#[inline]
fn mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `mut_slice_at_offset` for use when writing to the tail of the ring buffer.
#[inline]
fn unsafe_mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `slice_at_offset` for use when reading from head of the ring buffer.
#[inline]
fn unsafe_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Write data at an offset of the buffer. Do not use this function if you use `write_at_tail`/`read_from_head`.
#[inline]
pub fn write_at_offset(&mut self, offset: usize, data: &[u8]) -> usize {
self.mut_slice_at_offset(offset, data.len()).write(data).unwrap()
}
/// Read data from offset of the buffer. Do not use if using `write_at_tail`/`read_from_head`
#[inline]
pub fn read_from_offset(&mut self, offset: usize, mut data: &mut [u8]) -> usize {
let write_size = min(data.len(), self.size);
data.write(self.slice_at_offset(offset, write_size)).unwrap()
}
/// Write data at the end of the buffer. The amount of data written might be smaller than input.
#[inline]
pub fn write_at_tail(&mut self, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
let write = min(data.len(), available);
if write!= data.len() {
println!("Not writing all, available {}", available);
}
let offset = self.tail & self.mask;
self.seek_tail(write);
self.unsafe_mut_slice_at_offset(offset, write).write(&data[0..write]).unwrap()
}
/// Write at an offset from the tail, useful when dealing with out-of-order data. Note, the caller is responsible
/// for progressing the tail sufficiently (using `seek_tail`) when gaps are filled.
#[inline]
pub fn write_at_offset_from_tail(&mut self, offset: usize, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
if available < offset {
0 // The offset lies beyond where we can safely write.
} else {
let offset_tail = self.tail.wrapping_add(offset);
let available_at_offset = self.mask.wrapping_add(self.head).wrapping_sub(offset_tail);
let write = min(data.len(), available_at_offset);
let index = offset_tail & self.mask;
self.unsafe_mut_slice_at_offset(index, write).write(&data[0..write]).unwrap()
}
}
/// Data available to be read.
#[inline]
pub fn available(&self) -> usize {
self.tail.wrapping_sub(self.head)
}
#[inline]
fn read_offset(&self) -> usize {
self.head & self.mask
}
/// Read from the buffer, incrementing the read head by `increment` bytes. Returns bytes read.
#[inline]
pub fn read_from_head_with_increment(&mut self, mut data: &mut [u8], increment: usize) -> usize {
let offset = self.read_offset();
let to_read = min(self.available(), data.len());
self.head = self.head.wrapping_add(min(increment, to_read));
(&mut data[0..to_read]).write(self.unsafe_slice_at_offset(offset, to_read)).unwrap()
}
/// Read from the buffer, incrementing the read head. Returns bytes read.
#[inline]
pub fn read_from_head(&mut self, mut data: &mut [u8]) -> usize {
let len = data.len();
self.read_from_head_with_increment(data, len)
}
/// Peek data from the read head. Note, that this slice is only valid until the next `read` or `write` operation.
#[inline]
pub fn peek_from_head(&self, len: usize) -> &[u8] {
let offset = self.read_offset();
let to_read = min(len, self.available());
self.unsafe_slice_at_offset(offset, to_read)
}
/// Seek the read head by `seek` bytes (without actually reading any data). `seek` must be less-than-or-equal to the
/// number of available bytes.
#[inline]
pub fn seek_head(&mut self, seek: usize) {
let available = self.available();
assert!(available >= seek, "Seek beyond available bytes.");
self.head = self.head.wrapping_add(seek);
}
|
/// Length of the ring buffer.
#[inline]
pub fn len(&self) -> usize {
self.size
}
/// In cases with out-of-order data this allows the write head (and hence the amount of available data) to be
/// progressed without writing anything.
#[inline]
pub fn seek_tail(&mut self, increment_by: usize) {
self.tail = self.tail.wrapping_add(increment_by);
}
#[inline]
pub fn clear(&mut self) {
self.head = 0;
self.tail = 0;
}
}
|
random_line_split
|
|
ring_buffer.rs
|
use common::*;
use libc::{self, c_void, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::cmp::min;
use std::ffi::CString;
use std::io;
use std::io::Write;
use std::ptr;
use std::slice;
use uuid::*;
/// A ring buffer which can be used to insert and read ordered data.
pub struct RingBuffer {
/// Head, signifies where a consumer should read from.
head: usize,
/// Tail, signifies where a producer should write.
tail: usize,
/// Size of the ring buffer.
size: usize,
/// Used for computing circular things.
mask: usize,
/// Things for shm.
bottom_map: *mut c_void,
top_map: *mut c_void,
/// rust buffer.
buf: *mut u8,
}
unsafe impl Send for RingBuffer {}
impl Drop for RingBuffer {
fn drop(&mut self) {
unsafe {
munmap(self.bottom_map, self.size);
munmap(self.top_map, self.size);
}
}
}
#[cfg_attr(feature = "dev", allow(len_without_is_empty))]
impl RingBuffer {
unsafe fn allocate(pages: usize) -> Result<RingBuffer> {
if pages & (pages - 1)!= 0 {
// We need pages to be a power of 2.
return Err(ErrorKind::InvalidRingSize(pages).into());
}
let bytes = pages << 12;
let alloc_bytes = bytes * 2;
// First open a SHM region.
let name = CString::new(Uuid::new(UuidVersion::Random).unwrap().simple().to_string()).unwrap();
let fd = shm_open(name.as_ptr(), libc::O_CREAT | libc::O_RDWR, 0o700);
if fd < 0 {
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if ftruncate(fd, bytes as i64)!= 0 {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
// First get a big enough chunk of virtual memory. Fortunately for us this does not actually commit any physical
// pages. We allocate twice as much memory so as to mirror the ring buffer.
let address = mmap(ptr::null_mut(),
alloc_bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if address == libc::MAP_FAILED {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
};
assert!((address as usize) % 4096 == 0);
if shm_unlink(name.as_ptr())!= 0 {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
let bottom = (address as *mut u8).offset(bytes as isize) as *mut libc::c_void;
let bottom_address = mmap(bottom,
bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_FIXED | libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if bottom_address == libc::MAP_FAILED {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if bottom_address!= bottom {
munmap(address, bytes);
munmap(bottom_address, bytes);
return Err(ErrorKind::RingDuplicationFailure.into());
}
libc::close(fd);
Ok(RingBuffer {
head: 0,
tail: 0,
size: bytes,
mask: bytes - 1,
bottom_map: bottom,
top_map: address,
buf: address as *mut u8,
})
}
/// Create a new wrapping ring buffer. The ring buffer size is specified in page size (4KB) and must be a power of
/// 2. This only works on Linux, and can panic should any of the syscalls fail.
pub fn new(pages: usize) -> Result<RingBuffer> {
unsafe { RingBuffer::allocate(pages) }
}
/// Produce an immutable slice at an offset. The nice thing about our implementation is that we can produce slices
/// despite using a circular ring buffer.
#[inline]
fn slice_at_offset(&self, offset: usize, len: usize) -> &[u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts(begin, len)
}
}
/// Produce a mutable slice.
#[inline]
fn mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `mut_slice_at_offset` for use when writing to the tail of the ring buffer.
#[inline]
fn unsafe_mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `slice_at_offset` for use when reading from head of the ring buffer.
#[inline]
fn unsafe_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Write data at an offset of the buffer. Do not use this function if you use `write_at_tail`/`read_from_head`.
#[inline]
pub fn write_at_offset(&mut self, offset: usize, data: &[u8]) -> usize {
self.mut_slice_at_offset(offset, data.len()).write(data).unwrap()
}
/// Read data from offset of the buffer. Do not use if using `write_at_tail`/`read_from_head`
#[inline]
pub fn read_from_offset(&mut self, offset: usize, mut data: &mut [u8]) -> usize {
let write_size = min(data.len(), self.size);
data.write(self.slice_at_offset(offset, write_size)).unwrap()
}
/// Write data at the end of the buffer. The amount of data written might be smaller than input.
#[inline]
pub fn write_at_tail(&mut self, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
let write = min(data.len(), available);
if write!= data.len() {
println!("Not writing all, available {}", available);
}
let offset = self.tail & self.mask;
self.seek_tail(write);
self.unsafe_mut_slice_at_offset(offset, write).write(&data[0..write]).unwrap()
}
/// Write at an offset from the tail, useful when dealing with out-of-order data. Note, the caller is responsible
/// for progressing the tail sufficiently (using `seek_tail`) when gaps are filled.
#[inline]
pub fn write_at_offset_from_tail(&mut self, offset: usize, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
if available < offset {
0 // The offset lies beyond where we can safely write.
} else {
let offset_tail = self.tail.wrapping_add(offset);
let available_at_offset = self.mask.wrapping_add(self.head).wrapping_sub(offset_tail);
let write = min(data.len(), available_at_offset);
let index = offset_tail & self.mask;
self.unsafe_mut_slice_at_offset(index, write).write(&data[0..write]).unwrap()
}
}
/// Data available to be read.
#[inline]
pub fn available(&self) -> usize {
self.tail.wrapping_sub(self.head)
}
#[inline]
fn read_offset(&self) -> usize {
self.head & self.mask
}
/// Read from the buffer, incrementing the read head by `increment` bytes. Returns bytes read.
#[inline]
pub fn read_from_head_with_increment(&mut self, mut data: &mut [u8], increment: usize) -> usize {
let offset = self.read_offset();
let to_read = min(self.available(), data.len());
self.head = self.head.wrapping_add(min(increment, to_read));
(&mut data[0..to_read]).write(self.unsafe_slice_at_offset(offset, to_read)).unwrap()
}
/// Read from the buffer, incrementing the read head. Returns bytes read.
#[inline]
pub fn read_from_head(&mut self, mut data: &mut [u8]) -> usize {
let len = data.len();
self.read_from_head_with_increment(data, len)
}
/// Peek data from the read head. Note, that this slice is only valid until the next `read` or `write` operation.
#[inline]
pub fn peek_from_head(&self, len: usize) -> &[u8] {
let offset = self.read_offset();
let to_read = min(len, self.available());
self.unsafe_slice_at_offset(offset, to_read)
}
/// Seek the read head by `seek` bytes (without actually reading any data). `seek` must be less-than-or-equal to the
/// number of available bytes.
#[inline]
pub fn seek_head(&mut self, seek: usize) {
let available = self.available();
assert!(available >= seek, "Seek beyond available bytes.");
self.head = self.head.wrapping_add(seek);
}
/// Length of the ring buffer.
#[inline]
pub fn len(&self) -> usize {
self.size
}
/// In cases with out-of-order data this allows the write head (and hence the amount of available data) to be
/// progressed without writing anything.
#[inline]
pub fn
|
(&mut self, increment_by: usize) {
self.tail = self.tail.wrapping_add(increment_by);
}
#[inline]
pub fn clear(&mut self) {
self.head = 0;
self.tail = 0;
}
}
|
seek_tail
|
identifier_name
|
ring_buffer.rs
|
use common::*;
use libc::{self, c_void, ftruncate, mmap, munmap, shm_open, shm_unlink};
use std::cmp::min;
use std::ffi::CString;
use std::io;
use std::io::Write;
use std::ptr;
use std::slice;
use uuid::*;
/// A ring buffer which can be used to insert and read ordered data.
pub struct RingBuffer {
/// Head, signifies where a consumer should read from.
head: usize,
/// Tail, signifies where a producer should write.
tail: usize,
/// Size of the ring buffer.
size: usize,
/// Used for computing circular things.
mask: usize,
/// Things for shm.
bottom_map: *mut c_void,
top_map: *mut c_void,
/// rust buffer.
buf: *mut u8,
}
unsafe impl Send for RingBuffer {}
impl Drop for RingBuffer {
fn drop(&mut self) {
unsafe {
munmap(self.bottom_map, self.size);
munmap(self.top_map, self.size);
}
}
}
#[cfg_attr(feature = "dev", allow(len_without_is_empty))]
impl RingBuffer {
unsafe fn allocate(pages: usize) -> Result<RingBuffer> {
if pages & (pages - 1)!= 0 {
// We need pages to be a power of 2.
return Err(ErrorKind::InvalidRingSize(pages).into());
}
let bytes = pages << 12;
let alloc_bytes = bytes * 2;
// First open a SHM region.
let name = CString::new(Uuid::new(UuidVersion::Random).unwrap().simple().to_string()).unwrap();
let fd = shm_open(name.as_ptr(), libc::O_CREAT | libc::O_RDWR, 0o700);
if fd < 0 {
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if ftruncate(fd, bytes as i64)!= 0
|
// First get a big enough chunk of virtual memory. Fortunately for us this does not actually commit any physical
// pages. We allocate twice as much memory so as to mirror the ring buffer.
let address = mmap(ptr::null_mut(),
alloc_bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if address == libc::MAP_FAILED {
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
};
assert!((address as usize) % 4096 == 0);
if shm_unlink(name.as_ptr())!= 0 {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
let bottom = (address as *mut u8).offset(bytes as isize) as *mut libc::c_void;
let bottom_address = mmap(bottom,
bytes,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_FIXED | libc::MAP_ANONYMOUS | libc::MAP_SHARED,
fd,
0);
if bottom_address == libc::MAP_FAILED {
munmap(address, alloc_bytes);
libc::close(fd);
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
if bottom_address!= bottom {
munmap(address, bytes);
munmap(bottom_address, bytes);
return Err(ErrorKind::RingDuplicationFailure.into());
}
libc::close(fd);
Ok(RingBuffer {
head: 0,
tail: 0,
size: bytes,
mask: bytes - 1,
bottom_map: bottom,
top_map: address,
buf: address as *mut u8,
})
}
/// Create a new wrapping ring buffer. The ring buffer size is specified in page size (4KB) and must be a power of
/// 2. This only works on Linux, and can panic should any of the syscalls fail.
pub fn new(pages: usize) -> Result<RingBuffer> {
unsafe { RingBuffer::allocate(pages) }
}
/// Produce an immutable slice at an offset. The nice thing about our implementation is that we can produce slices
/// despite using a circular ring buffer.
#[inline]
fn slice_at_offset(&self, offset: usize, len: usize) -> &[u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts(begin, len)
}
}
/// Produce a mutable slice.
#[inline]
fn mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
if len >= self.size {
panic!("slice beyond buffer length");
}
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `mut_slice_at_offset` for use when writing to the tail of the ring buffer.
#[inline]
fn unsafe_mut_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Unsafe version of `slice_at_offset` for use when reading from head of the ring buffer.
#[inline]
fn unsafe_slice_at_offset(&self, offset: usize, len: usize) -> &mut [u8] {
unsafe {
let begin = self.buf.offset(offset as isize);
slice::from_raw_parts_mut(begin, len)
}
}
/// Write data at an offset of the buffer. Do not use this function if you use `write_at_tail`/`read_from_head`.
#[inline]
pub fn write_at_offset(&mut self, offset: usize, data: &[u8]) -> usize {
self.mut_slice_at_offset(offset, data.len()).write(data).unwrap()
}
/// Read data from offset of the buffer. Do not use if using `write_at_tail`/`read_from_head`
#[inline]
pub fn read_from_offset(&mut self, offset: usize, mut data: &mut [u8]) -> usize {
let write_size = min(data.len(), self.size);
data.write(self.slice_at_offset(offset, write_size)).unwrap()
}
/// Write data at the end of the buffer. The amount of data written might be smaller than input.
#[inline]
pub fn write_at_tail(&mut self, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
let write = min(data.len(), available);
if write!= data.len() {
println!("Not writing all, available {}", available);
}
let offset = self.tail & self.mask;
self.seek_tail(write);
self.unsafe_mut_slice_at_offset(offset, write).write(&data[0..write]).unwrap()
}
/// Write at an offset from the tail, useful when dealing with out-of-order data. Note, the caller is responsible
/// for progressing the tail sufficiently (using `seek_tail`) when gaps are filled.
#[inline]
pub fn write_at_offset_from_tail(&mut self, offset: usize, data: &[u8]) -> usize {
let available = self.mask.wrapping_add(self.head).wrapping_sub(self.tail);
if available < offset {
0 // The offset lies beyond where we can safely write.
} else {
let offset_tail = self.tail.wrapping_add(offset);
let available_at_offset = self.mask.wrapping_add(self.head).wrapping_sub(offset_tail);
let write = min(data.len(), available_at_offset);
let index = offset_tail & self.mask;
self.unsafe_mut_slice_at_offset(index, write).write(&data[0..write]).unwrap()
}
}
/// Data available to be read.
#[inline]
pub fn available(&self) -> usize {
self.tail.wrapping_sub(self.head)
}
#[inline]
fn read_offset(&self) -> usize {
self.head & self.mask
}
/// Read from the buffer, incrementing the read head by `increment` bytes. Returns bytes read.
#[inline]
pub fn read_from_head_with_increment(&mut self, mut data: &mut [u8], increment: usize) -> usize {
let offset = self.read_offset();
let to_read = min(self.available(), data.len());
self.head = self.head.wrapping_add(min(increment, to_read));
(&mut data[0..to_read]).write(self.unsafe_slice_at_offset(offset, to_read)).unwrap()
}
/// Read from the buffer, incrementing the read head. Returns bytes read.
#[inline]
pub fn read_from_head(&mut self, mut data: &mut [u8]) -> usize {
let len = data.len();
self.read_from_head_with_increment(data, len)
}
/// Peek data from the read head. Note, that this slice is only valid until the next `read` or `write` operation.
#[inline]
pub fn peek_from_head(&self, len: usize) -> &[u8] {
let offset = self.read_offset();
let to_read = min(len, self.available());
self.unsafe_slice_at_offset(offset, to_read)
}
/// Seek the read head by `seek` bytes (without actually reading any data). `seek` must be less-than-or-equal to the
/// number of available bytes.
#[inline]
pub fn seek_head(&mut self, seek: usize) {
let available = self.available();
assert!(available >= seek, "Seek beyond available bytes.");
self.head = self.head.wrapping_add(seek);
}
/// Length of the ring buffer.
#[inline]
pub fn len(&self) -> usize {
self.size
}
/// In cases with out-of-order data this allows the write head (and hence the amount of available data) to be
/// progressed without writing anything.
#[inline]
pub fn seek_tail(&mut self, increment_by: usize) {
self.tail = self.tail.wrapping_add(increment_by);
}
#[inline]
pub fn clear(&mut self) {
self.head = 0;
self.tail = 0;
}
}
|
{
libc::close(fd);
shm_unlink(name.as_ptr());
return Err(io::Error::last_os_error()).chain_err(|| ErrorKind::RingAllocationFailure);
}
|
conditional_block
|
fileref.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 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 version 2 for more details.
*/
use core::ops::Deref;
use core::fmt;
use errors::Error;
use goff;
use io::{Read, Write};
use kif;
use session::Pager;
use vfs::filetable::Fd;
use vfs::{FileHandle, Map, Seek, SeekMode};
use vpe::VPE;
#[derive(Clone)]
pub struct FileRef {
file: FileHandle,
fd: Fd,
}
impl FileRef {
pub fn new(file: FileHandle, fd: Fd) -> Self {
FileRef {
file: file,
fd: fd,
}
}
pub fn fd(&self) -> Fd {
self.fd
}
pub fn handle(&self) -> FileHandle {
self.file.clone()
}
}
impl Drop for FileRef {
fn
|
(&mut self) {
VPE::cur().files().remove(self.fd);
}
}
impl Deref for FileRef {
type Target = FileHandle;
fn deref(&self) -> &FileHandle {
&self.file
}
}
impl Read for FileRef {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.file.borrow_mut().read(buf)
}
}
impl Write for FileRef {
fn flush(&mut self) -> Result<(), Error> {
self.file.borrow_mut().flush()
}
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.file.borrow_mut().write(buf)
}
}
impl Seek for FileRef {
fn seek(&mut self, off: usize, whence: SeekMode) -> Result<usize, Error> {
self.file.borrow_mut().seek(off, whence)
}
}
impl Map for FileRef {
fn map(&self, pager: &Pager, virt: goff, off: usize, len: usize, prot: kif::Perm) -> Result<(), Error> {
self.file.borrow().map(pager, virt, off, len, prot)
}
}
impl fmt::Debug for FileRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "FileRef[fd={}, file={:?}]", self.fd, self.file.borrow())
}
}
|
drop
|
identifier_name
|
fileref.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 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 version 2 for more details.
*/
use core::ops::Deref;
use core::fmt;
use errors::Error;
use goff;
use io::{Read, Write};
use kif;
use session::Pager;
use vfs::filetable::Fd;
use vfs::{FileHandle, Map, Seek, SeekMode};
use vpe::VPE;
#[derive(Clone)]
pub struct FileRef {
file: FileHandle,
fd: Fd,
}
impl FileRef {
pub fn new(file: FileHandle, fd: Fd) -> Self {
FileRef {
file: file,
fd: fd,
}
}
pub fn fd(&self) -> Fd {
self.fd
}
pub fn handle(&self) -> FileHandle {
self.file.clone()
}
}
impl Drop for FileRef {
fn drop(&mut self) {
VPE::cur().files().remove(self.fd);
}
}
impl Deref for FileRef {
type Target = FileHandle;
fn deref(&self) -> &FileHandle {
&self.file
}
}
impl Read for FileRef {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.file.borrow_mut().read(buf)
}
}
impl Write for FileRef {
fn flush(&mut self) -> Result<(), Error> {
self.file.borrow_mut().flush()
}
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.file.borrow_mut().write(buf)
}
}
impl Seek for FileRef {
fn seek(&mut self, off: usize, whence: SeekMode) -> Result<usize, Error>
|
}
impl Map for FileRef {
fn map(&self, pager: &Pager, virt: goff, off: usize, len: usize, prot: kif::Perm) -> Result<(), Error> {
self.file.borrow().map(pager, virt, off, len, prot)
}
}
impl fmt::Debug for FileRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "FileRef[fd={}, file={:?}]", self.fd, self.file.borrow())
}
}
|
{
self.file.borrow_mut().seek(off, whence)
}
|
identifier_body
|
fileref.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 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 version 2 for more details.
*/
use core::ops::Deref;
use core::fmt;
use errors::Error;
use goff;
use io::{Read, Write};
use kif;
use session::Pager;
use vfs::filetable::Fd;
use vfs::{FileHandle, Map, Seek, SeekMode};
use vpe::VPE;
#[derive(Clone)]
pub struct FileRef {
file: FileHandle,
fd: Fd,
}
impl FileRef {
pub fn new(file: FileHandle, fd: Fd) -> Self {
FileRef {
file: file,
fd: fd,
}
}
pub fn fd(&self) -> Fd {
self.fd
}
pub fn handle(&self) -> FileHandle {
self.file.clone()
}
}
impl Drop for FileRef {
fn drop(&mut self) {
VPE::cur().files().remove(self.fd);
}
}
impl Deref for FileRef {
type Target = FileHandle;
fn deref(&self) -> &FileHandle {
&self.file
}
}
impl Read for FileRef {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
self.file.borrow_mut().read(buf)
}
}
impl Write for FileRef {
fn flush(&mut self) -> Result<(), Error> {
self.file.borrow_mut().flush()
}
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
self.file.borrow_mut().write(buf)
}
}
impl Seek for FileRef {
fn seek(&mut self, off: usize, whence: SeekMode) -> Result<usize, Error> {
self.file.borrow_mut().seek(off, whence)
}
}
|
self.file.borrow().map(pager, virt, off, len, prot)
}
}
impl fmt::Debug for FileRef {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "FileRef[fd={}, file={:?}]", self.fd, self.file.borrow())
}
}
|
impl Map for FileRef {
fn map(&self, pager: &Pager, virt: goff, off: usize, len: usize, prot: kif::Perm) -> Result<(), Error> {
|
random_line_split
|
factor.rs
|
#![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <[email protected]>
* (c) Wiktor Kuropatwa <[email protected]>
* 20150223 added Pollard rho method implementation
* (c) kwantam <[email protected]>
* 20150429 sped up trial division by adding table of prime inverses
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate rand;
#[macro_use]
extern crate uucore;
use numeric::*;
use prime_table::P_INVS_U64;
use rand::distributions::{Range, IndependentSample};
use std::cmp::{max, min};
use std::io::{stdin, BufRead, BufReader, Write};
use std::num::Wrapping;
use std::mem::swap;
mod numeric;
mod prime_table;
static NAME: &'static str = "factor";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn rho_pollard_pseudorandom_function(x: u64, a: u64, b: u64, num: u64) -> u64 {
if num < 1 << 63 {
(sm_mul(a, sm_mul(x, x, num), num) + b) % num
} else {
big_add(big_mul(a, big_mul(x, x, num), num), b, num)
}
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind_sample(&mut rng);
let mut b = range.ind_sample(&mut rng);
loop {
x = rho_pollard_pseudorandom_function(x, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
let d = gcd(num, max(x, y) - min(x, y));
if d == num {
// Failure, retry with diffrent function
x = range.ind_sample(&mut rng);
y = x;
a = range.ind_sample(&mut rng);
b = range.ind_sample(&mut rng);
} else if d > 1 {
return d;
}
}
}
fn rho_pollard_factor(num: u64, factors: &mut Vec<u64>) {
if is_prime(num) {
factors.push(num);
return;
}
let divisor = rho_pollard_find_divisor(num);
rho_pollard_factor(divisor, factors);
rho_pollard_factor(num / divisor, factors);
}
fn
|
(mut num: u64, factors: &mut Vec<u64>) {
if num < 2 {
return;
}
while num % 2 == 0 {
num /= 2;
factors.push(2);
}
if num == 1 {
return;
}
if is_prime(num) {
factors.push(num);
return;
}
for &(prime, inv, ceil) in P_INVS_U64 {
if num == 1 {
break;
}
// inv = prime^-1 mod 2^64
// ceil = floor((2^64-1) / prime)
// if (num * inv) mod 2^64 <= ceil, then prime divides num
// See http://math.stackexchange.com/questions/1251327/
// for a nice explanation.
loop {
let Wrapping(x) = Wrapping(num) * Wrapping(inv); // x = num * inv mod 2^64
if x <= ceil {
num = x;
factors.push(prime);
if is_prime(num) {
factors.push(num);
return;
}
} else {
break;
}
}
}
// do we still have more factoring to do?
// Decide whether to use Pollard Rho or slow divisibility based on
// number's size:
//if num >= 1 << 63 {
// number is too big to use rho pollard without overflowing
//trial_division_slow(num, factors);
//} else if num > 1 {
// number is still greater than 1, but not so big that we have to worry
rho_pollard_factor(num, factors);
//}
}
fn print_factors(num: u64) {
print!("{}:", num);
let mut factors = Vec::new();
// we always start with table division, and go from there
table_division(num, &mut factors);
factors.sort();
for fac in &factors {
print!(" {}", fac);
}
println!("");
}
fn print_factors_str(num_str: &str) {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
}
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "show this help message");
opts.optflag("v", "version", "print the version and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "Invalid options\n{}", f)
};
if matches.opt_present("help") {
let msg = format!("{0} {1}
Usage:
\t{0} [NUMBER]...
\t{0} [OPTION]
Print the prime factors of the given number(s). If none are specified,
read from standard input.", NAME, VERSION);
print!("{}", opts.usage(&msg));
return 1;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
}
}
} else {
for num_str in &matches.free {
print_factors_str(num_str);
}
}
0
}
|
table_division
|
identifier_name
|
factor.rs
|
#![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <[email protected]>
* (c) Wiktor Kuropatwa <[email protected]>
* 20150223 added Pollard rho method implementation
* (c) kwantam <[email protected]>
* 20150429 sped up trial division by adding table of prime inverses
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate rand;
#[macro_use]
extern crate uucore;
use numeric::*;
use prime_table::P_INVS_U64;
use rand::distributions::{Range, IndependentSample};
use std::cmp::{max, min};
use std::io::{stdin, BufRead, BufReader, Write};
use std::num::Wrapping;
use std::mem::swap;
mod numeric;
mod prime_table;
static NAME: &'static str = "factor";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn rho_pollard_pseudorandom_function(x: u64, a: u64, b: u64, num: u64) -> u64 {
if num < 1 << 63
|
else {
big_add(big_mul(a, big_mul(x, x, num), num), b, num)
}
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind_sample(&mut rng);
let mut b = range.ind_sample(&mut rng);
loop {
x = rho_pollard_pseudorandom_function(x, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
let d = gcd(num, max(x, y) - min(x, y));
if d == num {
// Failure, retry with diffrent function
x = range.ind_sample(&mut rng);
y = x;
a = range.ind_sample(&mut rng);
b = range.ind_sample(&mut rng);
} else if d > 1 {
return d;
}
}
}
fn rho_pollard_factor(num: u64, factors: &mut Vec<u64>) {
if is_prime(num) {
factors.push(num);
return;
}
let divisor = rho_pollard_find_divisor(num);
rho_pollard_factor(divisor, factors);
rho_pollard_factor(num / divisor, factors);
}
fn table_division(mut num: u64, factors: &mut Vec<u64>) {
if num < 2 {
return;
}
while num % 2 == 0 {
num /= 2;
factors.push(2);
}
if num == 1 {
return;
}
if is_prime(num) {
factors.push(num);
return;
}
for &(prime, inv, ceil) in P_INVS_U64 {
if num == 1 {
break;
}
// inv = prime^-1 mod 2^64
// ceil = floor((2^64-1) / prime)
// if (num * inv) mod 2^64 <= ceil, then prime divides num
// See http://math.stackexchange.com/questions/1251327/
// for a nice explanation.
loop {
let Wrapping(x) = Wrapping(num) * Wrapping(inv); // x = num * inv mod 2^64
if x <= ceil {
num = x;
factors.push(prime);
if is_prime(num) {
factors.push(num);
return;
}
} else {
break;
}
}
}
// do we still have more factoring to do?
// Decide whether to use Pollard Rho or slow divisibility based on
// number's size:
//if num >= 1 << 63 {
// number is too big to use rho pollard without overflowing
//trial_division_slow(num, factors);
//} else if num > 1 {
// number is still greater than 1, but not so big that we have to worry
rho_pollard_factor(num, factors);
//}
}
fn print_factors(num: u64) {
print!("{}:", num);
let mut factors = Vec::new();
// we always start with table division, and go from there
table_division(num, &mut factors);
factors.sort();
for fac in &factors {
print!(" {}", fac);
}
println!("");
}
fn print_factors_str(num_str: &str) {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
}
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "show this help message");
opts.optflag("v", "version", "print the version and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "Invalid options\n{}", f)
};
if matches.opt_present("help") {
let msg = format!("{0} {1}
Usage:
\t{0} [NUMBER]...
\t{0} [OPTION]
Print the prime factors of the given number(s). If none are specified,
read from standard input.", NAME, VERSION);
print!("{}", opts.usage(&msg));
return 1;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
}
}
} else {
for num_str in &matches.free {
print_factors_str(num_str);
}
}
0
}
|
{
(sm_mul(a, sm_mul(x, x, num), num) + b) % num
}
|
conditional_block
|
factor.rs
|
#![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <[email protected]>
* (c) Wiktor Kuropatwa <[email protected]>
* 20150223 added Pollard rho method implementation
* (c) kwantam <[email protected]>
* 20150429 sped up trial division by adding table of prime inverses
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate rand;
#[macro_use]
extern crate uucore;
use numeric::*;
use prime_table::P_INVS_U64;
use rand::distributions::{Range, IndependentSample};
use std::cmp::{max, min};
use std::io::{stdin, BufRead, BufReader, Write};
use std::num::Wrapping;
use std::mem::swap;
mod numeric;
mod prime_table;
static NAME: &'static str = "factor";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn rho_pollard_pseudorandom_function(x: u64, a: u64, b: u64, num: u64) -> u64 {
if num < 1 << 63 {
(sm_mul(a, sm_mul(x, x, num), num) + b) % num
} else {
big_add(big_mul(a, big_mul(x, x, num), num), b, num)
}
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind_sample(&mut rng);
let mut b = range.ind_sample(&mut rng);
loop {
x = rho_pollard_pseudorandom_function(x, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
let d = gcd(num, max(x, y) - min(x, y));
if d == num {
// Failure, retry with diffrent function
x = range.ind_sample(&mut rng);
y = x;
a = range.ind_sample(&mut rng);
b = range.ind_sample(&mut rng);
} else if d > 1 {
return d;
}
}
}
fn rho_pollard_factor(num: u64, factors: &mut Vec<u64>) {
if is_prime(num) {
factors.push(num);
return;
}
let divisor = rho_pollard_find_divisor(num);
rho_pollard_factor(divisor, factors);
rho_pollard_factor(num / divisor, factors);
}
fn table_division(mut num: u64, factors: &mut Vec<u64>)
|
// inv = prime^-1 mod 2^64
// ceil = floor((2^64-1) / prime)
// if (num * inv) mod 2^64 <= ceil, then prime divides num
// See http://math.stackexchange.com/questions/1251327/
// for a nice explanation.
loop {
let Wrapping(x) = Wrapping(num) * Wrapping(inv); // x = num * inv mod 2^64
if x <= ceil {
num = x;
factors.push(prime);
if is_prime(num) {
factors.push(num);
return;
}
} else {
break;
}
}
}
// do we still have more factoring to do?
// Decide whether to use Pollard Rho or slow divisibility based on
// number's size:
//if num >= 1 << 63 {
// number is too big to use rho pollard without overflowing
//trial_division_slow(num, factors);
//} else if num > 1 {
// number is still greater than 1, but not so big that we have to worry
rho_pollard_factor(num, factors);
//}
}
fn print_factors(num: u64) {
print!("{}:", num);
let mut factors = Vec::new();
// we always start with table division, and go from there
table_division(num, &mut factors);
factors.sort();
for fac in &factors {
print!(" {}", fac);
}
println!("");
}
fn print_factors_str(num_str: &str) {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
}
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "show this help message");
opts.optflag("v", "version", "print the version and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "Invalid options\n{}", f)
};
if matches.opt_present("help") {
let msg = format!("{0} {1}
Usage:
\t{0} [NUMBER]...
\t{0} [OPTION]
Print the prime factors of the given number(s). If none are specified,
read from standard input.", NAME, VERSION);
print!("{}", opts.usage(&msg));
return 1;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.is_empty() {
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
}
}
} else {
for num_str in &matches.free {
print_factors_str(num_str);
}
}
0
}
|
{
if num < 2 {
return;
}
while num % 2 == 0 {
num /= 2;
factors.push(2);
}
if num == 1 {
return;
}
if is_prime(num) {
factors.push(num);
return;
}
for &(prime, inv, ceil) in P_INVS_U64 {
if num == 1 {
break;
}
|
identifier_body
|
factor.rs
|
#![crate_name = "uu_factor"]
/*
* This file is part of the uutils coreutils package.
*
* (c) T. Jameson Little <[email protected]>
* (c) Wiktor Kuropatwa <[email protected]>
* 20150223 added Pollard rho method implementation
* (c) kwantam <[email protected]>
* 20150429 sped up trial division by adding table of prime inverses
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
extern crate rand;
#[macro_use]
extern crate uucore;
use numeric::*;
use prime_table::P_INVS_U64;
use rand::distributions::{Range, IndependentSample};
use std::cmp::{max, min};
use std::io::{stdin, BufRead, BufReader, Write};
use std::num::Wrapping;
use std::mem::swap;
mod numeric;
mod prime_table;
static NAME: &'static str = "factor";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn rho_pollard_pseudorandom_function(x: u64, a: u64, b: u64, num: u64) -> u64 {
if num < 1 << 63 {
(sm_mul(a, sm_mul(x, x, num), num) + b) % num
} else {
big_add(big_mul(a, big_mul(x, x, num), num), b, num)
}
}
fn gcd(mut a: u64, mut b: u64) -> u64 {
while b > 0 {
a %= b;
swap(&mut a, &mut b);
}
a
}
fn rho_pollard_find_divisor(num: u64) -> u64 {
let range = Range::new(1, num);
let mut rng = rand::weak_rng();
let mut x = range.ind_sample(&mut rng);
let mut y = x;
let mut a = range.ind_sample(&mut rng);
let mut b = range.ind_sample(&mut rng);
loop {
x = rho_pollard_pseudorandom_function(x, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
y = rho_pollard_pseudorandom_function(y, a, b, num);
let d = gcd(num, max(x, y) - min(x, y));
if d == num {
// Failure, retry with diffrent function
x = range.ind_sample(&mut rng);
y = x;
a = range.ind_sample(&mut rng);
b = range.ind_sample(&mut rng);
} else if d > 1 {
return d;
}
}
}
fn rho_pollard_factor(num: u64, factors: &mut Vec<u64>) {
if is_prime(num) {
factors.push(num);
return;
}
let divisor = rho_pollard_find_divisor(num);
rho_pollard_factor(divisor, factors);
rho_pollard_factor(num / divisor, factors);
}
fn table_division(mut num: u64, factors: &mut Vec<u64>) {
if num < 2 {
return;
}
while num % 2 == 0 {
num /= 2;
factors.push(2);
}
if num == 1 {
return;
}
if is_prime(num) {
factors.push(num);
return;
}
for &(prime, inv, ceil) in P_INVS_U64 {
if num == 1 {
break;
}
// inv = prime^-1 mod 2^64
// ceil = floor((2^64-1) / prime)
// if (num * inv) mod 2^64 <= ceil, then prime divides num
// See http://math.stackexchange.com/questions/1251327/
// for a nice explanation.
loop {
let Wrapping(x) = Wrapping(num) * Wrapping(inv); // x = num * inv mod 2^64
if x <= ceil {
num = x;
factors.push(prime);
if is_prime(num) {
factors.push(num);
return;
}
} else {
break;
}
}
}
// do we still have more factoring to do?
// Decide whether to use Pollard Rho or slow divisibility based on
// number's size:
//if num >= 1 << 63 {
// number is too big to use rho pollard without overflowing
//trial_division_slow(num, factors);
//} else if num > 1 {
// number is still greater than 1, but not so big that we have to worry
rho_pollard_factor(num, factors);
//}
}
fn print_factors(num: u64) {
print!("{}:", num);
let mut factors = Vec::new();
// we always start with table division, and go from there
table_division(num, &mut factors);
factors.sort();
for fac in &factors {
print!(" {}", fac);
}
println!("");
}
fn print_factors_str(num_str: &str) {
if let Err(e) = num_str.parse::<u64>().and_then(|x| Ok(print_factors(x))) {
show_warning!("{}: {}", num_str, e);
}
}
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
opts.optflag("h", "help", "show this help message");
opts.optflag("v", "version", "print the version and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "Invalid options\n{}", f)
};
if matches.opt_present("help") {
let msg = format!("{0} {1}
Usage:
\t{0} [NUMBER]...
\t{0} [OPTION]
Print the prime factors of the given number(s). If none are specified,
read from standard input.", NAME, VERSION);
print!("{}", opts.usage(&msg));
return 1;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.free.is_empty() {
|
}
}
} else {
for num_str in &matches.free {
print_factors_str(num_str);
}
}
0
}
|
for line in BufReader::new(stdin()).lines() {
for number in line.unwrap().split_whitespace() {
print_factors_str(number);
|
random_line_split
|
gen_sample.rs
|
use async_trait::*;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::executor::LocalPool;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::LocalSpawnExt;
use macro_test::gen_sample::*;
use pasta_core::Scriptor;
use std::collections::HashSet;
use std::ops::Range;
struct TestScriptor {
tags: HashSet<String>,
talk: String,
tx: Sender<String>,
}
impl TestScriptor {
pub fn new() -> (Self, Receiver<String>) {
let (tx, rx) = channel(0);
(
Self {
tags: Default::default(),
talk: Default::default(),
tx: tx,
},
rx,
)
}
}
#[async_trait]
impl Scriptor for TestScriptor {
/// トーク開始
async fn start(&mut self) {
let t = std::mem::replace(&mut self.talk, Default::default());
self.tx.send(t).await.unwrap();
}
/// アクター切替
fn actor(&mut self, t: &str) {
let s = format!("actor({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// アクション(表情)の指定
fn action(&mut self, t: &str) {
let s = format!("action({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// セリフの指定
fn serif(&mut self, t: &str) {
let s = format!("serif({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// タグを取得
fn tags(&self) -> &HashSet<String> {
&self.tags
}
/// タグを取得
fn tags_mut(&mut self) -> &mut HashSet<String> {
&mut self.tags
}
/// タグ要素を覚える
fn memory(&mut self, _tag: &str) {}
/// タグ要素を忘れる
fn forget(&mut self, _tag: &str) {}
/// タグ要素の記憶・忘却の確定
fn commit_tags(&mut self) {}
/// u32の乱数を返す
fn rand_u32(&self) -> u32 {
0u32
}
/// u32の乱数を返す
fn rand_i32(&self) -> i32 {
0
}
/// f32の乱数を返す
fn rand_f32(&self) -> f32 {
0.0
}
/// f64の乱数を返す
fn rand_f64(&self) -> f64 {
0.0
}
/// usizeの範囲で乱数を返す
fn rand_range_usize(&self, range: Range<usize>) -> usize {
range.start
}
/// f64の範囲で乱数を返す
fn rand_range_f64(&self, range: Range<f64>) -> f64 {
range.start
}
}
#[test]
fn rand_jump_test() {
let (mut s, _) = TestScriptor::new();
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
let jt = rand_jump(&mut s, JT::START);
assert_eq!(JT::H5, jt);
}
#[test]
fn talk_test_1() {
let mut pool = LocalPool::new();
let spawner = pool.spawner();
let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags
|
let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
walk(&mut s, JT::START).await;
})
.unwrap();
let left = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Default::default();
right.push_str("actor(パスタ)\n");
right.push_str("serif(こんにちは!)\n");
right.push_str("serif(お昼過ぎになりましたね。)\n");
assert_eq!(right, left);
}
|
_mut().insert("お昼過ぎ".to_owned());
let jump = walk_one(&mut s, JT::START).await;
let jump = walk_one(&mut s, jump).await;
walk_one(&mut s, jump).await;
})
.unwrap();
let act = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Default::default();
right.push_str("actor(パスタ)\n");
right.push_str("serif(こんにちは!)\n");
right.push_str("serif(お昼過ぎになりましたね。)\n");
assert_eq!(right, act);
}
#[test]
fn talk_test_2() {
let mut pool = LocalPool::new();
let spawner = pool.spawner();
|
identifier_body
|
gen_sample.rs
|
use async_trait::*;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::executor::LocalPool;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::LocalSpawnExt;
use macro_test::gen_sample::*;
use pasta_core::Scriptor;
use std::collections::HashSet;
use std::ops::Range;
struct TestScriptor {
tags: HashSet<String>,
talk: String,
tx: Sender<String>,
}
|
impl TestScriptor {
pub fn new() -> (Self, Receiver<String>) {
let (tx, rx) = channel(0);
(
Self {
tags: Default::default(),
talk: Default::default(),
tx: tx,
},
rx,
)
}
}
#[async_trait]
impl Scriptor for TestScriptor {
/// トーク開始
async fn start(&mut self) {
let t = std::mem::replace(&mut self.talk, Default::default());
self.tx.send(t).await.unwrap();
}
/// アクター切替
fn actor(&mut self, t: &str) {
let s = format!("actor({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// アクション(表情)の指定
fn action(&mut self, t: &str) {
let s = format!("action({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// セリフの指定
fn serif(&mut self, t: &str) {
let s = format!("serif({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// タグを取得
fn tags(&self) -> &HashSet<String> {
&self.tags
}
/// タグを取得
fn tags_mut(&mut self) -> &mut HashSet<String> {
&mut self.tags
}
/// タグ要素を覚える
fn memory(&mut self, _tag: &str) {}
/// タグ要素を忘れる
fn forget(&mut self, _tag: &str) {}
/// タグ要素の記憶・忘却の確定
fn commit_tags(&mut self) {}
/// u32の乱数を返す
fn rand_u32(&self) -> u32 {
0u32
}
/// u32の乱数を返す
fn rand_i32(&self) -> i32 {
0
}
/// f32の乱数を返す
fn rand_f32(&self) -> f32 {
0.0
}
/// f64の乱数を返す
fn rand_f64(&self) -> f64 {
0.0
}
/// usizeの範囲で乱数を返す
fn rand_range_usize(&self, range: Range<usize>) -> usize {
range.start
}
/// f64の範囲で乱数を返す
fn rand_range_f64(&self, range: Range<f64>) -> f64 {
range.start
}
}
#[test]
fn rand_jump_test() {
let (mut s, _) = TestScriptor::new();
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
let jt = rand_jump(&mut s, JT::START);
assert_eq!(JT::H5, jt);
}
#[test]
fn talk_test_1() {
let mut pool = LocalPool::new();
let spawner = pool.spawner();
let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
let jump = walk_one(&mut s, JT::START).await;
let jump = walk_one(&mut s, jump).await;
walk_one(&mut s, jump).await;
})
.unwrap();
let act = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Default::default();
right.push_str("actor(パスタ)\n");
right.push_str("serif(こんにちは!)\n");
right.push_str("serif(お昼過ぎになりましたね。)\n");
assert_eq!(right, act);
}
#[test]
fn talk_test_2() {
let mut pool = LocalPool::new();
let spawner = pool.spawner();
let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
walk(&mut s, JT::START).await;
})
.unwrap();
let left = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Default::default();
right.push_str("actor(パスタ)\n");
right.push_str("serif(こんにちは!)\n");
right.push_str("serif(お昼過ぎになりましたね。)\n");
assert_eq!(right, left);
}
|
random_line_split
|
|
gen_sample.rs
|
use async_trait::*;
use futures::channel::mpsc::{channel, Receiver, Sender};
use futures::executor::LocalPool;
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::LocalSpawnExt;
use macro_test::gen_sample::*;
use pasta_core::Scriptor;
use std::collections::HashSet;
use std::ops::Range;
struct
|
{
tags: HashSet<String>,
talk: String,
tx: Sender<String>,
}
impl TestScriptor {
pub fn new() -> (Self, Receiver<String>) {
let (tx, rx) = channel(0);
(
Self {
tags: Default::default(),
talk: Default::default(),
tx: tx,
},
rx,
)
}
}
#[async_trait]
impl Scriptor for TestScriptor {
/// トーク開始
async fn start(&mut self) {
let t = std::mem::replace(&mut self.talk, Default::default());
self.tx.send(t).await.unwrap();
}
/// アクター切替
fn actor(&mut self, t: &str) {
let s = format!("actor({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// アクション(表情)の指定
fn action(&mut self, t: &str) {
let s = format!("action({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// セリフの指定
fn serif(&mut self, t: &str) {
let s = format!("serif({})", t);
self.talk.push_str(&format!("{}\n", &s));
}
/// タグを取得
fn tags(&self) -> &HashSet<String> {
&self.tags
}
/// タグを取得
fn tags_mut(&mut self) -> &mut HashSet<String> {
&mut self.tags
}
/// タグ要素を覚える
fn memory(&mut self, _tag: &str) {}
/// タグ要素を忘れる
fn forget(&mut self, _tag: &str) {}
/// タグ要素の記憶・忘却の確定
fn commit_tags(&mut self) {}
/// u32の乱数を返す
fn rand_u32(&self) -> u32 {
0u32
}
/// u32の乱数を返す
fn rand_i32(&self) -> i32 {
0
}
/// f32の乱数を返す
fn rand_f32(&self) -> f32 {
0.0
}
/// f64の乱数を返す
fn rand_f64(&self) -> f64 {
0.0
}
/// usizeの範囲で乱数を返す
fn rand_range_usize(&self, range: Range<usize>) -> usize {
range.start
}
/// f64の範囲で乱数を返す
fn rand_range_f64(&self, range: Range<f64>) -> f64 {
range.start
}
}
#[test]
fn rand_jump_test() {
let (mut s, _) = TestScriptor::new();
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
let jt = rand_jump(&mut s, JT::START);
assert_eq!(JT::H5, jt);
}
#[test]
fn talk_test_1() {
let mut pool = LocalPool::new();
let spawner = pool.spawner();
let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
let jump = walk_one(&mut s, JT::START).await;
let jump = walk_one(&mut s, jump).await;
walk_one(&mut s, jump).await;
})
.unwrap();
let act = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Default::default();
right.push_str("actor(パスタ)\n");
right.push_str("serif(こんにちは!)\n");
right.push_str("serif(お昼過ぎになりましたね。)\n");
assert_eq!(right, act);
}
#[test]
fn talk_test_2() {
let mut pool = LocalPool::new();
let spawner = pool.spawner();
let (mut s, mut rx) = TestScriptor::new();
spawner
.spawn_local(async move {
s.tags_mut().insert("通常トーク".to_owned());
s.tags_mut().insert("お昼過ぎ".to_owned());
walk(&mut s, JT::START).await;
})
.unwrap();
let left = pool.run_until(async move { rx.next().await.unwrap() });
let mut right: String = Default::default();
right.push_str("actor(パスタ)\n");
right.push_str("serif(こんにちは!)\n");
right.push_str("serif(お昼過ぎになりましたね。)\n");
assert_eq!(right, left);
}
|
TestScriptor
|
identifier_name
|
main.rs
|
use std::env;
fn first_factor(product: u64) -> u64 {
let mut primes = Vec::new();
for i in 2..(product + 1) {
if!primes.iter().any(|p| i % p == 0) { // is prime
if product % i == 0 {
return i;
}
primes.push(i);
}
}
1
}
fn largest_prime(product: u64) -> u64
|
fn main() {
match env::args().nth(1) {
None => println!("Needs a first argument"),
Some(string) => match string.parse::<u64>() {
Ok(product) => println!("{}", largest_prime(product)),
Err(_) => println!("First argument must be an int"),
}
}
}
|
{
let mut remaining = product;
let mut primes = Vec::new();
loop {
let factor = first_factor(remaining);
primes.push(factor);
remaining = remaining / factor;
if factor == 1 {
break;
}
}
let mut max_prime = 1;
for p in primes {
if p > max_prime {
max_prime = p
}
}
max_prime
}
|
identifier_body
|
main.rs
|
use std::env;
fn first_factor(product: u64) -> u64 {
let mut primes = Vec::new();
for i in 2..(product + 1) {
if!primes.iter().any(|p| i % p == 0) { // is prime
if product % i == 0 {
return i;
}
primes.push(i);
}
}
1
}
fn
|
(product: u64) -> u64 {
let mut remaining = product;
let mut primes = Vec::new();
loop {
let factor = first_factor(remaining);
primes.push(factor);
remaining = remaining / factor;
if factor == 1 {
break;
}
}
let mut max_prime = 1;
for p in primes {
if p > max_prime {
max_prime = p
}
}
max_prime
}
fn main() {
match env::args().nth(1) {
None => println!("Needs a first argument"),
Some(string) => match string.parse::<u64>() {
Ok(product) => println!("{}", largest_prime(product)),
Err(_) => println!("First argument must be an int"),
}
}
}
|
largest_prime
|
identifier_name
|
main.rs
|
use std::env;
fn first_factor(product: u64) -> u64 {
let mut primes = Vec::new();
for i in 2..(product + 1) {
if!primes.iter().any(|p| i % p == 0) { // is prime
if product % i == 0 {
return i;
}
primes.push(i);
}
}
1
}
fn largest_prime(product: u64) -> u64 {
|
let mut remaining = product;
let mut primes = Vec::new();
loop {
let factor = first_factor(remaining);
primes.push(factor);
remaining = remaining / factor;
if factor == 1 {
break;
}
}
let mut max_prime = 1;
for p in primes {
if p > max_prime {
max_prime = p
}
}
max_prime
}
fn main() {
match env::args().nth(1) {
None => println!("Needs a first argument"),
Some(string) => match string.parse::<u64>() {
Ok(product) => println!("{}", largest_prime(product)),
Err(_) => println!("First argument must be an int"),
}
}
}
|
random_line_split
|
|
limited-debuginfo.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// ignore-lldb
// compile-flags:--debuginfo=1
// Make sure functions have proper names
// gdb-command:info functions
// gdb-check:[...]void[...]main([...]);
// gdb-check:[...]void[...]some_function([...]);
// gdb-check:[...]void[...]some_other_function([...]);
// gdb-check:[...]void[...]zzz([...]);
// gdb-command:run
// Make sure there is no information about locals
// gdb-command:info locals
// gdb-check:No locals.
// gdb-command:continue
#![allow(unused_variables)]
struct Struct {
a: i64,
b: i32
}
fn main() {
some_function(101, 202);
some_other_function(1, 2);
}
fn zzz() {()}
fn
|
(a: int, b: int) {
let some_variable = Struct { a: 11, b: 22 };
let some_other_variable = 23i;
zzz(); // #break
}
fn some_other_function(a: int, b: int) -> bool { true }
|
some_function
|
identifier_name
|
limited-debuginfo.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// ignore-lldb
// compile-flags:--debuginfo=1
// Make sure functions have proper names
// gdb-command:info functions
// gdb-check:[...]void[...]main([...]);
// gdb-check:[...]void[...]some_function([...]);
// gdb-check:[...]void[...]some_other_function([...]);
// gdb-check:[...]void[...]zzz([...]);
// gdb-command:run
// Make sure there is no information about locals
// gdb-command:info locals
// gdb-check:No locals.
// gdb-command:continue
#![allow(unused_variables)]
struct Struct {
a: i64,
b: i32
}
fn main()
|
fn zzz() {()}
fn some_function(a: int, b: int) {
let some_variable = Struct { a: 11, b: 22 };
let some_other_variable = 23i;
zzz(); // #break
}
fn some_other_function(a: int, b: int) -> bool { true }
|
{
some_function(101, 202);
some_other_function(1, 2);
}
|
identifier_body
|
limited-debuginfo.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// ignore-lldb
// compile-flags:--debuginfo=1
// Make sure functions have proper names
// gdb-command:info functions
// gdb-check:[...]void[...]main([...]);
// gdb-check:[...]void[...]some_function([...]);
|
// Make sure there is no information about locals
// gdb-command:info locals
// gdb-check:No locals.
// gdb-command:continue
#![allow(unused_variables)]
struct Struct {
a: i64,
b: i32
}
fn main() {
some_function(101, 202);
some_other_function(1, 2);
}
fn zzz() {()}
fn some_function(a: int, b: int) {
let some_variable = Struct { a: 11, b: 22 };
let some_other_variable = 23i;
zzz(); // #break
}
fn some_other_function(a: int, b: int) -> bool { true }
|
// gdb-check:[...]void[...]some_other_function([...]);
// gdb-check:[...]void[...]zzz([...]);
// gdb-command:run
|
random_line_split
|
informant.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
extern crate ansi_term;
use self::ansi_term::Colour::{White, Yellow, Green, Cyan, Blue};
use self::ansi_term::Style;
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::time::{Instant, Duration};
use io::{TimerToken, IoContext, IoHandler};
use isatty::{stdout_isatty};
use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::ClientIoMessage;
use ethcore::snapshot::service::Service as SnapshotService;
use ethcore::snapshot::{RestorationStatus, SnapshotService as SS};
use number_prefix::{binary_prefix, Standalone, Prefixed};
use ethcore_rpc::{is_major_importing};
use ethcore_rpc::informant::RpcStats;
use rlp::View;
pub struct Informant {
report: RwLock<Option<ClientReport>>,
last_tick: RwLock<Instant>,
with_color: bool,
client: Arc<Client>,
snapshot: Option<Arc<SnapshotService>>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
rpc_stats: Option<Arc<RpcStats>>,
last_import: Mutex<Instant>,
skipped: AtomicUsize,
skipped_txs: AtomicUsize,
in_shutdown: AtomicBool,
}
/// Format byte counts to standard denominations.
pub fn format_bytes(b: usize) -> String {
match binary_prefix(b as f64) {
Standalone(bytes) => format!("{} bytes", bytes),
Prefixed(prefix, n) => format!("{:.0} {}B", n, prefix),
}
}
/// Something that can be converted to milliseconds.
pub trait MillisecondDuration {
/// Get the value in milliseconds.
fn as_milliseconds(&self) -> u64;
}
impl MillisecondDuration for Duration {
fn as_milliseconds(&self) -> u64 {
self.as_secs() * 1000 + self.subsec_nanos() as u64 / 1_000_000
}
}
impl Informant {
/// Make a new instance potentially `with_color` output.
pub fn new(
client: Arc<Client>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
snapshot: Option<Arc<SnapshotService>>,
rpc_stats: Option<Arc<RpcStats>>,
with_color: bool,
) -> Self {
Informant {
report: RwLock::new(None),
last_tick: RwLock::new(Instant::now()),
with_color: with_color,
client: client,
snapshot: snapshot,
sync: sync,
net: net,
rpc_stats: rpc_stats,
last_import: Mutex::new(Instant::now()),
skipped: AtomicUsize::new(0),
skipped_txs: AtomicUsize::new(0),
in_shutdown: AtomicBool::new(false),
}
}
/// Signal that we're shutting down; no more output necessary.
pub fn shutdown(&self) {
self.in_shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
}
#[cfg_attr(feature="dev", allow(match_bool))]
pub fn tick(&self) {
let elapsed = self.last_tick.read().elapsed();
if elapsed < Duration::from_secs(5) {
return;
}
let chain_info = self.client.chain_info();
let queue_info = self.client.queue_info();
let cache_info = self.client.blockchain_cache_info();
let network_config = self.net.as_ref().map(|n| n.network_config());
let sync_status = self.sync.as_ref().map(|s| s.status());
let rpc_stats = self.rpc_stats.as_ref();
let importing = is_major_importing(sync_status.map(|s| s.state), self.client.queue_info());
let (snapshot_sync, snapshot_current, snapshot_total) = self.snapshot.as_ref().map_or((false, 0, 0), |s|
match s.status() {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, state_chunks_done + block_chunks_done, state_chunks + block_chunks),
_ => (false, 0, 0),
}
);
if!importing &&!snapshot_sync && elapsed < Duration::from_secs(30) {
return;
}
*self.last_tick.write() = Instant::now();
|
let mut write_report = self.report.write();
let report = self.client.report();
let paint = |c: Style, t: String| match self.with_color && stdout_isatty() {
true => format!("{}", c.paint(t)),
false => t,
};
info!(target: "import", "{} {} {} {}",
match importing {
true => match snapshot_sync {
false => format!("Syncing {} {} {} {}+{} Qed",
paint(White.bold(), format!("{:>8}", format!("#{}", chain_info.best_block_number))),
paint(White.bold(), format!("{}", chain_info.best_block_hash)),
{
let last_report = match *write_report { Some(ref last_report) => last_report.clone(), _ => ClientReport::default() };
format!("{} blk/s {} tx/s {} Mgas/s",
paint(Yellow.bold(), format!("{:4}", ((report.blocks_imported - last_report.blocks_imported) * 1000) as u64 / elapsed.as_milliseconds())),
paint(Yellow.bold(), format!("{:4}", ((report.transactions_applied - last_report.transactions_applied) * 1000) as u64 / elapsed.as_milliseconds())),
paint(Yellow.bold(), format!("{:3}", ((report.gas_processed - last_report.gas_processed) / From::from(elapsed.as_milliseconds() * 1000)).low_u64()))
)
},
paint(Green.bold(), format!("{:5}", queue_info.unverified_queue_size)),
paint(Green.bold(), format!("{:5}", queue_info.verified_queue_size))
),
true => format!("Syncing snapshot {}/{}", snapshot_current, snapshot_total),
},
false => String::new(),
},
match (&sync_status, &network_config) {
(&Some(ref sync_info), &Some(ref net_config)) => format!("{}{}/{}/{} peers",
match importing {
true => format!("{} ", paint(Green.bold(), format!("{:>8}", format!("#{}", sync_info.last_imported_block_number.unwrap_or(chain_info.best_block_number))))),
false => match sync_info.last_imported_old_block_number {
Some(number) => format!("{} ", paint(Yellow.bold(), format!("{:>8}", format!("#{}", number)))),
None => String::new(),
}
},
paint(Cyan.bold(), format!("{:2}", sync_info.num_active_peers)),
paint(Cyan.bold(), format!("{:2}", sync_info.num_peers)),
paint(Cyan.bold(), format!("{:2}", sync_info.current_max_peers(net_config.min_peers, net_config.max_peers))),
),
_ => String::new(),
},
format!("{} db {} chain {} queue{}",
paint(Blue.bold(), format!("{:>8}", format_bytes(report.state_db_mem))),
paint(Blue.bold(), format!("{:>8}", format_bytes(cache_info.total()))),
paint(Blue.bold(), format!("{:>8}", format_bytes(queue_info.mem_used))),
match sync_status {
Some(ref sync_info) => format!(" {} sync", paint(Blue.bold(), format!("{:>8}", format_bytes(sync_info.mem_used)))),
_ => String::new(),
}
),
match rpc_stats {
Some(ref rpc_stats) => format!(
"RPC: {} conn, {} req/s, {} µs",
paint(Blue.bold(), format!("{:2}", rpc_stats.sessions())),
paint(Blue.bold(), format!("{:2}", rpc_stats.requests_rate())),
paint(Blue.bold(), format!("{:3}", rpc_stats.approximated_roundtrip())),
),
_ => String::new(),
},
);
*write_report = Some(report);
}
}
impl ChainNotify for Informant {
fn new_blocks(&self, imported: Vec<H256>, _invalid: Vec<H256>, _enacted: Vec<H256>, _retracted: Vec<H256>, _sealed: Vec<H256>, _proposed: Vec<Bytes>, duration: u64) {
let mut last_import = self.last_import.lock();
let sync_state = self.sync.as_ref().map(|s| s.status().state);
let importing = is_major_importing(sync_state, self.client.queue_info());
let ripe = Instant::now() > *last_import + Duration::from_secs(1) &&!importing;
let txs_imported = imported.iter()
.take(imported.len().saturating_sub(if ripe { 1 } else { 0 }))
.filter_map(|h| self.client.block(BlockId::Hash(*h)))
.map(|b| b.transactions_count())
.sum();
if ripe {
if let Some(block) = imported.last().and_then(|h| self.client.block(BlockId::Hash(*h))) {
let header_view = block.header_view();
let size = block.rlp().as_raw().len();
let (skipped, skipped_txs) = (self.skipped.load(AtomicOrdering::Relaxed) + imported.len() - 1, self.skipped_txs.load(AtomicOrdering::Relaxed) + txs_imported);
info!(target: "import", "Imported {} {} ({} txs, {} Mgas, {} ms, {} KiB){}",
Colour::White.bold().paint(format!("#{}", header_view.number())),
Colour::White.bold().paint(format!("{}", header_view.hash())),
Colour::Yellow.bold().paint(format!("{}", block.transactions_count())),
Colour::Yellow.bold().paint(format!("{:.2}", header_view.gas_used().low_u64() as f32 / 1000000f32)),
Colour::Purple.bold().paint(format!("{:.2}", duration as f32 / 1000000f32)),
Colour::Blue.bold().paint(format!("{:.2}", size as f32 / 1024f32)),
if skipped > 0 {
format!(" + another {} block(s) containing {} tx(s)",
Colour::Red.bold().paint(format!("{}", skipped)),
Colour::Red.bold().paint(format!("{}", skipped_txs))
)
} else {
String::new()
}
);
self.skipped.store(0, AtomicOrdering::Relaxed);
self.skipped_txs.store(0, AtomicOrdering::Relaxed);
*last_import = Instant::now();
}
} else {
self.skipped.fetch_add(imported.len(), AtomicOrdering::Relaxed);
self.skipped_txs.fetch_add(txs_imported, AtomicOrdering::Relaxed);
}
}
}
const INFO_TIMER: TimerToken = 0;
impl IoHandler<ClientIoMessage> for Informant {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
if timer == INFO_TIMER &&!self.in_shutdown.load(AtomicOrdering::SeqCst) {
self.tick();
}
}
}
|
random_line_split
|
|
informant.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
extern crate ansi_term;
use self::ansi_term::Colour::{White, Yellow, Green, Cyan, Blue};
use self::ansi_term::Style;
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::time::{Instant, Duration};
use io::{TimerToken, IoContext, IoHandler};
use isatty::{stdout_isatty};
use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::ClientIoMessage;
use ethcore::snapshot::service::Service as SnapshotService;
use ethcore::snapshot::{RestorationStatus, SnapshotService as SS};
use number_prefix::{binary_prefix, Standalone, Prefixed};
use ethcore_rpc::{is_major_importing};
use ethcore_rpc::informant::RpcStats;
use rlp::View;
pub struct Informant {
report: RwLock<Option<ClientReport>>,
last_tick: RwLock<Instant>,
with_color: bool,
client: Arc<Client>,
snapshot: Option<Arc<SnapshotService>>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
rpc_stats: Option<Arc<RpcStats>>,
last_import: Mutex<Instant>,
skipped: AtomicUsize,
skipped_txs: AtomicUsize,
in_shutdown: AtomicBool,
}
/// Format byte counts to standard denominations.
pub fn format_bytes(b: usize) -> String {
match binary_prefix(b as f64) {
Standalone(bytes) => format!("{} bytes", bytes),
Prefixed(prefix, n) => format!("{:.0} {}B", n, prefix),
}
}
/// Something that can be converted to milliseconds.
pub trait MillisecondDuration {
/// Get the value in milliseconds.
fn as_milliseconds(&self) -> u64;
}
impl MillisecondDuration for Duration {
fn as_milliseconds(&self) -> u64 {
self.as_secs() * 1000 + self.subsec_nanos() as u64 / 1_000_000
}
}
impl Informant {
/// Make a new instance potentially `with_color` output.
pub fn
|
(
client: Arc<Client>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
snapshot: Option<Arc<SnapshotService>>,
rpc_stats: Option<Arc<RpcStats>>,
with_color: bool,
) -> Self {
Informant {
report: RwLock::new(None),
last_tick: RwLock::new(Instant::now()),
with_color: with_color,
client: client,
snapshot: snapshot,
sync: sync,
net: net,
rpc_stats: rpc_stats,
last_import: Mutex::new(Instant::now()),
skipped: AtomicUsize::new(0),
skipped_txs: AtomicUsize::new(0),
in_shutdown: AtomicBool::new(false),
}
}
/// Signal that we're shutting down; no more output necessary.
pub fn shutdown(&self) {
self.in_shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
}
#[cfg_attr(feature="dev", allow(match_bool))]
pub fn tick(&self) {
let elapsed = self.last_tick.read().elapsed();
if elapsed < Duration::from_secs(5) {
return;
}
let chain_info = self.client.chain_info();
let queue_info = self.client.queue_info();
let cache_info = self.client.blockchain_cache_info();
let network_config = self.net.as_ref().map(|n| n.network_config());
let sync_status = self.sync.as_ref().map(|s| s.status());
let rpc_stats = self.rpc_stats.as_ref();
let importing = is_major_importing(sync_status.map(|s| s.state), self.client.queue_info());
let (snapshot_sync, snapshot_current, snapshot_total) = self.snapshot.as_ref().map_or((false, 0, 0), |s|
match s.status() {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, state_chunks_done + block_chunks_done, state_chunks + block_chunks),
_ => (false, 0, 0),
}
);
if!importing &&!snapshot_sync && elapsed < Duration::from_secs(30) {
return;
}
*self.last_tick.write() = Instant::now();
let mut write_report = self.report.write();
let report = self.client.report();
let paint = |c: Style, t: String| match self.with_color && stdout_isatty() {
true => format!("{}", c.paint(t)),
false => t,
};
info!(target: "import", "{} {} {} {}",
match importing {
true => match snapshot_sync {
false => format!("Syncing {} {} {} {}+{} Qed",
paint(White.bold(), format!("{:>8}", format!("#{}", chain_info.best_block_number))),
paint(White.bold(), format!("{}", chain_info.best_block_hash)),
{
let last_report = match *write_report { Some(ref last_report) => last_report.clone(), _ => ClientReport::default() };
format!("{} blk/s {} tx/s {} Mgas/s",
paint(Yellow.bold(), format!("{:4}", ((report.blocks_imported - last_report.blocks_imported) * 1000) as u64 / elapsed.as_milliseconds())),
paint(Yellow.bold(), format!("{:4}", ((report.transactions_applied - last_report.transactions_applied) * 1000) as u64 / elapsed.as_milliseconds())),
paint(Yellow.bold(), format!("{:3}", ((report.gas_processed - last_report.gas_processed) / From::from(elapsed.as_milliseconds() * 1000)).low_u64()))
)
},
paint(Green.bold(), format!("{:5}", queue_info.unverified_queue_size)),
paint(Green.bold(), format!("{:5}", queue_info.verified_queue_size))
),
true => format!("Syncing snapshot {}/{}", snapshot_current, snapshot_total),
},
false => String::new(),
},
match (&sync_status, &network_config) {
(&Some(ref sync_info), &Some(ref net_config)) => format!("{}{}/{}/{} peers",
match importing {
true => format!("{} ", paint(Green.bold(), format!("{:>8}", format!("#{}", sync_info.last_imported_block_number.unwrap_or(chain_info.best_block_number))))),
false => match sync_info.last_imported_old_block_number {
Some(number) => format!("{} ", paint(Yellow.bold(), format!("{:>8}", format!("#{}", number)))),
None => String::new(),
}
},
paint(Cyan.bold(), format!("{:2}", sync_info.num_active_peers)),
paint(Cyan.bold(), format!("{:2}", sync_info.num_peers)),
paint(Cyan.bold(), format!("{:2}", sync_info.current_max_peers(net_config.min_peers, net_config.max_peers))),
),
_ => String::new(),
},
format!("{} db {} chain {} queue{}",
paint(Blue.bold(), format!("{:>8}", format_bytes(report.state_db_mem))),
paint(Blue.bold(), format!("{:>8}", format_bytes(cache_info.total()))),
paint(Blue.bold(), format!("{:>8}", format_bytes(queue_info.mem_used))),
match sync_status {
Some(ref sync_info) => format!(" {} sync", paint(Blue.bold(), format!("{:>8}", format_bytes(sync_info.mem_used)))),
_ => String::new(),
}
),
match rpc_stats {
Some(ref rpc_stats) => format!(
"RPC: {} conn, {} req/s, {} µs",
paint(Blue.bold(), format!("{:2}", rpc_stats.sessions())),
paint(Blue.bold(), format!("{:2}", rpc_stats.requests_rate())),
paint(Blue.bold(), format!("{:3}", rpc_stats.approximated_roundtrip())),
),
_ => String::new(),
},
);
*write_report = Some(report);
}
}
impl ChainNotify for Informant {
fn new_blocks(&self, imported: Vec<H256>, _invalid: Vec<H256>, _enacted: Vec<H256>, _retracted: Vec<H256>, _sealed: Vec<H256>, _proposed: Vec<Bytes>, duration: u64) {
let mut last_import = self.last_import.lock();
let sync_state = self.sync.as_ref().map(|s| s.status().state);
let importing = is_major_importing(sync_state, self.client.queue_info());
let ripe = Instant::now() > *last_import + Duration::from_secs(1) &&!importing;
let txs_imported = imported.iter()
.take(imported.len().saturating_sub(if ripe { 1 } else { 0 }))
.filter_map(|h| self.client.block(BlockId::Hash(*h)))
.map(|b| b.transactions_count())
.sum();
if ripe {
if let Some(block) = imported.last().and_then(|h| self.client.block(BlockId::Hash(*h))) {
let header_view = block.header_view();
let size = block.rlp().as_raw().len();
let (skipped, skipped_txs) = (self.skipped.load(AtomicOrdering::Relaxed) + imported.len() - 1, self.skipped_txs.load(AtomicOrdering::Relaxed) + txs_imported);
info!(target: "import", "Imported {} {} ({} txs, {} Mgas, {} ms, {} KiB){}",
Colour::White.bold().paint(format!("#{}", header_view.number())),
Colour::White.bold().paint(format!("{}", header_view.hash())),
Colour::Yellow.bold().paint(format!("{}", block.transactions_count())),
Colour::Yellow.bold().paint(format!("{:.2}", header_view.gas_used().low_u64() as f32 / 1000000f32)),
Colour::Purple.bold().paint(format!("{:.2}", duration as f32 / 1000000f32)),
Colour::Blue.bold().paint(format!("{:.2}", size as f32 / 1024f32)),
if skipped > 0 {
format!(" + another {} block(s) containing {} tx(s)",
Colour::Red.bold().paint(format!("{}", skipped)),
Colour::Red.bold().paint(format!("{}", skipped_txs))
)
} else {
String::new()
}
);
self.skipped.store(0, AtomicOrdering::Relaxed);
self.skipped_txs.store(0, AtomicOrdering::Relaxed);
*last_import = Instant::now();
}
} else {
self.skipped.fetch_add(imported.len(), AtomicOrdering::Relaxed);
self.skipped_txs.fetch_add(txs_imported, AtomicOrdering::Relaxed);
}
}
}
const INFO_TIMER: TimerToken = 0;
impl IoHandler<ClientIoMessage> for Informant {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
if timer == INFO_TIMER &&!self.in_shutdown.load(AtomicOrdering::SeqCst) {
self.tick();
}
}
}
|
new
|
identifier_name
|
informant.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
extern crate ansi_term;
use self::ansi_term::Colour::{White, Yellow, Green, Cyan, Blue};
use self::ansi_term::Style;
use std::sync::{Arc};
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
use std::time::{Instant, Duration};
use io::{TimerToken, IoContext, IoHandler};
use isatty::{stdout_isatty};
use ethsync::{SyncProvider, ManageNetwork};
use util::{Uint, RwLock, Mutex, H256, Colour, Bytes};
use ethcore::client::*;
use ethcore::service::ClientIoMessage;
use ethcore::snapshot::service::Service as SnapshotService;
use ethcore::snapshot::{RestorationStatus, SnapshotService as SS};
use number_prefix::{binary_prefix, Standalone, Prefixed};
use ethcore_rpc::{is_major_importing};
use ethcore_rpc::informant::RpcStats;
use rlp::View;
pub struct Informant {
report: RwLock<Option<ClientReport>>,
last_tick: RwLock<Instant>,
with_color: bool,
client: Arc<Client>,
snapshot: Option<Arc<SnapshotService>>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
rpc_stats: Option<Arc<RpcStats>>,
last_import: Mutex<Instant>,
skipped: AtomicUsize,
skipped_txs: AtomicUsize,
in_shutdown: AtomicBool,
}
/// Format byte counts to standard denominations.
pub fn format_bytes(b: usize) -> String {
match binary_prefix(b as f64) {
Standalone(bytes) => format!("{} bytes", bytes),
Prefixed(prefix, n) => format!("{:.0} {}B", n, prefix),
}
}
/// Something that can be converted to milliseconds.
pub trait MillisecondDuration {
/// Get the value in milliseconds.
fn as_milliseconds(&self) -> u64;
}
impl MillisecondDuration for Duration {
fn as_milliseconds(&self) -> u64
|
}
impl Informant {
/// Make a new instance potentially `with_color` output.
pub fn new(
client: Arc<Client>,
sync: Option<Arc<SyncProvider>>,
net: Option<Arc<ManageNetwork>>,
snapshot: Option<Arc<SnapshotService>>,
rpc_stats: Option<Arc<RpcStats>>,
with_color: bool,
) -> Self {
Informant {
report: RwLock::new(None),
last_tick: RwLock::new(Instant::now()),
with_color: with_color,
client: client,
snapshot: snapshot,
sync: sync,
net: net,
rpc_stats: rpc_stats,
last_import: Mutex::new(Instant::now()),
skipped: AtomicUsize::new(0),
skipped_txs: AtomicUsize::new(0),
in_shutdown: AtomicBool::new(false),
}
}
/// Signal that we're shutting down; no more output necessary.
pub fn shutdown(&self) {
self.in_shutdown.store(true, ::std::sync::atomic::Ordering::SeqCst);
}
#[cfg_attr(feature="dev", allow(match_bool))]
pub fn tick(&self) {
let elapsed = self.last_tick.read().elapsed();
if elapsed < Duration::from_secs(5) {
return;
}
let chain_info = self.client.chain_info();
let queue_info = self.client.queue_info();
let cache_info = self.client.blockchain_cache_info();
let network_config = self.net.as_ref().map(|n| n.network_config());
let sync_status = self.sync.as_ref().map(|s| s.status());
let rpc_stats = self.rpc_stats.as_ref();
let importing = is_major_importing(sync_status.map(|s| s.state), self.client.queue_info());
let (snapshot_sync, snapshot_current, snapshot_total) = self.snapshot.as_ref().map_or((false, 0, 0), |s|
match s.status() {
RestorationStatus::Ongoing { state_chunks, block_chunks, state_chunks_done, block_chunks_done } =>
(true, state_chunks_done + block_chunks_done, state_chunks + block_chunks),
_ => (false, 0, 0),
}
);
if!importing &&!snapshot_sync && elapsed < Duration::from_secs(30) {
return;
}
*self.last_tick.write() = Instant::now();
let mut write_report = self.report.write();
let report = self.client.report();
let paint = |c: Style, t: String| match self.with_color && stdout_isatty() {
true => format!("{}", c.paint(t)),
false => t,
};
info!(target: "import", "{} {} {} {}",
match importing {
true => match snapshot_sync {
false => format!("Syncing {} {} {} {}+{} Qed",
paint(White.bold(), format!("{:>8}", format!("#{}", chain_info.best_block_number))),
paint(White.bold(), format!("{}", chain_info.best_block_hash)),
{
let last_report = match *write_report { Some(ref last_report) => last_report.clone(), _ => ClientReport::default() };
format!("{} blk/s {} tx/s {} Mgas/s",
paint(Yellow.bold(), format!("{:4}", ((report.blocks_imported - last_report.blocks_imported) * 1000) as u64 / elapsed.as_milliseconds())),
paint(Yellow.bold(), format!("{:4}", ((report.transactions_applied - last_report.transactions_applied) * 1000) as u64 / elapsed.as_milliseconds())),
paint(Yellow.bold(), format!("{:3}", ((report.gas_processed - last_report.gas_processed) / From::from(elapsed.as_milliseconds() * 1000)).low_u64()))
)
},
paint(Green.bold(), format!("{:5}", queue_info.unverified_queue_size)),
paint(Green.bold(), format!("{:5}", queue_info.verified_queue_size))
),
true => format!("Syncing snapshot {}/{}", snapshot_current, snapshot_total),
},
false => String::new(),
},
match (&sync_status, &network_config) {
(&Some(ref sync_info), &Some(ref net_config)) => format!("{}{}/{}/{} peers",
match importing {
true => format!("{} ", paint(Green.bold(), format!("{:>8}", format!("#{}", sync_info.last_imported_block_number.unwrap_or(chain_info.best_block_number))))),
false => match sync_info.last_imported_old_block_number {
Some(number) => format!("{} ", paint(Yellow.bold(), format!("{:>8}", format!("#{}", number)))),
None => String::new(),
}
},
paint(Cyan.bold(), format!("{:2}", sync_info.num_active_peers)),
paint(Cyan.bold(), format!("{:2}", sync_info.num_peers)),
paint(Cyan.bold(), format!("{:2}", sync_info.current_max_peers(net_config.min_peers, net_config.max_peers))),
),
_ => String::new(),
},
format!("{} db {} chain {} queue{}",
paint(Blue.bold(), format!("{:>8}", format_bytes(report.state_db_mem))),
paint(Blue.bold(), format!("{:>8}", format_bytes(cache_info.total()))),
paint(Blue.bold(), format!("{:>8}", format_bytes(queue_info.mem_used))),
match sync_status {
Some(ref sync_info) => format!(" {} sync", paint(Blue.bold(), format!("{:>8}", format_bytes(sync_info.mem_used)))),
_ => String::new(),
}
),
match rpc_stats {
Some(ref rpc_stats) => format!(
"RPC: {} conn, {} req/s, {} µs",
paint(Blue.bold(), format!("{:2}", rpc_stats.sessions())),
paint(Blue.bold(), format!("{:2}", rpc_stats.requests_rate())),
paint(Blue.bold(), format!("{:3}", rpc_stats.approximated_roundtrip())),
),
_ => String::new(),
},
);
*write_report = Some(report);
}
}
impl ChainNotify for Informant {
fn new_blocks(&self, imported: Vec<H256>, _invalid: Vec<H256>, _enacted: Vec<H256>, _retracted: Vec<H256>, _sealed: Vec<H256>, _proposed: Vec<Bytes>, duration: u64) {
let mut last_import = self.last_import.lock();
let sync_state = self.sync.as_ref().map(|s| s.status().state);
let importing = is_major_importing(sync_state, self.client.queue_info());
let ripe = Instant::now() > *last_import + Duration::from_secs(1) &&!importing;
let txs_imported = imported.iter()
.take(imported.len().saturating_sub(if ripe { 1 } else { 0 }))
.filter_map(|h| self.client.block(BlockId::Hash(*h)))
.map(|b| b.transactions_count())
.sum();
if ripe {
if let Some(block) = imported.last().and_then(|h| self.client.block(BlockId::Hash(*h))) {
let header_view = block.header_view();
let size = block.rlp().as_raw().len();
let (skipped, skipped_txs) = (self.skipped.load(AtomicOrdering::Relaxed) + imported.len() - 1, self.skipped_txs.load(AtomicOrdering::Relaxed) + txs_imported);
info!(target: "import", "Imported {} {} ({} txs, {} Mgas, {} ms, {} KiB){}",
Colour::White.bold().paint(format!("#{}", header_view.number())),
Colour::White.bold().paint(format!("{}", header_view.hash())),
Colour::Yellow.bold().paint(format!("{}", block.transactions_count())),
Colour::Yellow.bold().paint(format!("{:.2}", header_view.gas_used().low_u64() as f32 / 1000000f32)),
Colour::Purple.bold().paint(format!("{:.2}", duration as f32 / 1000000f32)),
Colour::Blue.bold().paint(format!("{:.2}", size as f32 / 1024f32)),
if skipped > 0 {
format!(" + another {} block(s) containing {} tx(s)",
Colour::Red.bold().paint(format!("{}", skipped)),
Colour::Red.bold().paint(format!("{}", skipped_txs))
)
} else {
String::new()
}
);
self.skipped.store(0, AtomicOrdering::Relaxed);
self.skipped_txs.store(0, AtomicOrdering::Relaxed);
*last_import = Instant::now();
}
} else {
self.skipped.fetch_add(imported.len(), AtomicOrdering::Relaxed);
self.skipped_txs.fetch_add(txs_imported, AtomicOrdering::Relaxed);
}
}
}
const INFO_TIMER: TimerToken = 0;
impl IoHandler<ClientIoMessage> for Informant {
fn initialize(&self, io: &IoContext<ClientIoMessage>) {
io.register_timer(INFO_TIMER, 5000).expect("Error registering timer");
}
fn timeout(&self, _io: &IoContext<ClientIoMessage>, timer: TimerToken) {
if timer == INFO_TIMER &&!self.in_shutdown.load(AtomicOrdering::SeqCst) {
self.tick();
}
}
}
|
{
self.as_secs() * 1000 + self.subsec_nanos() as u64 / 1_000_000
}
|
identifier_body
|
operator-multidispatch.rs
|
// run-pass
// Test that we can overload the `+` operator for points so that two
// points can be added, and a point can be added to an integer.
use std::ops;
#[derive(Debug,PartialEq,Eq)]
struct Point {
x: isize,
y: isize
}
impl ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {x: self.x + other.x, y: self.y + other.y}
}
}
impl ops::Add<isize> for Point {
type Output = Point;
fn add(self, other: isize) -> Point {
Point {x: self.x + other,
y: self.y + other}
}
}
pub fn main()
|
{
let mut p = Point {x: 10, y: 20};
p = p + Point {x: 101, y: 102};
assert_eq!(p, Point {x: 111, y: 122});
p = p + 1;
assert_eq!(p, Point {x: 112, y: 123});
}
|
identifier_body
|
|
operator-multidispatch.rs
|
// run-pass
// Test that we can overload the `+` operator for points so that two
// points can be added, and a point can be added to an integer.
use std::ops;
#[derive(Debug,PartialEq,Eq)]
struct Point {
x: isize,
y: isize
}
impl ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {x: self.x + other.x, y: self.y + other.y}
}
}
impl ops::Add<isize> for Point {
type Output = Point;
fn
|
(self, other: isize) -> Point {
Point {x: self.x + other,
y: self.y + other}
}
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p = p + Point {x: 101, y: 102};
assert_eq!(p, Point {x: 111, y: 122});
p = p + 1;
assert_eq!(p, Point {x: 112, y: 123});
}
|
add
|
identifier_name
|
operator-multidispatch.rs
|
// run-pass
// Test that we can overload the `+` operator for points so that two
// points can be added, and a point can be added to an integer.
use std::ops;
#[derive(Debug,PartialEq,Eq)]
struct Point {
x: isize,
y: isize
}
impl ops::Add for Point {
type Output = Point;
fn add(self, other: Point) -> Point {
Point {x: self.x + other.x, y: self.y + other.y}
}
}
impl ops::Add<isize> for Point {
type Output = Point;
fn add(self, other: isize) -> Point {
Point {x: self.x + other,
y: self.y + other}
}
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
|
assert_eq!(p, Point {x: 112, y: 123});
}
|
p = p + Point {x: 101, y: 102};
assert_eq!(p, Point {x: 111, y: 122});
p = p + 1;
|
random_line_split
|
hostname.rs
|
#![crate_name = "uu_hostname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alan Andrade <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with:
*
* https://www.opensource.apple.com/source/shell_cmds/shell_cmds-170/hostname/hostname.c?txt
*/
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::collections::hash_set::HashSet;
use std::iter::repeat;
use std::str;
use std::io::Write;
use std::net::ToSocketAddrs;
static NAME: &'static str = "hostname";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
extern {
fn gethostname(name: *mut libc::c_char, namelen: libc::size_t) -> libc::c_int;
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
extern {
fn sethostname(name: *const libc::c_char, namelen: libc::c_int) -> libc::c_int;
}
#[cfg(target_os = "linux")]
extern {
fn sethostname(name: *const libc::c_char, namelen: libc::size_t) -> libc::c_int;
}
pub fn uumain(args: Vec<String>) -> i32 {
let program = &args[0];
let mut opts = Options::new();
opts.optflag("d", "domain", "Display the name of the DNS domain if possible");
opts.optflag("i", "ip-address", "Display the network address(es) of the host");
opts.optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)"); // TODO: support --long
opts.optflag("s", "short", "Display the short hostname (the portion before the first dot) if possible");
opts.optflag("h", "help", "Show help");
opts.optflag("V", "version", "Show program's version");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
_ => { help_menu(program, opts); return 0; }
};
if matches.opt_present("h") {
help_menu(program, opts);
return 0
}
if matches.opt_present("V") { version(); return 0 }
match matches.free.len() {
0 => {
let hostname = xgethostname();
if matches.opt_present("i") {
// XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later.
// This should use std::net::lookup_host, but that is still marked unstable.
let hostname = hostname + ":1";
match hostname.to_socket_addrs() {
Ok(addresses) => {
let mut hashset = HashSet::new();
let mut output = String::new();
for addr in addresses {
// XXX: not sure why this is necessary...
if!hashset.contains(&addr) {
let mut ip = format!("{}", addr);
if ip.ends_with(":1") {
ip = ip[..ip.len()-2].to_owned();
}
output.push_str(&ip);
output.push_str(" ");
hashset.insert(addr.clone());
}
}
let len = output.len();
if len > 0 {
println!("{}", &output[0.. len - 1]);
}
}
Err(f) => {
show_error!("{}", f);
return 1;
}
}
} else {
if matches.opt_present("s") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
if ci.is_some() {
println!("{}", &hostname[0.. ci.unwrap().0]);
return 0;
}
} else if matches.opt_present("d") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
if ci.is_some() {
println!("{}", &hostname[ci.unwrap().0 + 1.. ]);
return 0;
}
}
println!("{}", hostname);
}
}
1 => xsethostname(matches.free.last().unwrap()),
_ => help_menu(program, opts)
};
0
}
fn version() {
println!("{} {}", NAME, VERSION);
}
fn help_menu(program: &str, options: Options)
|
fn xgethostname() -> String {
let namelen = 256usize;
let mut name : Vec<u8> = repeat(0).take(namelen).collect();
let err = unsafe {
gethostname (name.as_mut_ptr() as *mut libc::c_char,
namelen as libc::size_t)
};
if err!= 0 {
panic!("Cannot determine hostname");
}
let last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen);
str::from_utf8(&name[..last_char]).unwrap().to_owned()
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
fn xsethostname(name: &str) {
let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect();
let err = unsafe {
sethostname (vec_name.as_ptr(), vec_name.len() as libc::c_int)
};
if err!= 0 {
println!("Cannot set hostname to {}", name);
}
}
#[cfg(target_os = "linux")]
fn xsethostname(name: &str) {
let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect();
let err = unsafe {
sethostname (vec_name.as_ptr(), vec_name.len() as libc::size_t)
};
if err!= 0 {
println!("Cannot set hostname to {}", name);
}
}
|
{
version();
println!("");
println!("Usage:");
println!(" {} [OPTION]... [HOSTNAME]", program);
println!("");
print!("{}", options.usage("Print or set the system's host name."));
}
|
identifier_body
|
hostname.rs
|
#![crate_name = "uu_hostname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alan Andrade <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with:
*
* https://www.opensource.apple.com/source/shell_cmds/shell_cmds-170/hostname/hostname.c?txt
*/
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::collections::hash_set::HashSet;
use std::iter::repeat;
use std::str;
use std::io::Write;
use std::net::ToSocketAddrs;
static NAME: &'static str = "hostname";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
extern {
fn gethostname(name: *mut libc::c_char, namelen: libc::size_t) -> libc::c_int;
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
extern {
fn sethostname(name: *const libc::c_char, namelen: libc::c_int) -> libc::c_int;
}
#[cfg(target_os = "linux")]
extern {
fn sethostname(name: *const libc::c_char, namelen: libc::size_t) -> libc::c_int;
}
pub fn uumain(args: Vec<String>) -> i32 {
let program = &args[0];
let mut opts = Options::new();
opts.optflag("d", "domain", "Display the name of the DNS domain if possible");
opts.optflag("i", "ip-address", "Display the network address(es) of the host");
opts.optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)"); // TODO: support --long
opts.optflag("s", "short", "Display the short hostname (the portion before the first dot) if possible");
opts.optflag("h", "help", "Show help");
opts.optflag("V", "version", "Show program's version");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
_ => { help_menu(program, opts); return 0; }
};
if matches.opt_present("h") {
help_menu(program, opts);
return 0
}
if matches.opt_present("V") { version(); return 0 }
match matches.free.len() {
0 => {
let hostname = xgethostname();
if matches.opt_present("i") {
// XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later.
// This should use std::net::lookup_host, but that is still marked unstable.
let hostname = hostname + ":1";
match hostname.to_socket_addrs() {
Ok(addresses) => {
let mut hashset = HashSet::new();
let mut output = String::new();
for addr in addresses {
// XXX: not sure why this is necessary...
if!hashset.contains(&addr) {
let mut ip = format!("{}", addr);
if ip.ends_with(":1") {
ip = ip[..ip.len()-2].to_owned();
}
output.push_str(&ip);
output.push_str(" ");
hashset.insert(addr.clone());
}
}
let len = output.len();
if len > 0 {
println!("{}", &output[0.. len - 1]);
}
}
Err(f) => {
show_error!("{}", f);
return 1;
}
}
} else {
if matches.opt_present("s") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
if ci.is_some() {
println!("{}", &hostname[0.. ci.unwrap().0]);
return 0;
}
} else if matches.opt_present("d") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
if ci.is_some() {
println!("{}", &hostname[ci.unwrap().0 + 1.. ]);
return 0;
}
}
println!("{}", hostname);
}
}
1 => xsethostname(matches.free.last().unwrap()),
_ => help_menu(program, opts)
};
0
}
fn version() {
println!("{} {}", NAME, VERSION);
}
fn help_menu(program: &str, options: Options) {
version();
println!("");
println!("Usage:");
println!(" {} [OPTION]... [HOSTNAME]", program);
println!("");
print!("{}", options.usage("Print or set the system's host name."));
}
fn
|
() -> String {
let namelen = 256usize;
let mut name : Vec<u8> = repeat(0).take(namelen).collect();
let err = unsafe {
gethostname (name.as_mut_ptr() as *mut libc::c_char,
namelen as libc::size_t)
};
if err!= 0 {
panic!("Cannot determine hostname");
}
let last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen);
str::from_utf8(&name[..last_char]).unwrap().to_owned()
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
fn xsethostname(name: &str) {
let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect();
let err = unsafe {
sethostname (vec_name.as_ptr(), vec_name.len() as libc::c_int)
};
if err!= 0 {
println!("Cannot set hostname to {}", name);
}
}
#[cfg(target_os = "linux")]
fn xsethostname(name: &str) {
let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect();
let err = unsafe {
sethostname (vec_name.as_ptr(), vec_name.len() as libc::size_t)
};
if err!= 0 {
println!("Cannot set hostname to {}", name);
}
}
|
xgethostname
|
identifier_name
|
hostname.rs
|
#![crate_name = "uu_hostname"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Alan Andrade <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with:
*
* https://www.opensource.apple.com/source/shell_cmds/shell_cmds-170/hostname/hostname.c?txt
*/
extern crate getopts;
extern crate libc;
#[macro_use]
extern crate uucore;
use getopts::Options;
use std::collections::hash_set::HashSet;
use std::iter::repeat;
use std::str;
use std::io::Write;
use std::net::ToSocketAddrs;
static NAME: &'static str = "hostname";
static VERSION: &'static str = env!("CARGO_PKG_VERSION");
extern {
fn gethostname(name: *mut libc::c_char, namelen: libc::size_t) -> libc::c_int;
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
extern {
fn sethostname(name: *const libc::c_char, namelen: libc::c_int) -> libc::c_int;
}
#[cfg(target_os = "linux")]
extern {
fn sethostname(name: *const libc::c_char, namelen: libc::size_t) -> libc::c_int;
}
pub fn uumain(args: Vec<String>) -> i32 {
let program = &args[0];
let mut opts = Options::new();
opts.optflag("d", "domain", "Display the name of the DNS domain if possible");
opts.optflag("i", "ip-address", "Display the network address(es) of the host");
opts.optflag("f", "fqdn", "Display the FQDN (Fully Qualified Domain Name) (default)"); // TODO: support --long
opts.optflag("s", "short", "Display the short hostname (the portion before the first dot) if possible");
opts.optflag("h", "help", "Show help");
opts.optflag("V", "version", "Show program's version");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
_ => { help_menu(program, opts); return 0; }
};
if matches.opt_present("h") {
help_menu(program, opts);
return 0
}
if matches.opt_present("V") { version(); return 0 }
match matches.free.len() {
0 => {
let hostname = xgethostname();
if matches.opt_present("i") {
// XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later.
// This should use std::net::lookup_host, but that is still marked unstable.
let hostname = hostname + ":1";
match hostname.to_socket_addrs() {
Ok(addresses) => {
let mut hashset = HashSet::new();
let mut output = String::new();
for addr in addresses {
// XXX: not sure why this is necessary...
if!hashset.contains(&addr) {
let mut ip = format!("{}", addr);
if ip.ends_with(":1") {
ip = ip[..ip.len()-2].to_owned();
}
output.push_str(&ip);
output.push_str(" ");
hashset.insert(addr.clone());
}
}
let len = output.len();
|
show_error!("{}", f);
return 1;
}
}
} else {
if matches.opt_present("s") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
if ci.is_some() {
println!("{}", &hostname[0.. ci.unwrap().0]);
return 0;
}
} else if matches.opt_present("d") {
let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
let ci = it.next();
if ci.is_some() {
println!("{}", &hostname[ci.unwrap().0 + 1.. ]);
return 0;
}
}
println!("{}", hostname);
}
}
1 => xsethostname(matches.free.last().unwrap()),
_ => help_menu(program, opts)
};
0
}
fn version() {
println!("{} {}", NAME, VERSION);
}
fn help_menu(program: &str, options: Options) {
version();
println!("");
println!("Usage:");
println!(" {} [OPTION]... [HOSTNAME]", program);
println!("");
print!("{}", options.usage("Print or set the system's host name."));
}
fn xgethostname() -> String {
let namelen = 256usize;
let mut name : Vec<u8> = repeat(0).take(namelen).collect();
let err = unsafe {
gethostname (name.as_mut_ptr() as *mut libc::c_char,
namelen as libc::size_t)
};
if err!= 0 {
panic!("Cannot determine hostname");
}
let last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen);
str::from_utf8(&name[..last_char]).unwrap().to_owned()
}
#[cfg(any(target_os = "macos", target_os = "freebsd"))]
fn xsethostname(name: &str) {
let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect();
let err = unsafe {
sethostname (vec_name.as_ptr(), vec_name.len() as libc::c_int)
};
if err!= 0 {
println!("Cannot set hostname to {}", name);
}
}
#[cfg(target_os = "linux")]
fn xsethostname(name: &str) {
let vec_name: Vec<libc::c_char> = name.bytes().map(|c| c as libc::c_char).collect();
let err = unsafe {
sethostname (vec_name.as_ptr(), vec_name.len() as libc::size_t)
};
if err!= 0 {
println!("Cannot set hostname to {}", name);
}
}
|
if len > 0 {
println!("{}", &output[0 .. len - 1]);
}
}
Err(f) => {
|
random_line_split
|
issue-2149.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.
trait vec_monad<A> {
fn bind<B>(&self, f: |A| -> Vec<B> );
}
impl<A> vec_monad<A> for Vec<A> {
fn
|
<B>(&self, f: |A| -> Vec<B> ) {
let mut r = fail!();
for elt in self.iter() { r = r + f(*elt); }
//~^ ERROR the type of this value must be known
}
}
fn main() {
["hi"].bind(|x| [x] );
//~^ ERROR type `[&str,..1]` does not implement any method in scope named `bind`
}
|
bind
|
identifier_name
|
issue-2149.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.
trait vec_monad<A> {
fn bind<B>(&self, f: |A| -> Vec<B> );
}
impl<A> vec_monad<A> for Vec<A> {
fn bind<B>(&self, f: |A| -> Vec<B> ) {
let mut r = fail!();
for elt in self.iter() { r = r + f(*elt); }
//~^ ERROR the type of this value must be known
}
}
fn main()
|
{
["hi"].bind(|x| [x] );
//~^ ERROR type `[&str, ..1]` does not implement any method in scope named `bind`
}
|
identifier_body
|
|
issue-2149.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.
trait vec_monad<A> {
fn bind<B>(&self, f: |A| -> Vec<B> );
}
impl<A> vec_monad<A> for Vec<A> {
fn bind<B>(&self, f: |A| -> Vec<B> ) {
|
let mut r = fail!();
for elt in self.iter() { r = r + f(*elt); }
//~^ ERROR the type of this value must be known
}
}
fn main() {
["hi"].bind(|x| [x] );
//~^ ERROR type `[&str,..1]` does not implement any method in scope named `bind`
}
|
random_line_split
|
|
log_syntax-trace_macros-macro-locations.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.
// run-pass
// pretty-expanded FIXME #23616
#![feature(trace_macros, log_syntax)]
// make sure these macros can be used as in the various places that
// macros can occur.
// items
trace_macros!(false);
log_syntax!();
|
fn main() {
// statements
trace_macros!(false);
log_syntax!();
// expressions
(trace_macros!(false),
log_syntax!());
}
|
random_line_split
|
|
log_syntax-trace_macros-macro-locations.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.
// run-pass
// pretty-expanded FIXME #23616
#![feature(trace_macros, log_syntax)]
// make sure these macros can be used as in the various places that
// macros can occur.
// items
trace_macros!(false);
log_syntax!();
fn
|
() {
// statements
trace_macros!(false);
log_syntax!();
// expressions
(trace_macros!(false),
log_syntax!());
}
|
main
|
identifier_name
|
log_syntax-trace_macros-macro-locations.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.
// run-pass
// pretty-expanded FIXME #23616
#![feature(trace_macros, log_syntax)]
// make sure these macros can be used as in the various places that
// macros can occur.
// items
trace_macros!(false);
log_syntax!();
fn main()
|
{
// statements
trace_macros!(false);
log_syntax!();
// expressions
(trace_macros!(false),
log_syntax!());
}
|
identifier_body
|
|
error.rs
|
use std::path::PathBuf;
use std::error::Error;
use std::fmt;
use super::Environment;
use self::ConfigError::*;
use term_painter::Color::White;
use term_painter::ToStyle;
/// The type of a configuration parsing error.
#[derive(Debug, PartialEq, Clone)]
pub struct ParsingError {
/// Start and end byte indices into the source code where parsing failed.
pub byte_range: (usize, usize),
/// The (line, column) in the source code where parsing failure began.
pub start: (usize, usize),
/// The (line, column) in the source code where parsing failure ended.
pub end: (usize, usize),
/// A description of the parsing error that occured.
pub desc: String,
}
/// The type of a configuration error.
#[derive(Debug, PartialEq, Clone)]
pub enum ConfigError {
/// The current working directory could not be determined.
BadCWD,
/// The configuration file was not found.
NotFound,
/// There was an I/O error while reading the configuration file.
IOError,
/// The path at which the configuration file was found was invalid.
///
/// Parameters: (path, reason)
BadFilePath(PathBuf, &'static str),
/// An environment specified in `ROCKET_ENV` is invalid.
///
/// Parameters: (environment_name)
BadEnv(String),
/// An environment specified as a table `[environment]` is invalid.
///
/// Parameters: (environment_name, filename)
BadEntry(String, PathBuf),
/// A config key was specified with a value of the wrong type.
///
/// Parameters: (entry_name, expected_type, actual_type, filename)
BadType(String, &'static str, &'static str, PathBuf),
/// There was a TOML parsing error.
///
/// Parameters: (toml_source_string, filename, error_list)
ParseError(String, PathBuf, Vec<ParsingError>),
/// There was a TOML parsing error in a config environment variable.
///
/// Parameters: (env_key, env_value, expected type)
BadEnvVal(String, String, &'static str),
}
impl ConfigError {
/// Prints this configuration error with Rocket formatting.
pub fn pretty_print(&self) {
let valid_envs = Environment::valid();
match *self {
BadCWD => error!("couldn't get current working directory"),
NotFound => error!("config file was not found"),
IOError => error!("failed reading the config file: IO error"),
BadFilePath(ref path, reason) => {
error!("configuration file path '{:?}' is invalid", path);
info_!("{}", reason);
}
BadEntry(ref name, ref filename) => {
let valid_entries = format!("{}, and global", valid_envs);
error!("[{}] is not a known configuration environment", name);
info_!("in {:?}", White.paint(filename));
info_!("valid environments are: {}", White.paint(valid_entries));
}
BadEnv(ref name) => {
error!("'{}' is not a valid ROCKET_ENV value", name);
info_!("valid environments are: {}", White.paint(valid_envs));
}
BadType(ref name, expected, actual, ref filename) => {
error!("'{}' key could not be parsed", name);
info_!("in {:?}", White.paint(filename));
info_!("expected value to be {}, but found {}",
White.paint(expected), White.paint(actual));
}
ParseError(ref source, ref filename, ref errors) => {
for error in errors {
let (lo, hi) = error.byte_range;
let (line, col) = error.start;
let error_source = &source[lo..hi];
error!("config file could not be parsed as TOML");
info_!("at {:?}:{}:{}", White.paint(filename), line + 1, col + 1);
trace_!("'{}' - {}", error_source, White.paint(&error.desc));
}
}
BadEnvVal(ref key, ref value, ref expected) =>
|
}
}
/// Whether this error is of `NotFound` variant.
#[inline(always)]
pub fn is_not_found(&self) -> bool {
match *self {
NotFound => true,
_ => false
}
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BadCWD => write!(f, "couldn't get current working directory"),
NotFound => write!(f, "config file was not found"),
IOError => write!(f, "I/O error while reading the config file"),
BadFilePath(ref p, _) => write!(f, "{:?} is not a valid config path", p),
BadEnv(ref e) => write!(f, "{:?} is not a valid `ROCKET_ENV` value", e),
ParseError(..) => write!(f, "the config file contains invalid TOML"),
BadEntry(ref e, _) => {
write!(f, "{:?} is not a valid `[environment]` entry", e)
}
BadType(ref n, e, a, _) => {
write!(f, "type mismatch for '{}'. expected {}, found {}", n, e, a)
}
BadEnvVal(ref k, ref v, _) => {
write!(f, "environment variable '{}={}' could not be parsed", k, v)
}
}
}
}
impl Error for ConfigError {
fn description(&self) -> &str {
match *self {
BadCWD => "the current working directory could not be determined",
NotFound => "config file was not found",
IOError => "there was an I/O error while reading the config file",
BadFilePath(..) => "the config file path is invalid",
BadEntry(..) => "an environment specified as `[environment]` is invalid",
BadEnv(..) => "the environment specified in `ROCKET_ENV` is invalid",
ParseError(..) => "the config file contains invalid TOML",
BadType(..) => "a key was specified with a value of the wrong type",
BadEnvVal(..) => "an environment variable could not be parsed",
}
}
}
|
{
error!("environment variable '{}={}' could not be parsed",
White.paint(key), White.paint(value));
info_!("value for {:?} must be {}",
White.paint(key), White.paint(expected))
}
|
conditional_block
|
error.rs
|
use std::path::PathBuf;
use std::error::Error;
use std::fmt;
use super::Environment;
use self::ConfigError::*;
use term_painter::Color::White;
use term_painter::ToStyle;
/// The type of a configuration parsing error.
#[derive(Debug, PartialEq, Clone)]
pub struct ParsingError {
/// Start and end byte indices into the source code where parsing failed.
pub byte_range: (usize, usize),
/// The (line, column) in the source code where parsing failure began.
pub start: (usize, usize),
/// The (line, column) in the source code where parsing failure ended.
pub end: (usize, usize),
/// A description of the parsing error that occured.
pub desc: String,
}
/// The type of a configuration error.
#[derive(Debug, PartialEq, Clone)]
pub enum ConfigError {
/// The current working directory could not be determined.
BadCWD,
/// The configuration file was not found.
NotFound,
/// There was an I/O error while reading the configuration file.
IOError,
/// The path at which the configuration file was found was invalid.
///
/// Parameters: (path, reason)
BadFilePath(PathBuf, &'static str),
/// An environment specified in `ROCKET_ENV` is invalid.
///
/// Parameters: (environment_name)
BadEnv(String),
/// An environment specified as a table `[environment]` is invalid.
///
/// Parameters: (environment_name, filename)
BadEntry(String, PathBuf),
/// A config key was specified with a value of the wrong type.
///
/// Parameters: (entry_name, expected_type, actual_type, filename)
BadType(String, &'static str, &'static str, PathBuf),
/// There was a TOML parsing error.
///
/// Parameters: (toml_source_string, filename, error_list)
ParseError(String, PathBuf, Vec<ParsingError>),
/// There was a TOML parsing error in a config environment variable.
///
/// Parameters: (env_key, env_value, expected type)
BadEnvVal(String, String, &'static str),
}
impl ConfigError {
/// Prints this configuration error with Rocket formatting.
pub fn pretty_print(&self) {
let valid_envs = Environment::valid();
match *self {
BadCWD => error!("couldn't get current working directory"),
NotFound => error!("config file was not found"),
IOError => error!("failed reading the config file: IO error"),
BadFilePath(ref path, reason) => {
error!("configuration file path '{:?}' is invalid", path);
info_!("{}", reason);
}
BadEntry(ref name, ref filename) => {
let valid_entries = format!("{}, and global", valid_envs);
error!("[{}] is not a known configuration environment", name);
info_!("in {:?}", White.paint(filename));
info_!("valid environments are: {}", White.paint(valid_entries));
}
BadEnv(ref name) => {
error!("'{}' is not a valid ROCKET_ENV value", name);
info_!("valid environments are: {}", White.paint(valid_envs));
}
BadType(ref name, expected, actual, ref filename) => {
error!("'{}' key could not be parsed", name);
info_!("in {:?}", White.paint(filename));
info_!("expected value to be {}, but found {}",
White.paint(expected), White.paint(actual));
}
ParseError(ref source, ref filename, ref errors) => {
for error in errors {
let (lo, hi) = error.byte_range;
let (line, col) = error.start;
let error_source = &source[lo..hi];
error!("config file could not be parsed as TOML");
info_!("at {:?}:{}:{}", White.paint(filename), line + 1, col + 1);
trace_!("'{}' - {}", error_source, White.paint(&error.desc));
}
}
BadEnvVal(ref key, ref value, ref expected) => {
error!("environment variable '{}={}' could not be parsed",
White.paint(key), White.paint(value));
info_!("value for {:?} must be {}",
White.paint(key), White.paint(expected))
}
}
}
/// Whether this error is of `NotFound` variant.
#[inline(always)]
pub fn is_not_found(&self) -> bool {
match *self {
NotFound => true,
_ => false
}
}
}
impl fmt::Display for ConfigError {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BadCWD => write!(f, "couldn't get current working directory"),
NotFound => write!(f, "config file was not found"),
IOError => write!(f, "I/O error while reading the config file"),
BadFilePath(ref p, _) => write!(f, "{:?} is not a valid config path", p),
BadEnv(ref e) => write!(f, "{:?} is not a valid `ROCKET_ENV` value", e),
ParseError(..) => write!(f, "the config file contains invalid TOML"),
BadEntry(ref e, _) => {
write!(f, "{:?} is not a valid `[environment]` entry", e)
}
BadType(ref n, e, a, _) => {
write!(f, "type mismatch for '{}'. expected {}, found {}", n, e, a)
}
BadEnvVal(ref k, ref v, _) => {
write!(f, "environment variable '{}={}' could not be parsed", k, v)
}
}
}
}
impl Error for ConfigError {
fn description(&self) -> &str {
match *self {
BadCWD => "the current working directory could not be determined",
NotFound => "config file was not found",
IOError => "there was an I/O error while reading the config file",
BadFilePath(..) => "the config file path is invalid",
BadEntry(..) => "an environment specified as `[environment]` is invalid",
BadEnv(..) => "the environment specified in `ROCKET_ENV` is invalid",
ParseError(..) => "the config file contains invalid TOML",
BadType(..) => "a key was specified with a value of the wrong type",
BadEnvVal(..) => "an environment variable could not be parsed",
}
}
}
|
fmt
|
identifier_name
|
error.rs
|
use std::path::PathBuf;
use std::error::Error;
use std::fmt;
use super::Environment;
use self::ConfigError::*;
use term_painter::Color::White;
use term_painter::ToStyle;
/// The type of a configuration parsing error.
#[derive(Debug, PartialEq, Clone)]
pub struct ParsingError {
/// Start and end byte indices into the source code where parsing failed.
pub byte_range: (usize, usize),
/// The (line, column) in the source code where parsing failure began.
pub start: (usize, usize),
/// The (line, column) in the source code where parsing failure ended.
pub end: (usize, usize),
/// A description of the parsing error that occured.
pub desc: String,
}
/// The type of a configuration error.
#[derive(Debug, PartialEq, Clone)]
pub enum ConfigError {
/// The current working directory could not be determined.
BadCWD,
/// The configuration file was not found.
NotFound,
/// There was an I/O error while reading the configuration file.
IOError,
/// The path at which the configuration file was found was invalid.
///
/// Parameters: (path, reason)
BadFilePath(PathBuf, &'static str),
/// An environment specified in `ROCKET_ENV` is invalid.
///
/// Parameters: (environment_name)
BadEnv(String),
/// An environment specified as a table `[environment]` is invalid.
///
/// Parameters: (environment_name, filename)
BadEntry(String, PathBuf),
/// A config key was specified with a value of the wrong type.
///
/// Parameters: (entry_name, expected_type, actual_type, filename)
BadType(String, &'static str, &'static str, PathBuf),
/// There was a TOML parsing error.
///
/// Parameters: (toml_source_string, filename, error_list)
ParseError(String, PathBuf, Vec<ParsingError>),
/// There was a TOML parsing error in a config environment variable.
///
/// Parameters: (env_key, env_value, expected type)
BadEnvVal(String, String, &'static str),
}
impl ConfigError {
/// Prints this configuration error with Rocket formatting.
pub fn pretty_print(&self) {
let valid_envs = Environment::valid();
match *self {
BadCWD => error!("couldn't get current working directory"),
|
error!("configuration file path '{:?}' is invalid", path);
info_!("{}", reason);
}
BadEntry(ref name, ref filename) => {
let valid_entries = format!("{}, and global", valid_envs);
error!("[{}] is not a known configuration environment", name);
info_!("in {:?}", White.paint(filename));
info_!("valid environments are: {}", White.paint(valid_entries));
}
BadEnv(ref name) => {
error!("'{}' is not a valid ROCKET_ENV value", name);
info_!("valid environments are: {}", White.paint(valid_envs));
}
BadType(ref name, expected, actual, ref filename) => {
error!("'{}' key could not be parsed", name);
info_!("in {:?}", White.paint(filename));
info_!("expected value to be {}, but found {}",
White.paint(expected), White.paint(actual));
}
ParseError(ref source, ref filename, ref errors) => {
for error in errors {
let (lo, hi) = error.byte_range;
let (line, col) = error.start;
let error_source = &source[lo..hi];
error!("config file could not be parsed as TOML");
info_!("at {:?}:{}:{}", White.paint(filename), line + 1, col + 1);
trace_!("'{}' - {}", error_source, White.paint(&error.desc));
}
}
BadEnvVal(ref key, ref value, ref expected) => {
error!("environment variable '{}={}' could not be parsed",
White.paint(key), White.paint(value));
info_!("value for {:?} must be {}",
White.paint(key), White.paint(expected))
}
}
}
/// Whether this error is of `NotFound` variant.
#[inline(always)]
pub fn is_not_found(&self) -> bool {
match *self {
NotFound => true,
_ => false
}
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
BadCWD => write!(f, "couldn't get current working directory"),
NotFound => write!(f, "config file was not found"),
IOError => write!(f, "I/O error while reading the config file"),
BadFilePath(ref p, _) => write!(f, "{:?} is not a valid config path", p),
BadEnv(ref e) => write!(f, "{:?} is not a valid `ROCKET_ENV` value", e),
ParseError(..) => write!(f, "the config file contains invalid TOML"),
BadEntry(ref e, _) => {
write!(f, "{:?} is not a valid `[environment]` entry", e)
}
BadType(ref n, e, a, _) => {
write!(f, "type mismatch for '{}'. expected {}, found {}", n, e, a)
}
BadEnvVal(ref k, ref v, _) => {
write!(f, "environment variable '{}={}' could not be parsed", k, v)
}
}
}
}
impl Error for ConfigError {
fn description(&self) -> &str {
match *self {
BadCWD => "the current working directory could not be determined",
NotFound => "config file was not found",
IOError => "there was an I/O error while reading the config file",
BadFilePath(..) => "the config file path is invalid",
BadEntry(..) => "an environment specified as `[environment]` is invalid",
BadEnv(..) => "the environment specified in `ROCKET_ENV` is invalid",
ParseError(..) => "the config file contains invalid TOML",
BadType(..) => "a key was specified with a value of the wrong type",
BadEnvVal(..) => "an environment variable could not be parsed",
}
}
}
|
NotFound => error!("config file was not found"),
IOError => error!("failed reading the config file: IO error"),
BadFilePath(ref path, reason) => {
|
random_line_split
|
mode.rs
|
use state::State;
use std::marker::PhantomData;
use typeahead::Parse;
pub trait Transition<K>
where
K: Ord,
K: Copy,
K: Parse,
{
fn name(&self) -> &'static str;
fn transition(&self, state: &mut State<K>) -> Mode<K>;
}
#[derive(Clone, Copy, Debug)]
pub struct NormalMode<K> {
t: PhantomData<K>,
}
/// Used by `PendingMode` to remember what mode to transition to next.
#[derive(Clone, Copy, Debug)]
pub enum NextMode {
Normal,
Insert,
}
#[derive(Clone, Copy, Debug)]
pub struct PendingMode<K> {
t: PhantomData<K>,
pub next_mode: NextMode, // Mode to return to after motion or text object.
}
#[derive(Clone, Copy, Debug)]
pub struct InsertMode<K> {
t: PhantomData<K>,
replace_mode: bool,
}
#[derive(Clone, Copy, Debug)]
pub enum
|
<K> {
Normal(NormalMode<K>),
Pending(PendingMode<K>),
Insert(InsertMode<K>),
}
pub fn normal<K>() -> Mode<K> {
Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} })
}
pub fn recast_normal<K>(orig: &NormalMode<K>) -> Mode<K> {
Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} })
}
pub fn pending<K>(next_mode: NextMode) -> Mode<K> {
Mode::Pending(PendingMode::<K> {
t: PhantomData::<K> {},
next_mode: next_mode,
})
}
pub fn recast_pending<K>(orig: &PendingMode<K>) -> Mode<K> {
Mode::Pending(PendingMode::<K> {
t: PhantomData::<K> {},
next_mode: orig.next_mode,
})
}
pub fn insert<K>() -> Mode<K> {
Mode::Insert(InsertMode::<K> {
t: PhantomData::<K> {},
replace_mode: false,
})
}
pub fn replace<K>() -> Mode<K> {
Mode::Insert(InsertMode::<K> {
t: PhantomData::<K> {},
replace_mode: true,
})
}
impl<K> Transition<K> for Mode<K>
where
K: Ord,
K: Copy,
K: Parse,
{
fn name(&self) -> &'static str {
match *self {
Mode::Normal(x) => x.name(),
Mode::Pending(x) => x.name(),
Mode::Insert(x) => x.name(),
}
}
fn transition(&self, state: &mut State<K>) -> Mode<K> {
match *self {
Mode::Normal(x) => x.transition(state),
Mode::Pending(x) => x.transition(state),
Mode::Insert(x) => x.transition(state),
}
}
}
|
Mode
|
identifier_name
|
mode.rs
|
use state::State;
use std::marker::PhantomData;
use typeahead::Parse;
pub trait Transition<K>
where
K: Ord,
K: Copy,
|
{
fn name(&self) -> &'static str;
fn transition(&self, state: &mut State<K>) -> Mode<K>;
}
#[derive(Clone, Copy, Debug)]
pub struct NormalMode<K> {
t: PhantomData<K>,
}
/// Used by `PendingMode` to remember what mode to transition to next.
#[derive(Clone, Copy, Debug)]
pub enum NextMode {
Normal,
Insert,
}
#[derive(Clone, Copy, Debug)]
pub struct PendingMode<K> {
t: PhantomData<K>,
pub next_mode: NextMode, // Mode to return to after motion or text object.
}
#[derive(Clone, Copy, Debug)]
pub struct InsertMode<K> {
t: PhantomData<K>,
replace_mode: bool,
}
#[derive(Clone, Copy, Debug)]
pub enum Mode<K> {
Normal(NormalMode<K>),
Pending(PendingMode<K>),
Insert(InsertMode<K>),
}
pub fn normal<K>() -> Mode<K> {
Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} })
}
pub fn recast_normal<K>(orig: &NormalMode<K>) -> Mode<K> {
Mode::Normal(NormalMode::<K> { t: PhantomData::<K> {} })
}
pub fn pending<K>(next_mode: NextMode) -> Mode<K> {
Mode::Pending(PendingMode::<K> {
t: PhantomData::<K> {},
next_mode: next_mode,
})
}
pub fn recast_pending<K>(orig: &PendingMode<K>) -> Mode<K> {
Mode::Pending(PendingMode::<K> {
t: PhantomData::<K> {},
next_mode: orig.next_mode,
})
}
pub fn insert<K>() -> Mode<K> {
Mode::Insert(InsertMode::<K> {
t: PhantomData::<K> {},
replace_mode: false,
})
}
pub fn replace<K>() -> Mode<K> {
Mode::Insert(InsertMode::<K> {
t: PhantomData::<K> {},
replace_mode: true,
})
}
impl<K> Transition<K> for Mode<K>
where
K: Ord,
K: Copy,
K: Parse,
{
fn name(&self) -> &'static str {
match *self {
Mode::Normal(x) => x.name(),
Mode::Pending(x) => x.name(),
Mode::Insert(x) => x.name(),
}
}
fn transition(&self, state: &mut State<K>) -> Mode<K> {
match *self {
Mode::Normal(x) => x.transition(state),
Mode::Pending(x) => x.transition(state),
Mode::Insert(x) => x.transition(state),
}
}
}
|
K: Parse,
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.