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 |
|---|---|---|---|---|
project-fn-ret-contravariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
#![feature(rustc_attrs)]
// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an contravariant position, which affects the results.
// revisions: ok oneuse transmute krisskross
#![allow(dead_code, unused_variables)]
fn foo<'a>() -> &'a u32 { loop { } }
fn bar<T>(t: T, x: T::Output) -> T::Output
where T: FnOnce<()>
{
t()
}
#[cfg(ok)] // two instantiations: OK
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, x);
let b = bar(foo, y);
(a, b)
}
#[cfg(oneuse)] // one instantiation: OK (surprisingly)
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated
let a = bar(f, x); // this is considered ok because fn args are contravariant...
let b = bar(f, y); //...and hence we infer T to distinct values in each call.
(a, b)
}
#[cfg(transmute)] // one instantiations: BAD
fn baz<'a,'b>(x: &'a u32) -> &'static u32 {
bar(foo, x) //[transmute]~ ERROR E0495
}
#[cfg(krisskross)] // two instantiations, mixing and matching: BAD
fn transmute<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, y);
let b = bar(foo, x);
(a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623]
//[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623]
}
#[rustc_error]
fn main() |
//[ok]~^ ERROR compilation successful
//[oneuse]~^^ ERROR compilation successful
| { } | identifier_body |
project-fn-ret-contravariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
#![feature(rustc_attrs)]
// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an contravariant position, which affects the results.
// revisions: ok oneuse transmute krisskross
#![allow(dead_code, unused_variables)]
fn foo<'a>() -> &'a u32 { loop { } }
fn bar<T>(t: T, x: T::Output) -> T::Output
where T: FnOnce<()>
{
t()
}
#[cfg(ok)] // two instantiations: OK
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, x);
let b = bar(foo, y);
(a, b)
}
#[cfg(oneuse)] // one instantiation: OK (surprisingly)
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated
let a = bar(f, x); // this is considered ok because fn args are contravariant...
let b = bar(f, y); //...and hence we infer T to distinct values in each call.
(a, b)
}
#[cfg(transmute)] // one instantiations: BAD
fn baz<'a,'b>(x: &'a u32) -> &'static u32 {
bar(foo, x) //[transmute]~ ERROR E0495
}
#[cfg(krisskross)] // two instantiations, mixing and matching: BAD
fn | <'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, y);
let b = bar(foo, x);
(a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623]
//[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623]
}
#[rustc_error]
fn main() { }
//[ok]~^ ERROR compilation successful
//[oneuse]~^^ ERROR compilation successful
| transmute | identifier_name |
project-fn-ret-contravariant.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
#![feature(rustc_attrs)]
// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an contravariant position, which affects the results.
// revisions: ok oneuse transmute krisskross
#![allow(dead_code, unused_variables)]
fn foo<'a>() -> &'a u32 { loop { } }
fn bar<T>(t: T, x: T::Output) -> T::Output
where T: FnOnce<()>
{
t()
}
#[cfg(ok)] // two instantiations: OK
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, x);
let b = bar(foo, y);
(a, b)
}
#[cfg(oneuse)] // one instantiation: OK (surprisingly)
fn baz<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let f /* : fn() -> &'static u32 */ = foo; // <-- inferred type annotated
let a = bar(f, x); // this is considered ok because fn args are contravariant...
let b = bar(f, y); //...and hence we infer T to distinct values in each call.
(a, b)
}
#[cfg(transmute)] // one instantiations: BAD
fn baz<'a,'b>(x: &'a u32) -> &'static u32 {
bar(foo, x) //[transmute]~ ERROR E0495
}
#[cfg(krisskross)] // two instantiations, mixing and matching: BAD
fn transmute<'a,'b>(x: &'a u32, y: &'b u32) -> (&'a u32, &'b u32) {
let a = bar(foo, y);
let b = bar(foo, x); | fn main() { }
//[ok]~^ ERROR compilation successful
//[oneuse]~^^ ERROR compilation successful | (a, b) //[krisskross]~ ERROR 55:5: 55:6: lifetime mismatch [E0623]
//[krisskross]~^ ERROR 55:8: 55:9: lifetime mismatch [E0623]
}
#[rustc_error] | random_line_split |
plugin_class.rs | use node::inner_node::node_from_ptr;
use node::{String, Uri};
use world::World;
#[derive(Clone)]
pub struct PluginClass<'w> {
pub(crate) ptr: *const ::lilv_sys::LilvPluginClass,
pub(crate) world: &'w World,
}
impl<'w> PluginClass<'w> {
pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &World) -> PluginClass {
PluginClass { ptr, world }
}
pub fn | (&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) }
}
pub fn uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) }
}
pub fn label(&self) -> &String<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_label(self.ptr)) }
}
}
| parent_uri | identifier_name |
plugin_class.rs | use node::inner_node::node_from_ptr;
use node::{String, Uri};
use world::World;
#[derive(Clone)]
pub struct PluginClass<'w> {
pub(crate) ptr: *const ::lilv_sys::LilvPluginClass,
pub(crate) world: &'w World,
}
impl<'w> PluginClass<'w> {
pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &World) -> PluginClass |
pub fn parent_uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) }
}
pub fn uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) }
}
pub fn label(&self) -> &String<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_label(self.ptr)) }
}
}
| {
PluginClass { ptr, world }
} | identifier_body |
plugin_class.rs | use node::inner_node::node_from_ptr;
use node::{String, Uri};
use world::World;
#[derive(Clone)]
pub struct PluginClass<'w> {
pub(crate) ptr: *const ::lilv_sys::LilvPluginClass,
pub(crate) world: &'w World,
}
impl<'w> PluginClass<'w> { | unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_parent_uri(self.ptr)) }
}
pub fn uri(&self) -> &Uri<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_uri(self.ptr)) }
}
pub fn label(&self) -> &String<'w> {
unsafe { node_from_ptr(::lilv_sys::lilv_plugin_class_get_label(self.ptr)) }
}
} | pub(crate) fn new(ptr: *const ::lilv_sys::LilvPluginClass, world: &World) -> PluginClass {
PluginClass { ptr, world }
}
pub fn parent_uri(&self) -> &Uri<'w> { | random_line_split |
tree.rs | use std::io::{File, BufReader};
use std::container::Container;
use std::io::{BufferedWriter};
use std::fmt::{Show, Formatter, FormatError}; | pub trait TreeNode : Show {
fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>;
}
#[deriving(PartialEq,Eq)]
pub struct Tree<I> {
instructions: Vec<I>,
}
pub struct TreeIterator<'a, I> {
tree: &'a Tree<I>,
i: uint,
}
impl<I: TreeNode> Tree<I> {
pub fn new() -> Tree<I> {
Tree{ instructions: vec!() }
}
pub fn push(&mut self, inst: I) {
self.instructions.push(inst);
}
pub fn get<'a>(&'a self, index: uint) -> &'a I {
self.instructions.get(index)
}
pub fn parse_string(text: &str) -> BancResult<Tree<I>> {
let sreader = BufReader::new(text.as_bytes());
let mut tokenizer = Tokenizer::<BufReader>::from_buf(sreader);
Tree::parse(&mut tokenizer)
}
pub fn parse_file(file: File) -> BancResult<Tree<I>> {
let mut tokenizer = Tokenizer::<File>::from_file(file);
Tree::parse(&mut tokenizer)
}
pub fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Tree<I>> {
let mut tree = Tree::new();
while! tokenizer.eof() {
let node: BancResult<Option<I>> = TreeNode::parse(tokenizer);
match node {
Ok(Some(inst)) => {
tree.push(inst);
},
Ok(None) => {
break;
},
Err(e) => {
return Err(e);
},
}
}
Ok(tree)
}
pub fn render<W: Writer>(&self, buffer: &mut BufferedWriter<W>) {
buffer.write_str(self.to_str().as_slice()).unwrap();
}
pub fn iter<'a>(&'a self) -> TreeIterator<'a, I> {
TreeIterator::new(self, 0)
}
}
impl<I: TreeNode> Container for Tree<I> {
fn len(&self) -> uint {
self.instructions.len()
}
fn is_empty(&self) -> bool {
self.instructions.is_empty()
}
}
impl<'a, I: TreeNode> TreeIterator<'a, I> {
fn new(tree: &'a Tree<I>, start: uint) -> TreeIterator<'a, I> {
TreeIterator {
tree: tree,
i: start,
}
}
fn maybe_get(&self, i: uint) -> Option<&'a I> {
if self.i < self.tree.len() {
Some(self.tree.get(i))
} else {
None
}
}
}
impl<'a, I: TreeNode> Iterator<&'a I> for TreeIterator<'a, I> {
fn next(&mut self) -> Option<&'a I> {
let o = self.maybe_get(self.i);
self.i += 1;
o
}
}
impl<'a, I: TreeNode> RandomAccessIterator<&'a I> for TreeIterator<'a, I> {
fn indexable(&self) -> uint {
self.tree.len()
}
fn idx(&mut self, i: uint) -> Option<&'a I> {
self.maybe_get(i)
}
}
impl<I: TreeNode> Show for Tree<I> {
#[allow(unused_must_use)]
fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
for inst in self.instructions.iter() {
inst.fmt(formatter);
formatter.write_char('\n');
}
Ok(())
}
} | use syntax::tokenize::{Tokenizer};
use result::BancResult;
| random_line_split |
tree.rs | use std::io::{File, BufReader};
use std::container::Container;
use std::io::{BufferedWriter};
use std::fmt::{Show, Formatter, FormatError};
use syntax::tokenize::{Tokenizer};
use result::BancResult;
pub trait TreeNode : Show {
fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>;
}
#[deriving(PartialEq,Eq)]
pub struct Tree<I> {
instructions: Vec<I>,
}
pub struct TreeIterator<'a, I> {
tree: &'a Tree<I>,
i: uint,
}
impl<I: TreeNode> Tree<I> {
pub fn new() -> Tree<I> {
Tree{ instructions: vec!() }
}
pub fn push(&mut self, inst: I) {
self.instructions.push(inst);
}
pub fn get<'a>(&'a self, index: uint) -> &'a I {
self.instructions.get(index)
}
pub fn parse_string(text: &str) -> BancResult<Tree<I>> {
let sreader = BufReader::new(text.as_bytes());
let mut tokenizer = Tokenizer::<BufReader>::from_buf(sreader);
Tree::parse(&mut tokenizer)
}
pub fn parse_file(file: File) -> BancResult<Tree<I>> {
let mut tokenizer = Tokenizer::<File>::from_file(file);
Tree::parse(&mut tokenizer)
}
pub fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Tree<I>> {
let mut tree = Tree::new();
while! tokenizer.eof() {
let node: BancResult<Option<I>> = TreeNode::parse(tokenizer);
match node {
Ok(Some(inst)) => {
tree.push(inst);
},
Ok(None) => {
break;
},
Err(e) => {
return Err(e);
},
}
}
Ok(tree)
}
pub fn render<W: Writer>(&self, buffer: &mut BufferedWriter<W>) {
buffer.write_str(self.to_str().as_slice()).unwrap();
}
pub fn iter<'a>(&'a self) -> TreeIterator<'a, I> {
TreeIterator::new(self, 0)
}
}
impl<I: TreeNode> Container for Tree<I> {
fn len(&self) -> uint {
self.instructions.len()
}
fn is_empty(&self) -> bool {
self.instructions.is_empty()
}
}
impl<'a, I: TreeNode> TreeIterator<'a, I> {
fn new(tree: &'a Tree<I>, start: uint) -> TreeIterator<'a, I> {
TreeIterator {
tree: tree,
i: start,
}
}
fn maybe_get(&self, i: uint) -> Option<&'a I> {
if self.i < self.tree.len() {
Some(self.tree.get(i))
} else {
None
}
}
}
impl<'a, I: TreeNode> Iterator<&'a I> for TreeIterator<'a, I> {
fn next(&mut self) -> Option<&'a I> {
let o = self.maybe_get(self.i);
self.i += 1;
o
}
}
impl<'a, I: TreeNode> RandomAccessIterator<&'a I> for TreeIterator<'a, I> {
fn indexable(&self) -> uint {
self.tree.len()
}
fn idx(&mut self, i: uint) -> Option<&'a I> {
self.maybe_get(i)
}
}
impl<I: TreeNode> Show for Tree<I> {
#[allow(unused_must_use)]
fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> |
}
| {
for inst in self.instructions.iter() {
inst.fmt(formatter);
formatter.write_char('\n');
}
Ok(())
} | identifier_body |
tree.rs | use std::io::{File, BufReader};
use std::container::Container;
use std::io::{BufferedWriter};
use std::fmt::{Show, Formatter, FormatError};
use syntax::tokenize::{Tokenizer};
use result::BancResult;
pub trait TreeNode : Show {
fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Option<Self>>;
}
#[deriving(PartialEq,Eq)]
pub struct Tree<I> {
instructions: Vec<I>,
}
pub struct TreeIterator<'a, I> {
tree: &'a Tree<I>,
i: uint,
}
impl<I: TreeNode> Tree<I> {
pub fn new() -> Tree<I> {
Tree{ instructions: vec!() }
}
pub fn push(&mut self, inst: I) {
self.instructions.push(inst);
}
pub fn get<'a>(&'a self, index: uint) -> &'a I {
self.instructions.get(index)
}
pub fn parse_string(text: &str) -> BancResult<Tree<I>> {
let sreader = BufReader::new(text.as_bytes());
let mut tokenizer = Tokenizer::<BufReader>::from_buf(sreader);
Tree::parse(&mut tokenizer)
}
pub fn | (file: File) -> BancResult<Tree<I>> {
let mut tokenizer = Tokenizer::<File>::from_file(file);
Tree::parse(&mut tokenizer)
}
pub fn parse<R: Reader>(tokenizer: &mut Tokenizer<R>) -> BancResult<Tree<I>> {
let mut tree = Tree::new();
while! tokenizer.eof() {
let node: BancResult<Option<I>> = TreeNode::parse(tokenizer);
match node {
Ok(Some(inst)) => {
tree.push(inst);
},
Ok(None) => {
break;
},
Err(e) => {
return Err(e);
},
}
}
Ok(tree)
}
pub fn render<W: Writer>(&self, buffer: &mut BufferedWriter<W>) {
buffer.write_str(self.to_str().as_slice()).unwrap();
}
pub fn iter<'a>(&'a self) -> TreeIterator<'a, I> {
TreeIterator::new(self, 0)
}
}
impl<I: TreeNode> Container for Tree<I> {
fn len(&self) -> uint {
self.instructions.len()
}
fn is_empty(&self) -> bool {
self.instructions.is_empty()
}
}
impl<'a, I: TreeNode> TreeIterator<'a, I> {
fn new(tree: &'a Tree<I>, start: uint) -> TreeIterator<'a, I> {
TreeIterator {
tree: tree,
i: start,
}
}
fn maybe_get(&self, i: uint) -> Option<&'a I> {
if self.i < self.tree.len() {
Some(self.tree.get(i))
} else {
None
}
}
}
impl<'a, I: TreeNode> Iterator<&'a I> for TreeIterator<'a, I> {
fn next(&mut self) -> Option<&'a I> {
let o = self.maybe_get(self.i);
self.i += 1;
o
}
}
impl<'a, I: TreeNode> RandomAccessIterator<&'a I> for TreeIterator<'a, I> {
fn indexable(&self) -> uint {
self.tree.len()
}
fn idx(&mut self, i: uint) -> Option<&'a I> {
self.maybe_get(i)
}
}
impl<I: TreeNode> Show for Tree<I> {
#[allow(unused_must_use)]
fn fmt(&self, formatter: &mut Formatter) -> Result<(), FormatError> {
for inst in self.instructions.iter() {
inst.fmt(formatter);
formatter.write_char('\n');
}
Ok(())
}
}
| parse_file | identifier_name |
filemanager_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/. */
use ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Debug, Deserialize, Serialize)]
pub struct SelectedFile {
pub id: Uuid,
pub filename: PathBuf,
pub modified: u64, | #[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(IpcSender<FileManagerResult<Vec<SelectedFile>>>),
/// Read file, return the bytes
ReadFile(IpcSender<FileManagerResult<Vec<u8>>>, Uuid),
/// Delete the FileID entry
DeleteFileID(Uuid),
/// Shut down this thread
Exit,
}
pub type FileManagerResult<T> = Result<T, FileManagerThreadError>;
#[derive(Debug, Deserialize, Serialize)]
pub enum FileManagerThreadError {
/// The selection action is invalid, nothing is selected
InvalidSelection,
/// Failure to process file information such as file name, modified time etc.
FileInfoProcessingError,
/// Failure to read the file content
ReadFileError,
} | // https://w3c.github.io/FileAPI/#dfn-type
pub type_string: String,
}
| random_line_split |
filemanager_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/. */
use ipc_channel::ipc::IpcSender;
use std::path::PathBuf;
use uuid::Uuid;
#[derive(Debug, Deserialize, Serialize)]
pub struct | {
pub id: Uuid,
pub filename: PathBuf,
pub modified: u64,
// https://w3c.github.io/FileAPI/#dfn-type
pub type_string: String,
}
#[derive(Deserialize, Serialize)]
pub enum FileManagerThreadMsg {
/// Select a single file, return triple (FileID, FileName, lastModified)
SelectFile(IpcSender<FileManagerResult<SelectedFile>>),
/// Select multiple files, return a vector of triples
SelectFiles(IpcSender<FileManagerResult<Vec<SelectedFile>>>),
/// Read file, return the bytes
ReadFile(IpcSender<FileManagerResult<Vec<u8>>>, Uuid),
/// Delete the FileID entry
DeleteFileID(Uuid),
/// Shut down this thread
Exit,
}
pub type FileManagerResult<T> = Result<T, FileManagerThreadError>;
#[derive(Debug, Deserialize, Serialize)]
pub enum FileManagerThreadError {
/// The selection action is invalid, nothing is selected
InvalidSelection,
/// Failure to process file information such as file name, modified time etc.
FileInfoProcessingError,
/// Failure to read the file content
ReadFileError,
}
| SelectedFile | identifier_name |
regions-static-closure.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 | #![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(unboxed_closures)]
struct closure_box<'a> {
cl: Box<FnMut() + 'a>,
}
fn box_it<'a>(x: Box<FnMut() + 'a>) -> closure_box<'a> {
closure_box {cl: x}
}
fn call_static_closure(mut cl: closure_box<'static>) {
cl.cl.call_mut(())
}
pub fn main() {
let cl_box = box_it(box || println!("Hello, world!"));
call_static_closure(cl_box);
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
regions-static-closure.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.
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(unboxed_closures)]
struct closure_box<'a> {
cl: Box<FnMut() + 'a>,
}
fn box_it<'a>(x: Box<FnMut() + 'a>) -> closure_box<'a> {
closure_box {cl: x}
}
fn call_static_closure(mut cl: closure_box<'static>) {
cl.cl.call_mut(())
}
pub fn | () {
let cl_box = box_it(box || println!("Hello, world!"));
call_static_closure(cl_box);
}
| main | identifier_name |
app_result.rs | use std::io;
use std::error::FromError;
use std::fmt::{self, Display, Formatter};
use glob;
/// The result used in the whole application.
pub type AppResult<T> = Result<T, AppErr>;
/// The generic error used in the whole application.
pub struct AppErr
{
error: String
}
pub fn app_err(string: String) -> AppErr
{
AppErr::from_string(string)
}
impl AppErr
{
pub fn from_string(string: String) -> AppErr
{
AppErr { error: string }
}
}
| {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error>
{
writeln!(f, "{}", self.error)
}
}
impl FromError<io::Error> for AppErr
{
fn from_error(err: io::Error) -> AppErr
{
AppErr { error: format!("{}", err) }
}
}
impl FromError<glob::PatternError> for AppErr
{
fn from_error(err: glob::PatternError) -> AppErr
{
AppErr { error: format!("{}", err) }
}
} | impl Display for AppErr | random_line_split |
app_result.rs | use std::io;
use std::error::FromError;
use std::fmt::{self, Display, Formatter};
use glob;
/// The result used in the whole application.
pub type AppResult<T> = Result<T, AppErr>;
/// The generic error used in the whole application.
pub struct AppErr
{
error: String
}
pub fn app_err(string: String) -> AppErr
{
AppErr::from_string(string)
}
impl AppErr
{
pub fn from_string(string: String) -> AppErr
{
AppErr { error: string }
}
}
impl Display for AppErr
{
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error>
|
}
impl FromError<io::Error> for AppErr
{
fn from_error(err: io::Error) -> AppErr
{
AppErr { error: format!("{}", err) }
}
}
impl FromError<glob::PatternError> for AppErr
{
fn from_error(err: glob::PatternError) -> AppErr
{
AppErr { error: format!("{}", err) }
}
}
| {
writeln!(f, "{}", self.error)
} | identifier_body |
app_result.rs | use std::io;
use std::error::FromError;
use std::fmt::{self, Display, Formatter};
use glob;
/// The result used in the whole application.
pub type AppResult<T> = Result<T, AppErr>;
/// The generic error used in the whole application.
pub struct AppErr
{
error: String
}
pub fn app_err(string: String) -> AppErr
{
AppErr::from_string(string)
}
impl AppErr
{
pub fn | (string: String) -> AppErr
{
AppErr { error: string }
}
}
impl Display for AppErr
{
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error>
{
writeln!(f, "{}", self.error)
}
}
impl FromError<io::Error> for AppErr
{
fn from_error(err: io::Error) -> AppErr
{
AppErr { error: format!("{}", err) }
}
}
impl FromError<glob::PatternError> for AppErr
{
fn from_error(err: glob::PatternError) -> AppErr
{
AppErr { error: format!("{}", err) }
}
}
| from_string | identifier_name |
harfbuzz.rs | pub fn entry_for_glyph(&self, i: usize, y_pos: &mut Au) -> ShapedGlyphEntry {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
let pos_info_i = self.pos_infos.offset(i as isize);
let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset);
let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset);
let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance);
let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance);
let x_offset = Au::from_f64_px(x_offset);
let y_offset = Au::from_f64_px(y_offset);
let x_advance = Au::from_f64_px(x_advance);
let y_advance = Au::from_f64_px(y_advance);
let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) {
None
} else {
// adjust the pen..
if y_advance > Au(0) {
*y_pos = *y_pos - y_advance;
}
Some(Point2D::new(x_offset, *y_pos - y_offset))
};
ShapedGlyphEntry {
codepoint: (*glyph_info_i).codepoint as GlyphId,
advance: x_advance,
offset: offset,
}
}
}
}
#[derive(Debug)]
pub struct Shaper {
hb_face: *mut hb_face_t,
hb_font: *mut hb_font_t,
font: *const Font,
}
impl Drop for Shaper {
fn drop(&mut self) {
unsafe {
assert!(!self.hb_face.is_null());
hb_face_destroy(self.hb_face);
assert!(!self.hb_font.is_null());
hb_font_destroy(self.hb_font);
}
}
}
impl Shaper {
pub fn new(font: *const Font) -> Shaper {
unsafe {
let hb_face: *mut hb_face_t =
hb_face_create_for_tables(Some(font_table_func),
font as *const c_void as *mut c_void,
None);
let hb_font: *mut hb_font_t = hb_font_create(hb_face);
// Set points-per-em. if zero, performs no hinting in that direction.
let pt_size = (*font).actual_pt_size.to_f64_px();
hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint);
// Set scaling. Note that this takes 16.16 fixed point.
hb_font_set_scale(hb_font,
Shaper::float_to_fixed(pt_size) as c_int,
Shaper::float_to_fixed(pt_size) as c_int);
// configure static function callbacks.
hb_font_set_funcs(hb_font, HB_FONT_FUNCS.as_ptr(), font as *mut Font as *mut c_void, None);
Shaper {
hb_face: hb_face,
hb_font: hb_font,
font: font,
}
}
}
fn float_to_fixed(f: f64) -> i32 {
float_to_fixed(16, f)
}
fn fixed_to_float(i: hb_position_t) -> f64 {
fixed_to_float(16, i)
}
}
impl ShaperMethods for Shaper {
/// Calculate the layout metrics associated with the given text when painted in a specific
/// font.
fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
unsafe {
let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
hb_buffer_set_direction(hb_buffer, if options.flags.contains(RTL_FLAG) {
HB_DIRECTION_RTL
} else {
HB_DIRECTION_LTR
});
hb_buffer_set_script(hb_buffer, options.script.to_hb_script());
hb_buffer_add_utf8(hb_buffer,
text.as_ptr() as *const c_char,
text.len() as c_int,
0,
text.len() as c_int);
let mut features = Vec::new();
if options.flags.contains(IGNORE_LIGATURES_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: LIGA,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
if options.flags.contains(DISABLE_KERNING_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: KERN,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
hb_shape(self.hb_font, hb_buffer, features.as_mut_ptr(), features.len() as u32);
self.save_glyph_results(text, options, glyphs, hb_buffer);
hb_buffer_destroy(hb_buffer);
}
}
}
impl Shaper {
fn save_glyph_results(&self,
text: &str,
options: &ShapingOptions,
glyphs: &mut GlyphStore,
buffer: *mut hb_buffer_t) {
let glyph_data = ShapedGlyphData::new(buffer);
let glyph_count = glyph_data.len();
let byte_max = text.len();
debug!("Shaped text[byte count={}], got back {} glyph info records.",
byte_max,
glyph_count);
// make map of what chars have glyphs
let mut byte_to_glyph = vec![NO_GLYPH; byte_max];
debug!("(glyph idx) -> (text byte offset)");
for i in 0..glyph_data.len() {
let loc = glyph_data.byte_offset_of_glyph(i) as usize;
if loc < byte_max {
byte_to_glyph[loc] = i as i32;
} else {
debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}",
loc,
i);
}
debug!("{} -> {}", i, loc);
}
debug!("text: {:?}", text);
debug!("(char idx): char->(glyph index):");
for (i, ch) in text.char_indices() {
debug!("{}: {:?} --> {}", i, ch, byte_to_glyph[i]);
}
let mut glyph_span = 0..0;
let mut byte_range = 0..0;
let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character associations, 2+ glyphs and 1+ chars can be
// processed.
while glyph_span.start < glyph_count {
debug!("Processing glyph at idx={}", glyph_span.start);
glyph_span.end = glyph_span.start;
byte_range.end = glyph_data.byte_offset_of_glyph(glyph_span.start) as usize;
while byte_range.end < byte_max {
byte_range.end += 1;
// Extend the byte range to include any following byte without its own glyph.
while byte_range.end < byte_max && byte_to_glyph[byte_range.end] == NO_GLYPH {
byte_range.end += 1;
}
// Extend the glyph range to include all glyphs covered by bytes processed so far.
let mut max_glyph_idx = glyph_span.end;
for glyph_idx in &byte_to_glyph[byte_range.clone()] {
if *glyph_idx!= NO_GLYPH {
max_glyph_idx = cmp::max(*glyph_idx as usize + 1, max_glyph_idx);
}
}
if max_glyph_idx > glyph_span.end {
glyph_span.end = max_glyph_idx;
debug!("Extended glyph span to {:?}", glyph_span);
}
// if there's just one glyph, then we don't need further checks.
if glyph_span.len() == 1 { break; }
// if no glyphs were found yet, extend the char byte range more.
if glyph_span.len() == 0 { continue; }
// If byte_range now includes all the byte offsets found in glyph_span, then we
// have found a contiguous "cluster" and can stop extending it.
let mut all_glyphs_are_within_cluster: bool = true;
for j in glyph_span.clone() {
let loc = glyph_data.byte_offset_of_glyph(j);
if!byte_range.contains(loc as usize) {
all_glyphs_are_within_cluster = false;
break
}
}
if all_glyphs_are_within_cluster {
break
}
// Otherwise, the bytes we have seen so far correspond to a non-contiguous set of
// glyphs. Keep extending byte_range until we fill in all the holes in the glyph
// span or reach the end of the text.
}
assert!(byte_range.len() > 0);
assert!(glyph_span.len() > 0);
// Now byte_range is the ligature clump formed by the glyphs in glyph_span.
// We will save these glyphs to the glyph store at the index of the first byte.
let byte_idx = ByteIndex(byte_range.start as isize);
if glyph_span.len() == 1 {
// Fast path: 1-to-1 mapping of byte offset to single glyph.
//
// TODO(Issue #214): cluster ranges need to be computed before
// shaping, and then consulted here.
// for now, just pretend that every character is a cluster start.
// (i.e., pretend there are no combining character sequences).
// 1-to-1 mapping of character to glyph also treated as ligature start.
//
// NB: When we acquire the ability to handle ligatures that cross word boundaries,
// we'll need to do something special to handle `word-spacing` properly.
let character = text[byte_range.clone()].chars().next().unwrap();
if is_bidi_control(character) {
// Don't add any glyphs for bidi control chars
} else if character == '\t' {
// Treat tabs in pre-formatted text as a fixed number of spaces.
//
// TODO: Proper tab stops.
const TAB_COLS: i32 = 8;
let (space_glyph_id, space_advance) = glyph_space_advance(self.font);
let advance = Au::from_f64_px(space_advance) * TAB_COLS;
let data = GlyphData::new(space_glyph_id,
advance,
Default::default(),
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
} else {
let shape = glyph_data.entry_for_glyph(glyph_span.start, &mut y_pos);
let advance = self.advance_for_shaped_glyph(shape.advance, character, options);
let data = GlyphData::new(shape.codepoint,
advance,
shape.offset,
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
}
} else {
// collect all glyphs to be assigned to the first character.
let mut datas = vec!();
for glyph_i in glyph_span.clone() {
let shape = glyph_data.entry_for_glyph(glyph_i, &mut y_pos);
datas.push(GlyphData::new(shape.codepoint,
shape.advance,
shape.offset,
true, // treat as cluster start
glyph_i > glyph_span.start));
// all but first are ligature continuations
}
// now add the detailed glyph entry.
glyphs.add_glyphs_for_byte_index(byte_idx, &datas);
}
glyph_span.start = glyph_span.end;
byte_range.start = byte_range.end;
}
// this must be called after adding all glyph data; it sorts the
// lookup table for finding detailed glyphs by associated char index.
glyphs.finalize_changes();
}
fn advance_for_shaped_glyph(&self, mut advance: Au, character: char, options: &ShapingOptions)
-> Au {
if let Some(letter_spacing) = options.letter_spacing {
advance = advance + letter_spacing;
};
// CSS 2.1 § 16.4 states that "word spacing affects each space (U+0020) and non-breaking
// space (U+00A0) left in the text after the white space processing rules have been
// applied. The effect of the property on other word-separator characters is undefined."
// We elect to only space the two required code points.
if character =='' || character == '\u{a0}' {
// https://drafts.csswg.org/css-text-3/#word-spacing-property
let (length, percent) = options.word_spacing;
advance = (advance + length) + Au::new((advance.0 as f32 * percent.into_inner()) as i32);
}
advance
}
}
// Callbacks from Harfbuzz when font map and glyph advance lookup needed.
lazy_static! {
static ref HB_FONT_FUNCS: ptr::Unique<hb_font_funcs_t> = unsafe {
let hb_funcs = hb_font_funcs_create();
hb_font_funcs_set_glyph_func(hb_funcs, Some(glyph_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_advance_func(
hb_funcs, Some(glyph_h_advance_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_kerning_func(
hb_funcs, Some(glyph_h_kerning_func), ptr::null_mut(), None);
ptr::Unique::new(hb_funcs)
};
}
extern fn glyph_func(_: *mut hb_font_t,
font_data: *mut c_void,
unicode: hb_codepoint_t,
_: hb_codepoint_t,
glyph: *mut hb_codepoint_t,
_: *mut c_void)
-> hb_bool_t {
let font: *const Font = font_data as *const Font;
assert!(!font.is_null());
unsafe {
match (*font).glyph_index(char::from_u32(unicode).unwrap()) {
Some(g) => {
*glyph = g as hb_codepoint_t;
true as hb_bool_t
}
None => false as hb_bool_t
}
}
}
extern fn glyph_h_advance_func(_: *mut hb_font_t,
font_data: *mut c_void,
glyph: hb_codepoint_t,
_: *mut c_void)
-> hb_position_t {
let font: *mut Font = font_data as *mut Font;
assert!(!font.is_null());
unsafe {
let advance = (*font).glyph_h_advance(glyph as GlyphId);
Shaper::float_to_fixed(advance)
}
}
fn glyph_space_advance(font: *const Font) -> (hb_codepoint_t, f64) {
let space_unicode ='';
let space_glyph: hb_codepoint_t;
match unsafe { (*font).glyph_index(space_unicode) } {
Some(g) => {
space_glyph = g as hb_codepoint_t;
}
None => panic!("No space info")
}
let space_advance = unsafe { (*font).glyph_h_advance(space_glyph as GlyphId) };
(space_glyph, space_advance)
}
extern fn g | lyph_h_kerning_func( | identifier_name | |
harfbuzz.rs | _t,
}
pub struct ShapedGlyphEntry {
codepoint: GlyphId,
advance: Au,
offset: Option<Point2D<Au>>,
}
impl ShapedGlyphData {
pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData {
unsafe {
let mut glyph_count = 0;
let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mut glyph_count);
assert!(!glyph_infos.is_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
assert!(!pos_infos.is_null());
assert!(glyph_count == pos_count);
ShapedGlyphData {
count: glyph_count as usize,
glyph_infos: glyph_infos,
pos_infos: pos_infos,
}
}
}
#[inline(always)]
fn byte_offset_of_glyph(&self, i: usize) -> u32 {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
(*glyph_info_i).cluster
}
}
pub fn len(&self) -> usize {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn entry_for_glyph(&self, i: usize, y_pos: &mut Au) -> ShapedGlyphEntry {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
let pos_info_i = self.pos_infos.offset(i as isize);
let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset);
let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset);
let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance);
let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance);
let x_offset = Au::from_f64_px(x_offset);
let y_offset = Au::from_f64_px(y_offset);
let x_advance = Au::from_f64_px(x_advance);
let y_advance = Au::from_f64_px(y_advance);
let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) {
None
} else {
// adjust the pen..
if y_advance > Au(0) {
*y_pos = *y_pos - y_advance;
}
Some(Point2D::new(x_offset, *y_pos - y_offset))
};
ShapedGlyphEntry {
codepoint: (*glyph_info_i).codepoint as GlyphId,
advance: x_advance,
offset: offset,
}
}
}
}
#[derive(Debug)]
pub struct Shaper {
hb_face: *mut hb_face_t,
hb_font: *mut hb_font_t,
font: *const Font,
}
impl Drop for Shaper {
fn drop(&mut self) {
unsafe {
assert!(!self.hb_face.is_null());
hb_face_destroy(self.hb_face);
assert!(!self.hb_font.is_null());
hb_font_destroy(self.hb_font);
}
}
}
impl Shaper {
pub fn new(font: *const Font) -> Shaper {
unsafe {
let hb_face: *mut hb_face_t =
hb_face_create_for_tables(Some(font_table_func),
font as *const c_void as *mut c_void,
None);
let hb_font: *mut hb_font_t = hb_font_create(hb_face);
// Set points-per-em. if zero, performs no hinting in that direction.
let pt_size = (*font).actual_pt_size.to_f64_px();
hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint);
// Set scaling. Note that this takes 16.16 fixed point.
hb_font_set_scale(hb_font,
Shaper::float_to_fixed(pt_size) as c_int,
Shaper::float_to_fixed(pt_size) as c_int);
// configure static function callbacks.
hb_font_set_funcs(hb_font, HB_FONT_FUNCS.as_ptr(), font as *mut Font as *mut c_void, None);
Shaper {
hb_face: hb_face,
hb_font: hb_font,
font: font,
}
}
}
fn float_to_fixed(f: f64) -> i32 {
float_to_fixed(16, f)
}
fn fixed_to_float(i: hb_position_t) -> f64 {
fixed_to_float(16, i)
}
}
impl ShaperMethods for Shaper {
/// Calculate the layout metrics associated with the given text when painted in a specific
/// font.
fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
unsafe {
let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
hb_buffer_set_direction(hb_buffer, if options.flags.contains(RTL_FLAG) {
HB_DIRECTION_RTL
} else {
HB_DIRECTION_LTR
});
hb_buffer_set_script(hb_buffer, options.script.to_hb_script());
hb_buffer_add_utf8(hb_buffer,
text.as_ptr() as *const c_char,
text.len() as c_int,
0,
text.len() as c_int);
let mut features = Vec::new();
if options.flags.contains(IGNORE_LIGATURES_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: LIGA,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
if options.flags.contains(DISABLE_KERNING_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: KERN,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
hb_shape(self.hb_font, hb_buffer, features.as_mut_ptr(), features.len() as u32);
self.save_glyph_results(text, options, glyphs, hb_buffer);
hb_buffer_destroy(hb_buffer);
}
}
}
impl Shaper {
fn save_glyph_results(&self,
text: &str,
options: &ShapingOptions,
glyphs: &mut GlyphStore,
buffer: *mut hb_buffer_t) {
let glyph_data = ShapedGlyphData::new(buffer);
let glyph_count = glyph_data.len();
let byte_max = text.len();
debug!("Shaped text[byte count={}], got back {} glyph info records.",
byte_max,
glyph_count);
// make map of what chars have glyphs
let mut byte_to_glyph = vec![NO_GLYPH; byte_max];
debug!("(glyph idx) -> (text byte offset)");
for i in 0..glyph_data.len() {
let loc = glyph_data.byte_offset_of_glyph(i) as usize;
if loc < byte_max {
byte_to_glyph[loc] = i as i32;
} else {
debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}",
loc,
i);
}
debug!("{} -> {}", i, loc);
}
debug!("text: {:?}", text);
debug!("(char idx): char->(glyph index):");
for (i, ch) in text.char_indices() {
debug!("{}: {:?} --> {}", i, ch, byte_to_glyph[i]);
}
let mut glyph_span = 0..0;
let mut byte_range = 0..0;
let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character associations, 2+ glyphs and 1+ chars can be
// processed.
while glyph_span.start < glyph_count {
debug!("Processing glyph at idx={}", glyph_span.start);
glyph_span.end = glyph_span.start;
byte_range.end = glyph_data.byte_offset_of_glyph(glyph_span.start) as usize;
while byte_range.end < byte_max {
byte_range.end += 1;
// Extend the byte range to include any following byte without its own glyph.
while byte_range.end < byte_max && byte_to_glyph[byte_range.end] == NO_GLYPH {
byte_range.end += 1;
}
// Extend the glyph range to include all glyphs covered by bytes processed so far.
let mut max_glyph_idx = glyph_span.end;
for glyph_idx in &byte_to_glyph[byte_range.clone()] {
if *glyph_idx!= NO_GLYPH {
max_glyph_idx = cmp::max(*glyph_idx as usize + 1, max_glyph_idx);
}
}
if max_glyph_idx > glyph_span.end {
glyph_span.end = max_glyph_idx;
debug!("Extended glyph span to {:?}", glyph_span);
}
// if there's just one glyph, then we don't need further checks.
if glyph_span.len() == 1 { break; }
// if no glyphs were found yet, extend the char byte range more.
if glyph_span.len() == 0 { continue; }
// If byte_range now includes all the byte offsets found in glyph_span, then we
// have found a contiguous "cluster" and can stop extending it.
let mut all_glyphs_are_within_cluster: bool = true;
for j in glyph_span.clone() {
let loc = glyph_data.byte_offset_of_glyph(j);
if!byte_range.contains(loc as usize) {
all_glyphs_are_within_cluster = false;
break
}
}
if all_glyphs_are_within_cluster |
// Otherwise, the bytes we have seen so far correspond to a non-contiguous set of
// glyphs. Keep extending byte_range until we fill in all the holes in the glyph
// span or reach the end of the text.
}
assert!(byte_range.len() > 0);
assert!(glyph_span.len() > 0);
// Now byte_range is the ligature clump formed by the glyphs in glyph_span.
// We will save these glyphs to the glyph store at the index of the first byte.
let byte_idx = ByteIndex(byte_range.start as isize);
if glyph_span.len() == 1 {
// Fast path: 1-to-1 mapping of byte offset to single glyph.
//
// TODO(Issue #214): cluster ranges need to be computed before
// shaping, and then consulted here.
// for now, just pretend that every character is a cluster start.
// (i.e., pretend there are no combining character sequences).
// 1-to-1 mapping of character to glyph also treated as ligature start.
//
// NB: When we acquire the ability to handle ligatures that cross word boundaries,
// we'll need to do something special to handle `word-spacing` properly.
let character = text[byte_range.clone()].chars().next().unwrap();
if is_bidi_control(character) {
// Don't add any glyphs for bidi control chars
} else if character == '\t' {
// Treat tabs in pre-formatted text as a fixed number of spaces.
//
// TODO: Proper tab stops.
const TAB_COLS: i32 = 8;
let (space_glyph_id, space_advance) = glyph_space_advance(self.font);
let advance = Au::from_f64_px(space_advance) * TAB_COLS;
let data = GlyphData::new(space_glyph_id,
advance,
Default::default(),
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
} else {
let shape = glyph_data.entry_for_glyph(glyph_span.start, &mut y_pos);
let advance = self.advance_for_shaped_glyph(shape.advance, character, options);
let data = GlyphData::new(shape.codepoint,
advance,
shape.offset,
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
}
} else {
// collect all glyphs to be assigned to the first character.
let mut datas = vec!();
for glyph_i in glyph_span.clone() {
let shape = glyph_data.entry_for_glyph(glyph_i, &mut y_pos);
datas.push(GlyphData::new(shape.codepoint,
shape.advance,
shape.offset,
true, // treat as cluster start
glyph_i > glyph_span.start));
// all but first are ligature continuations
}
// now add the detailed glyph entry.
glyphs.add_glyphs_for_byte_index(byte_idx, &datas);
}
glyph_span.start = glyph_span.end;
byte_range.start = byte_range.end;
}
// this must be called after adding all glyph data; it sorts the
// lookup table for finding detailed glyphs by associated char index.
glyphs.finalize_changes();
}
fn advance_for_shaped_glyph(&self, mut advance: Au, character: char, options: &ShapingOptions)
-> Au {
if let Some(letter_spacing) = options.letter_spacing {
advance = advance + letter_spacing;
};
// CSS 2.1 § 16.4 states that "word spacing affects each space (U+0020) and non-breaking
// space (U+00A0) left in the text after the white space processing rules have been
// applied. The effect of the property on other word-separator characters is undefined."
// We elect to only space the two required code points.
if character =='' || character == '\u{a0}' {
// https://drafts.csswg.org/css-text-3/#word-spacing-property
let (length, percent) = options.word_spacing;
advance = (advance + length) + Au::new((advance.0 as f32 * percent.into_inner()) as i32);
}
advance
}
}
// Callbacks from Harfbuzz when font map and glyph advance lookup needed.
lazy_static! {
static ref HB_FONT_FUNCS: ptr::Unique<hb_font_funcs_t> = unsafe {
let hb_funcs = hb_font_funcs_create();
hb_font_funcs_set_glyph_func(hb_funcs, Some(glyph_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_advance_func(
hb_funcs, Some(glyph_h_advance_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_kerning_func(
hb_funcs, Some(glyph_h_kerning_func), ptr::null_mut(), None);
ptr::Unique::new(hb_funcs)
};
}
extern fn glyph_func(_: *mut hb_font_t,
font_data: *mut c_void,
unicode: hb_codepoint_t,
_: hb_codepoint_t,
glyph: *mut hb_codepoint_t,
_: *mut c_void)
-> hb_bool_t {
let font: *const Font = font_data as *const Font;
assert!(!font.is_null());
unsafe {
match (*font).glyph_index(char::from_u32(unicode).unwrap()) {
| {
break
} | conditional_block |
harfbuzz.rs | _position_t,
}
pub struct ShapedGlyphEntry {
codepoint: GlyphId,
advance: Au,
offset: Option<Point2D<Au>>,
}
impl ShapedGlyphData {
pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData {
unsafe {
let mut glyph_count = 0;
let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mut glyph_count);
assert!(!glyph_infos.is_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
assert!(!pos_infos.is_null());
assert!(glyph_count == pos_count);
ShapedGlyphData {
count: glyph_count as usize,
glyph_infos: glyph_infos,
pos_infos: pos_infos,
}
}
}
#[inline(always)]
fn byte_offset_of_glyph(&self, i: usize) -> u32 {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
(*glyph_info_i).cluster
}
}
pub fn len(&self) -> usize {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn entry_for_glyph(&self, i: usize, y_pos: &mut Au) -> ShapedGlyphEntry {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
let pos_info_i = self.pos_infos.offset(i as isize);
let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset);
let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset);
let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance);
let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance);
let x_offset = Au::from_f64_px(x_offset);
let y_offset = Au::from_f64_px(y_offset);
let x_advance = Au::from_f64_px(x_advance);
let y_advance = Au::from_f64_px(y_advance);
let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) {
None
} else {
// adjust the pen..
if y_advance > Au(0) {
*y_pos = *y_pos - y_advance;
}
Some(Point2D::new(x_offset, *y_pos - y_offset))
};
ShapedGlyphEntry {
codepoint: (*glyph_info_i).codepoint as GlyphId,
advance: x_advance,
offset: offset,
}
}
}
}
#[derive(Debug)]
pub struct Shaper {
hb_face: *mut hb_face_t,
hb_font: *mut hb_font_t,
font: *const Font,
}
impl Drop for Shaper {
fn drop(&mut self) {
unsafe {
assert!(!self.hb_face.is_null());
hb_face_destroy(self.hb_face);
assert!(!self.hb_font.is_null());
hb_font_destroy(self.hb_font);
}
}
}
impl Shaper {
pub fn new(font: *const Font) -> Shaper {
unsafe {
let hb_face: *mut hb_face_t =
hb_face_create_for_tables(Some(font_table_func),
font as *const c_void as *mut c_void,
None);
let hb_font: *mut hb_font_t = hb_font_create(hb_face);
// Set points-per-em. if zero, performs no hinting in that direction.
let pt_size = (*font).actual_pt_size.to_f64_px();
hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint);
// Set scaling. Note that this takes 16.16 fixed point.
hb_font_set_scale(hb_font,
Shaper::float_to_fixed(pt_size) as c_int,
Shaper::float_to_fixed(pt_size) as c_int);
// configure static function callbacks.
hb_font_set_funcs(hb_font, HB_FONT_FUNCS.as_ptr(), font as *mut Font as *mut c_void, None);
Shaper {
hb_face: hb_face,
hb_font: hb_font,
font: font,
}
}
}
fn float_to_fixed(f: f64) -> i32 {
float_to_fixed(16, f)
}
| fixed_to_float(16, i)
}
}
impl ShaperMethods for Shaper {
/// Calculate the layout metrics associated with the given text when painted in a specific
/// font.
fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
unsafe {
let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
hb_buffer_set_direction(hb_buffer, if options.flags.contains(RTL_FLAG) {
HB_DIRECTION_RTL
} else {
HB_DIRECTION_LTR
});
hb_buffer_set_script(hb_buffer, options.script.to_hb_script());
hb_buffer_add_utf8(hb_buffer,
text.as_ptr() as *const c_char,
text.len() as c_int,
0,
text.len() as c_int);
let mut features = Vec::new();
if options.flags.contains(IGNORE_LIGATURES_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: LIGA,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
if options.flags.contains(DISABLE_KERNING_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: KERN,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
hb_shape(self.hb_font, hb_buffer, features.as_mut_ptr(), features.len() as u32);
self.save_glyph_results(text, options, glyphs, hb_buffer);
hb_buffer_destroy(hb_buffer);
}
}
}
impl Shaper {
fn save_glyph_results(&self,
text: &str,
options: &ShapingOptions,
glyphs: &mut GlyphStore,
buffer: *mut hb_buffer_t) {
let glyph_data = ShapedGlyphData::new(buffer);
let glyph_count = glyph_data.len();
let byte_max = text.len();
debug!("Shaped text[byte count={}], got back {} glyph info records.",
byte_max,
glyph_count);
// make map of what chars have glyphs
let mut byte_to_glyph = vec![NO_GLYPH; byte_max];
debug!("(glyph idx) -> (text byte offset)");
for i in 0..glyph_data.len() {
let loc = glyph_data.byte_offset_of_glyph(i) as usize;
if loc < byte_max {
byte_to_glyph[loc] = i as i32;
} else {
debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}",
loc,
i);
}
debug!("{} -> {}", i, loc);
}
debug!("text: {:?}", text);
debug!("(char idx): char->(glyph index):");
for (i, ch) in text.char_indices() {
debug!("{}: {:?} --> {}", i, ch, byte_to_glyph[i]);
}
let mut glyph_span = 0..0;
let mut byte_range = 0..0;
let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character associations, 2+ glyphs and 1+ chars can be
// processed.
while glyph_span.start < glyph_count {
debug!("Processing glyph at idx={}", glyph_span.start);
glyph_span.end = glyph_span.start;
byte_range.end = glyph_data.byte_offset_of_glyph(glyph_span.start) as usize;
while byte_range.end < byte_max {
byte_range.end += 1;
// Extend the byte range to include any following byte without its own glyph.
while byte_range.end < byte_max && byte_to_glyph[byte_range.end] == NO_GLYPH {
byte_range.end += 1;
}
// Extend the glyph range to include all glyphs covered by bytes processed so far.
let mut max_glyph_idx = glyph_span.end;
for glyph_idx in &byte_to_glyph[byte_range.clone()] {
if *glyph_idx!= NO_GLYPH {
max_glyph_idx = cmp::max(*glyph_idx as usize + 1, max_glyph_idx);
}
}
if max_glyph_idx > glyph_span.end {
glyph_span.end = max_glyph_idx;
debug!("Extended glyph span to {:?}", glyph_span);
}
// if there's just one glyph, then we don't need further checks.
if glyph_span.len() == 1 { break; }
// if no glyphs were found yet, extend the char byte range more.
if glyph_span.len() == 0 { continue; }
// If byte_range now includes all the byte offsets found in glyph_span, then we
// have found a contiguous "cluster" and can stop extending it.
let mut all_glyphs_are_within_cluster: bool = true;
for j in glyph_span.clone() {
let loc = glyph_data.byte_offset_of_glyph(j);
if!byte_range.contains(loc as usize) {
all_glyphs_are_within_cluster = false;
break
}
}
if all_glyphs_are_within_cluster {
break
}
// Otherwise, the bytes we have seen so far correspond to a non-contiguous set of
// glyphs. Keep extending byte_range until we fill in all the holes in the glyph
// span or reach the end of the text.
}
assert!(byte_range.len() > 0);
assert!(glyph_span.len() > 0);
// Now byte_range is the ligature clump formed by the glyphs in glyph_span.
// We will save these glyphs to the glyph store at the index of the first byte.
let byte_idx = ByteIndex(byte_range.start as isize);
if glyph_span.len() == 1 {
// Fast path: 1-to-1 mapping of byte offset to single glyph.
//
// TODO(Issue #214): cluster ranges need to be computed before
// shaping, and then consulted here.
// for now, just pretend that every character is a cluster start.
// (i.e., pretend there are no combining character sequences).
// 1-to-1 mapping of character to glyph also treated as ligature start.
//
// NB: When we acquire the ability to handle ligatures that cross word boundaries,
// we'll need to do something special to handle `word-spacing` properly.
let character = text[byte_range.clone()].chars().next().unwrap();
if is_bidi_control(character) {
// Don't add any glyphs for bidi control chars
} else if character == '\t' {
// Treat tabs in pre-formatted text as a fixed number of spaces.
//
// TODO: Proper tab stops.
const TAB_COLS: i32 = 8;
let (space_glyph_id, space_advance) = glyph_space_advance(self.font);
let advance = Au::from_f64_px(space_advance) * TAB_COLS;
let data = GlyphData::new(space_glyph_id,
advance,
Default::default(),
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
} else {
let shape = glyph_data.entry_for_glyph(glyph_span.start, &mut y_pos);
let advance = self.advance_for_shaped_glyph(shape.advance, character, options);
let data = GlyphData::new(shape.codepoint,
advance,
shape.offset,
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
}
} else {
// collect all glyphs to be assigned to the first character.
let mut datas = vec!();
for glyph_i in glyph_span.clone() {
let shape = glyph_data.entry_for_glyph(glyph_i, &mut y_pos);
datas.push(GlyphData::new(shape.codepoint,
shape.advance,
shape.offset,
true, // treat as cluster start
glyph_i > glyph_span.start));
// all but first are ligature continuations
}
// now add the detailed glyph entry.
glyphs.add_glyphs_for_byte_index(byte_idx, &datas);
}
glyph_span.start = glyph_span.end;
byte_range.start = byte_range.end;
}
// this must be called after adding all glyph data; it sorts the
// lookup table for finding detailed glyphs by associated char index.
glyphs.finalize_changes();
}
fn advance_for_shaped_glyph(&self, mut advance: Au, character: char, options: &ShapingOptions)
-> Au {
if let Some(letter_spacing) = options.letter_spacing {
advance = advance + letter_spacing;
};
// CSS 2.1 § 16.4 states that "word spacing affects each space (U+0020) and non-breaking
// space (U+00A0) left in the text after the white space processing rules have been
// applied. The effect of the property on other word-separator characters is undefined."
// We elect to only space the two required code points.
if character =='' || character == '\u{a0}' {
// https://drafts.csswg.org/css-text-3/#word-spacing-property
let (length, percent) = options.word_spacing;
advance = (advance + length) + Au::new((advance.0 as f32 * percent.into_inner()) as i32);
}
advance
}
}
// Callbacks from Harfbuzz when font map and glyph advance lookup needed.
lazy_static! {
static ref HB_FONT_FUNCS: ptr::Unique<hb_font_funcs_t> = unsafe {
let hb_funcs = hb_font_funcs_create();
hb_font_funcs_set_glyph_func(hb_funcs, Some(glyph_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_advance_func(
hb_funcs, Some(glyph_h_advance_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_kerning_func(
hb_funcs, Some(glyph_h_kerning_func), ptr::null_mut(), None);
ptr::Unique::new(hb_funcs)
};
}
extern fn glyph_func(_: *mut hb_font_t,
font_data: *mut c_void,
unicode: hb_codepoint_t,
_: hb_codepoint_t,
glyph: *mut hb_codepoint_t,
_: *mut c_void)
-> hb_bool_t {
let font: *const Font = font_data as *const Font;
assert!(!font.is_null());
unsafe {
match (*font).glyph_index(char::from_u32(unicode).unwrap()) {
| fn fixed_to_float(i: hb_position_t) -> f64 { | random_line_split |
harfbuzz.rs | _t,
}
pub struct ShapedGlyphEntry {
codepoint: GlyphId,
advance: Au,
offset: Option<Point2D<Au>>,
}
impl ShapedGlyphData {
pub fn new(buffer: *mut hb_buffer_t) -> ShapedGlyphData {
unsafe {
let mut glyph_count = 0;
let glyph_infos = hb_buffer_get_glyph_infos(buffer, &mut glyph_count);
assert!(!glyph_infos.is_null());
let mut pos_count = 0;
let pos_infos = hb_buffer_get_glyph_positions(buffer, &mut pos_count);
assert!(!pos_infos.is_null());
assert!(glyph_count == pos_count);
ShapedGlyphData {
count: glyph_count as usize,
glyph_infos: glyph_infos,
pos_infos: pos_infos,
}
}
}
#[inline(always)]
fn byte_offset_of_glyph(&self, i: usize) -> u32 {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
(*glyph_info_i).cluster
}
}
pub fn len(&self) -> usize {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn entry_for_glyph(&self, i: usize, y_pos: &mut Au) -> ShapedGlyphEntry {
assert!(i < self.count);
unsafe {
let glyph_info_i = self.glyph_infos.offset(i as isize);
let pos_info_i = self.pos_infos.offset(i as isize);
let x_offset = Shaper::fixed_to_float((*pos_info_i).x_offset);
let y_offset = Shaper::fixed_to_float((*pos_info_i).y_offset);
let x_advance = Shaper::fixed_to_float((*pos_info_i).x_advance);
let y_advance = Shaper::fixed_to_float((*pos_info_i).y_advance);
let x_offset = Au::from_f64_px(x_offset);
let y_offset = Au::from_f64_px(y_offset);
let x_advance = Au::from_f64_px(x_advance);
let y_advance = Au::from_f64_px(y_advance);
let offset = if x_offset == Au(0) && y_offset == Au(0) && y_advance == Au(0) {
None
} else {
// adjust the pen..
if y_advance > Au(0) {
*y_pos = *y_pos - y_advance;
}
Some(Point2D::new(x_offset, *y_pos - y_offset))
};
ShapedGlyphEntry {
codepoint: (*glyph_info_i).codepoint as GlyphId,
advance: x_advance,
offset: offset,
}
}
}
}
#[derive(Debug)]
pub struct Shaper {
hb_face: *mut hb_face_t,
hb_font: *mut hb_font_t,
font: *const Font,
}
impl Drop for Shaper {
fn drop(&mut self) {
unsafe {
assert!(!self.hb_face.is_null());
hb_face_destroy(self.hb_face);
assert!(!self.hb_font.is_null());
hb_font_destroy(self.hb_font);
}
}
}
impl Shaper {
pub fn new(font: *const Font) -> Shaper {
unsafe {
let hb_face: *mut hb_face_t =
hb_face_create_for_tables(Some(font_table_func),
font as *const c_void as *mut c_void,
None);
let hb_font: *mut hb_font_t = hb_font_create(hb_face);
// Set points-per-em. if zero, performs no hinting in that direction.
let pt_size = (*font).actual_pt_size.to_f64_px();
hb_font_set_ppem(hb_font, pt_size as c_uint, pt_size as c_uint);
// Set scaling. Note that this takes 16.16 fixed point.
hb_font_set_scale(hb_font,
Shaper::float_to_fixed(pt_size) as c_int,
Shaper::float_to_fixed(pt_size) as c_int);
// configure static function callbacks.
hb_font_set_funcs(hb_font, HB_FONT_FUNCS.as_ptr(), font as *mut Font as *mut c_void, None);
Shaper {
hb_face: hb_face,
hb_font: hb_font,
font: font,
}
}
}
fn float_to_fixed(f: f64) -> i32 |
fn fixed_to_float(i: hb_position_t) -> f64 {
fixed_to_float(16, i)
}
}
impl ShaperMethods for Shaper {
/// Calculate the layout metrics associated with the given text when painted in a specific
/// font.
fn shape_text(&self, text: &str, options: &ShapingOptions, glyphs: &mut GlyphStore) {
unsafe {
let hb_buffer: *mut hb_buffer_t = hb_buffer_create();
hb_buffer_set_direction(hb_buffer, if options.flags.contains(RTL_FLAG) {
HB_DIRECTION_RTL
} else {
HB_DIRECTION_LTR
});
hb_buffer_set_script(hb_buffer, options.script.to_hb_script());
hb_buffer_add_utf8(hb_buffer,
text.as_ptr() as *const c_char,
text.len() as c_int,
0,
text.len() as c_int);
let mut features = Vec::new();
if options.flags.contains(IGNORE_LIGATURES_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: LIGA,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
if options.flags.contains(DISABLE_KERNING_SHAPING_FLAG) {
features.push(hb_feature_t {
tag: KERN,
value: 0,
start: 0,
end: hb_buffer_get_length(hb_buffer),
})
}
hb_shape(self.hb_font, hb_buffer, features.as_mut_ptr(), features.len() as u32);
self.save_glyph_results(text, options, glyphs, hb_buffer);
hb_buffer_destroy(hb_buffer);
}
}
}
impl Shaper {
fn save_glyph_results(&self,
text: &str,
options: &ShapingOptions,
glyphs: &mut GlyphStore,
buffer: *mut hb_buffer_t) {
let glyph_data = ShapedGlyphData::new(buffer);
let glyph_count = glyph_data.len();
let byte_max = text.len();
debug!("Shaped text[byte count={}], got back {} glyph info records.",
byte_max,
glyph_count);
// make map of what chars have glyphs
let mut byte_to_glyph = vec![NO_GLYPH; byte_max];
debug!("(glyph idx) -> (text byte offset)");
for i in 0..glyph_data.len() {
let loc = glyph_data.byte_offset_of_glyph(i) as usize;
if loc < byte_max {
byte_to_glyph[loc] = i as i32;
} else {
debug!("ERROR: tried to set out of range byte_to_glyph: idx={}, glyph idx={}",
loc,
i);
}
debug!("{} -> {}", i, loc);
}
debug!("text: {:?}", text);
debug!("(char idx): char->(glyph index):");
for (i, ch) in text.char_indices() {
debug!("{}: {:?} --> {}", i, ch, byte_to_glyph[i]);
}
let mut glyph_span = 0..0;
let mut byte_range = 0..0;
let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character associations, 2+ glyphs and 1+ chars can be
// processed.
while glyph_span.start < glyph_count {
debug!("Processing glyph at idx={}", glyph_span.start);
glyph_span.end = glyph_span.start;
byte_range.end = glyph_data.byte_offset_of_glyph(glyph_span.start) as usize;
while byte_range.end < byte_max {
byte_range.end += 1;
// Extend the byte range to include any following byte without its own glyph.
while byte_range.end < byte_max && byte_to_glyph[byte_range.end] == NO_GLYPH {
byte_range.end += 1;
}
// Extend the glyph range to include all glyphs covered by bytes processed so far.
let mut max_glyph_idx = glyph_span.end;
for glyph_idx in &byte_to_glyph[byte_range.clone()] {
if *glyph_idx!= NO_GLYPH {
max_glyph_idx = cmp::max(*glyph_idx as usize + 1, max_glyph_idx);
}
}
if max_glyph_idx > glyph_span.end {
glyph_span.end = max_glyph_idx;
debug!("Extended glyph span to {:?}", glyph_span);
}
// if there's just one glyph, then we don't need further checks.
if glyph_span.len() == 1 { break; }
// if no glyphs were found yet, extend the char byte range more.
if glyph_span.len() == 0 { continue; }
// If byte_range now includes all the byte offsets found in glyph_span, then we
// have found a contiguous "cluster" and can stop extending it.
let mut all_glyphs_are_within_cluster: bool = true;
for j in glyph_span.clone() {
let loc = glyph_data.byte_offset_of_glyph(j);
if!byte_range.contains(loc as usize) {
all_glyphs_are_within_cluster = false;
break
}
}
if all_glyphs_are_within_cluster {
break
}
// Otherwise, the bytes we have seen so far correspond to a non-contiguous set of
// glyphs. Keep extending byte_range until we fill in all the holes in the glyph
// span or reach the end of the text.
}
assert!(byte_range.len() > 0);
assert!(glyph_span.len() > 0);
// Now byte_range is the ligature clump formed by the glyphs in glyph_span.
// We will save these glyphs to the glyph store at the index of the first byte.
let byte_idx = ByteIndex(byte_range.start as isize);
if glyph_span.len() == 1 {
// Fast path: 1-to-1 mapping of byte offset to single glyph.
//
// TODO(Issue #214): cluster ranges need to be computed before
// shaping, and then consulted here.
// for now, just pretend that every character is a cluster start.
// (i.e., pretend there are no combining character sequences).
// 1-to-1 mapping of character to glyph also treated as ligature start.
//
// NB: When we acquire the ability to handle ligatures that cross word boundaries,
// we'll need to do something special to handle `word-spacing` properly.
let character = text[byte_range.clone()].chars().next().unwrap();
if is_bidi_control(character) {
// Don't add any glyphs for bidi control chars
} else if character == '\t' {
// Treat tabs in pre-formatted text as a fixed number of spaces.
//
// TODO: Proper tab stops.
const TAB_COLS: i32 = 8;
let (space_glyph_id, space_advance) = glyph_space_advance(self.font);
let advance = Au::from_f64_px(space_advance) * TAB_COLS;
let data = GlyphData::new(space_glyph_id,
advance,
Default::default(),
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
} else {
let shape = glyph_data.entry_for_glyph(glyph_span.start, &mut y_pos);
let advance = self.advance_for_shaped_glyph(shape.advance, character, options);
let data = GlyphData::new(shape.codepoint,
advance,
shape.offset,
true,
true);
glyphs.add_glyph_for_byte_index(byte_idx, character, &data);
}
} else {
// collect all glyphs to be assigned to the first character.
let mut datas = vec!();
for glyph_i in glyph_span.clone() {
let shape = glyph_data.entry_for_glyph(glyph_i, &mut y_pos);
datas.push(GlyphData::new(shape.codepoint,
shape.advance,
shape.offset,
true, // treat as cluster start
glyph_i > glyph_span.start));
// all but first are ligature continuations
}
// now add the detailed glyph entry.
glyphs.add_glyphs_for_byte_index(byte_idx, &datas);
}
glyph_span.start = glyph_span.end;
byte_range.start = byte_range.end;
}
// this must be called after adding all glyph data; it sorts the
// lookup table for finding detailed glyphs by associated char index.
glyphs.finalize_changes();
}
fn advance_for_shaped_glyph(&self, mut advance: Au, character: char, options: &ShapingOptions)
-> Au {
if let Some(letter_spacing) = options.letter_spacing {
advance = advance + letter_spacing;
};
// CSS 2.1 § 16.4 states that "word spacing affects each space (U+0020) and non-breaking
// space (U+00A0) left in the text after the white space processing rules have been
// applied. The effect of the property on other word-separator characters is undefined."
// We elect to only space the two required code points.
if character =='' || character == '\u{a0}' {
// https://drafts.csswg.org/css-text-3/#word-spacing-property
let (length, percent) = options.word_spacing;
advance = (advance + length) + Au::new((advance.0 as f32 * percent.into_inner()) as i32);
}
advance
}
}
// Callbacks from Harfbuzz when font map and glyph advance lookup needed.
lazy_static! {
static ref HB_FONT_FUNCS: ptr::Unique<hb_font_funcs_t> = unsafe {
let hb_funcs = hb_font_funcs_create();
hb_font_funcs_set_glyph_func(hb_funcs, Some(glyph_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_advance_func(
hb_funcs, Some(glyph_h_advance_func), ptr::null_mut(), None);
hb_font_funcs_set_glyph_h_kerning_func(
hb_funcs, Some(glyph_h_kerning_func), ptr::null_mut(), None);
ptr::Unique::new(hb_funcs)
};
}
extern fn glyph_func(_: *mut hb_font_t,
font_data: *mut c_void,
unicode: hb_codepoint_t,
_: hb_codepoint_t,
glyph: *mut hb_codepoint_t,
_: *mut c_void)
-> hb_bool_t {
let font: *const Font = font_data as *const Font;
assert!(!font.is_null());
unsafe {
match (*font).glyph_index(char::from_u32(unicode).unwrap()) {
| {
float_to_fixed(16, f)
} | identifier_body |
thread.rs | use core::time::Duration;
use crate::syscall;
use alloc::string::String;
pub struct Thread {
name: Option<String>,
stack_size: usize,
stack_top: * const u8,
id: ThreadId,
}
pub struct Builder {
name: Option<String>,
stack_size: usize,
}
impl Builder {
const DEFAULT_SIZE: usize = 0x400000usize;
pub fn new() -> Self {
Self {
name: None,
stack_size: Self::DEFAULT_SIZE,
}
}
pub fn name(self, name: String) -> Self |
pub fn stack_size(self, stack_size: usize) -> Self {
Self {
name: self.name,
stack_size
}
}
}
#[derive(Clone)]
pub struct ThreadId(u16);
impl Thread {
pub fn unpark(&self) { }
pub fn id(&self) -> ThreadId { self.id.clone() }
pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) }
/*
fn new(name: Option<String>, stack_size: usize) -> Thread {
let (stack_memory, stack_size) = mapping::allocate_stack_memory(stack_size);
Thread {
name,
stack_size,
id: ThreadId(syscall::c_types::NULL_TID),
stack_top: stack_memory + stack_size,
}
}
*/
/*
pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>, error::Error>
where F: FnOnce() -> T + Send +'static, T: Send +'static {
unsafe {
syscall::sys_create_thread(syscall::c_types::NULL_TID,
&f as * const F as * const c_void,
core::ptr::null() as * const PAddr,
self.stack_top as * const c_void);
}
}
*/
}
pub fn sleep(dur: Duration) {
let millis = dur.as_millis().clamp(0, 0xffffffff) as u32;
match syscall::sleep(millis) {
Err(code) => eprintln!("syscall::sleep() failed with code: {}", code),
_ => (),
};
}
pub fn yield_now() {
match syscall::sleep(0) {
Err(code) => eprintln!("syscall::sleep() failed with code: {}", code),
_ => ()
};
} | {
Self {
name: Some(name),
stack_size: self.stack_size
}
} | identifier_body |
thread.rs | use core::time::Duration;
use crate::syscall;
use alloc::string::String;
pub struct Thread {
name: Option<String>,
stack_size: usize,
stack_top: * const u8,
id: ThreadId,
}
pub struct Builder {
name: Option<String>,
stack_size: usize,
}
impl Builder {
const DEFAULT_SIZE: usize = 0x400000usize;
pub fn new() -> Self {
Self {
name: None,
stack_size: Self::DEFAULT_SIZE,
}
}
pub fn name(self, name: String) -> Self {
Self {
name: Some(name),
stack_size: self.stack_size
}
}
pub fn stack_size(self, stack_size: usize) -> Self {
Self {
name: self.name,
stack_size
}
}
}
#[derive(Clone)]
| impl Thread {
pub fn unpark(&self) { }
pub fn id(&self) -> ThreadId { self.id.clone() }
pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) }
/*
fn new(name: Option<String>, stack_size: usize) -> Thread {
let (stack_memory, stack_size) = mapping::allocate_stack_memory(stack_size);
Thread {
name,
stack_size,
id: ThreadId(syscall::c_types::NULL_TID),
stack_top: stack_memory + stack_size,
}
}
*/
/*
pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>, error::Error>
where F: FnOnce() -> T + Send +'static, T: Send +'static {
unsafe {
syscall::sys_create_thread(syscall::c_types::NULL_TID,
&f as * const F as * const c_void,
core::ptr::null() as * const PAddr,
self.stack_top as * const c_void);
}
}
*/
}
pub fn sleep(dur: Duration) {
let millis = dur.as_millis().clamp(0, 0xffffffff) as u32;
match syscall::sleep(millis) {
Err(code) => eprintln!("syscall::sleep() failed with code: {}", code),
_ => (),
};
}
pub fn yield_now() {
match syscall::sleep(0) {
Err(code) => eprintln!("syscall::sleep() failed with code: {}", code),
_ => ()
};
} | pub struct ThreadId(u16);
| random_line_split |
thread.rs | use core::time::Duration;
use crate::syscall;
use alloc::string::String;
pub struct Thread {
name: Option<String>,
stack_size: usize,
stack_top: * const u8,
id: ThreadId,
}
pub struct Builder {
name: Option<String>,
stack_size: usize,
}
impl Builder {
const DEFAULT_SIZE: usize = 0x400000usize;
pub fn new() -> Self {
Self {
name: None,
stack_size: Self::DEFAULT_SIZE,
}
}
pub fn name(self, name: String) -> Self {
Self {
name: Some(name),
stack_size: self.stack_size
}
}
pub fn stack_size(self, stack_size: usize) -> Self {
Self {
name: self.name,
stack_size
}
}
}
#[derive(Clone)]
pub struct ThreadId(u16);
impl Thread {
pub fn | (&self) { }
pub fn id(&self) -> ThreadId { self.id.clone() }
pub fn name(&self) -> Option<&str> { self.name.as_ref().map(|s| s.as_str()) }
/*
fn new(name: Option<String>, stack_size: usize) -> Thread {
let (stack_memory, stack_size) = mapping::allocate_stack_memory(stack_size);
Thread {
name,
stack_size,
id: ThreadId(syscall::c_types::NULL_TID),
stack_top: stack_memory + stack_size,
}
}
*/
/*
pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>, error::Error>
where F: FnOnce() -> T + Send +'static, T: Send +'static {
unsafe {
syscall::sys_create_thread(syscall::c_types::NULL_TID,
&f as * const F as * const c_void,
core::ptr::null() as * const PAddr,
self.stack_top as * const c_void);
}
}
*/
}
pub fn sleep(dur: Duration) {
let millis = dur.as_millis().clamp(0, 0xffffffff) as u32;
match syscall::sleep(millis) {
Err(code) => eprintln!("syscall::sleep() failed with code: {}", code),
_ => (),
};
}
pub fn yield_now() {
match syscall::sleep(0) {
Err(code) => eprintln!("syscall::sleep() failed with code: {}", code),
_ => ()
};
} | unpark | identifier_name |
sprite_renderer.rs | /*
use cgmath::Vector2;
use gfx;
use gfx_device_gl;
use gfx_device_gl::{Resources};
use gfx::{Device, CommandQueue,FrameSync, GraphicsPoolExt,
Surface, Swapchain, SwapchainExt, WindowExt};
use gfx::traits::DeviceExt;
use graphics::render_thread::RenderPackage;
type ColorFormat = gfx::format::Rgba8;
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];
gfx_defines!{
vertex SpriteVertex {
pos: [f32;2] = "a_Pos",
color: [f32;3] = "color",
rotation: f32 = "rotation",
uv: [f32;2] = "uv",
}
pipeline SpritePipeLine {
vbuf: gfx::VertexBuffer<SpriteVertex> = (),
sprite: gfx::TextureSampler<[f32; 4]> = "u_tex",
out: gfx::BlendTarget<ColorFormat> = ("Target0", gfx::state::MASK_ALL, gfx::preset::blend::ALPHA),
}
}
#[derive(Clone)]
pub struct SpriteRenderData {
pub pos: Vector2<f32>,
pub scale: Vector2<f32>,
pub z_rotation: f32,
pub color: [f32; 3],
}
pub struct SpriteRenderer {
pso: gfx::PipelineState<Resources, SpritePipeLine::Meta>,
graphics_pool: gfx::GraphicsCommandPool<gfx_device_gl::Backend>,
}
impl SpriteRenderer {
pub fn new(device: &mut gfx_device_gl::Device, graphics_pool: gfx::GraphicsCommandPool<gfx_device_gl::Backend>) -> SpriteRenderer {
let pso = device.create_pipeline_simple(
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/shaders/box_shader.vs"
)),
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/shaders/box_shader.fs"
)),
SpritePipeLine::new(),
).unwrap();
SpriteRenderer {
pso,
graphics_pool
}
}
pub fn render_sprites(&mut self, sprites_to_render: &Vec<SpriteRenderData>, render_package: &mut RenderPackage, view: &gfx::handle::RenderTargetView<gfx_device_gl::Resources, (gfx::format::R8_G8_B8_A8, gfx::format::Unorm)>,) {
let mut vertex_info = vec![];
let mut index_info : Vec<u16> = vec![];
// let mut graphics_pool = render_package.graphics_queue.create_graphics_pool(1);
for box_to_render in sprites_to_render.iter() {
vertex_info.extend(&[
SpriteVertex{pos: [box_to_render.pos.x + (-0.5f32 * box_to_render.scale.x), box_to_render.pos.y + (-0.5f32 * box_to_render.scale.y)], color: box_to_render.color, rotation: box_to_render.z_rotation, uv:[0.0f32, 0.0f32]},//top left
SpriteVertex{pos: [box_to_render.pos.x + ( 0.5f32 * box_to_render.scale.x), box_to_render.pos.y + (-0.5f32 * box_to_render.scale.y)], color: box_to_render.color, rotation: box_to_render.z_rotation, uv:[1.0f32, 0.0f32]},//top right
SpriteVertex{pos: [box_to_render.pos.x + (-0.5f32 * box_to_render.scale.x), box_to_render.pos.y + ( 0.5f32 * box_to_render.scale.y)], color: box_to_render.color, rotation: box_to_render.z_rotation, uv:[0.0f32, 1.0f32]},//bottom left
SpriteVertex{pos: [box_to_render.pos.x + ( 0.5f32 * box_to_render.scale.x), box_to_render.pos.y + ( 0.5f32 * box_to_render.scale.y)], color: box_to_render.color, rotation: box_to_render.z_rotation, uv:[1.0f32, 1.0f32]}//bottom right
]
);
}
for i in 0..sprites_to_render.len() { | 2 + (i * 4), 1 + (i * 4), 3 + (i * 4)]);//bottom right triangle
}
let (vertex_buffer, index_buffer) = render_package.device.create_vertex_buffer_with_slice(&vertex_info, &*index_info);
let text_sampler = render_package.device.create_sampler_linear();
let sprite_data = SpritePipeLine::Data {
vbuf: vertex_buffer.clone(),
sprite: (_, text_sampler),
out: view.clone(),
};
{
let mut box_encoder = self.graphics_pool.acquire_graphics_encoder();
box_encoder.clear(&sprite_data.out, BLACK);
box_encoder.draw(&index_buffer, &self.pso, &sprite_data);
let _ = box_encoder.synced_flush(render_package.graphics_queue, &[&render_package.frame_semaphore], &[&render_package.draw_semaphore], Some(&render_package.frame_fence)).expect("could not flush encoder");
}
self.graphics_pool.reset();
}
}
*/ | let i = i as u16;
index_info.extend(&[0 + (i * 4), 1 + (i * 4), 2 + (i * 4),//top left triangle | random_line_split |
main.rs | //! # Beamium.
//!
//! Beamium scrap Prometheus endpoint and forward metrics to Warp10.
extern crate backoff;
extern crate bytes;
extern crate cast;
extern crate clap;
extern crate core;
extern crate ctrlc;
extern crate flate2;
extern crate futures;
extern crate humantime;
extern crate hyper;
extern crate hyper_timeout;
extern crate hyper_tls;
extern crate nix;
extern crate regex;
#[macro_use]
extern crate slog;
extern crate slog_async;
#[macro_use]
extern crate slog_scope;
extern crate slog_stream;
extern crate slog_syslog;
extern crate slog_term;
extern crate time;
extern crate tokio_core;
extern crate tokio_timer;
extern crate yaml_rust;
use clap::App;
use std::fs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
mod config;
mod lib;
mod log;
mod router;
mod scraper;
mod sink;
include!("version.rs");
/// Main loop.
fn main() |
// Bootstrap config
let config_path = matches.value_of("config").unwrap_or("");
let config = match config::load_config(&config_path) {
Ok(config) => config,
Err(err) => {
crit!("Fail to load config {}: {}", &config_path, err);
std::process::abort();
}
};
if matches.is_present("t") {
info!("config ok");
std::process::exit(0);
}
info!("starting");
// Setup logging
match log::log(&config.parameters, matches.occurrences_of("v")) {
Ok(()) => {}
Err(err) => {
crit!("Log setup failure: {}", err);
std::process::abort();
}
}
// Ensure dirs
match fs::create_dir_all(&config.parameters.source_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create source directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
match fs::create_dir_all(&config.parameters.sink_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create sink directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
// Synchronisation stuff
let sigint = Arc::new(AtomicBool::new(false));
let mut handles = Vec::with_capacity(config.scrapers.len());
// Sigint handling
let r = sigint.clone();
ctrlc::set_handler(move || {
r.store(true, Ordering::SeqCst);
}).expect("Error setting sigint handler");
// Spawn scrapers
info!("spawning scrapers");
for scraper in config.scrapers.clone() {
let (parameters, sigint) = (config.parameters.clone(), sigint.clone());
handles.push(thread::spawn(move || {
slog_scope::scope(
&slog_scope::logger().new(o!("scraper" => scraper.name.clone())),
|| scraper::scraper(&scraper, ¶meters, &sigint),
);
}));
}
// Spawn router
info!("spawning router");
let mut router = router::Router::new(&config.sinks, &config.parameters, &config.labels);
router.start();
// Spawn sinks
info!("spawning sinks");
let mut sinks: Vec<sink::Sink> = config
.sinks
.iter()
.map(|sink| sink::Sink::new(&sink, &config.parameters))
.collect();
sinks.iter_mut().for_each(|s| s.start());
info!("started");
// Wait for sigint
loop {
thread::sleep(Duration::from_millis(10));
if sigint.load(Ordering::Relaxed) {
break;
}
}
info!("shutting down");
for handle in handles {
handle.join().unwrap();
}
router.stop();
for s in sinks {
s.stop();
}
info!("halted");
}
| {
// Setup a bare logger
log::bootstrap();
let matches = App::new("beamium")
.version(&*format!(
"{} ({}#{})",
env!("CARGO_PKG_VERSION"),
COMMIT,
PROFILE,
))
.author("d33d33 <kevin@d33d33.fr>")
.about("Send Prometheus metrics to Warp10")
.args_from_usage(
"-c, --config=[FILE] 'Sets a custom config file'
\
-v... 'Increase verbosity level (console only)'
-t 'Test config'",
)
.get_matches(); | identifier_body |
main.rs | //! # Beamium.
//!
//! Beamium scrap Prometheus endpoint and forward metrics to Warp10.
extern crate backoff;
extern crate bytes;
extern crate cast;
extern crate clap;
extern crate core;
extern crate ctrlc;
extern crate flate2;
extern crate futures;
extern crate humantime;
extern crate hyper;
extern crate hyper_timeout;
extern crate hyper_tls;
extern crate nix;
extern crate regex;
#[macro_use]
extern crate slog;
extern crate slog_async;
#[macro_use]
extern crate slog_scope;
extern crate slog_stream;
extern crate slog_syslog;
extern crate slog_term;
extern crate time;
extern crate tokio_core;
extern crate tokio_timer;
extern crate yaml_rust;
use clap::App;
use std::fs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
mod config;
mod lib;
mod log;
mod router;
mod scraper;
mod sink;
include!("version.rs");
/// Main loop.
fn main() {
// Setup a bare logger
log::bootstrap();
let matches = App::new("beamium")
.version(&*format!(
"{} ({}#{})",
env!("CARGO_PKG_VERSION"),
COMMIT,
PROFILE,
))
.author("d33d33 <kevin@d33d33.fr>")
.about("Send Prometheus metrics to Warp10")
.args_from_usage(
"-c, --config=[FILE] 'Sets a custom config file'
\
-v... 'Increase verbosity level (console only)'
-t 'Test config'",
)
.get_matches();
// Bootstrap config
let config_path = matches.value_of("config").unwrap_or(""); | std::process::abort();
}
};
if matches.is_present("t") {
info!("config ok");
std::process::exit(0);
}
info!("starting");
// Setup logging
match log::log(&config.parameters, matches.occurrences_of("v")) {
Ok(()) => {}
Err(err) => {
crit!("Log setup failure: {}", err);
std::process::abort();
}
}
// Ensure dirs
match fs::create_dir_all(&config.parameters.source_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create source directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
match fs::create_dir_all(&config.parameters.sink_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create sink directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
// Synchronisation stuff
let sigint = Arc::new(AtomicBool::new(false));
let mut handles = Vec::with_capacity(config.scrapers.len());
// Sigint handling
let r = sigint.clone();
ctrlc::set_handler(move || {
r.store(true, Ordering::SeqCst);
}).expect("Error setting sigint handler");
// Spawn scrapers
info!("spawning scrapers");
for scraper in config.scrapers.clone() {
let (parameters, sigint) = (config.parameters.clone(), sigint.clone());
handles.push(thread::spawn(move || {
slog_scope::scope(
&slog_scope::logger().new(o!("scraper" => scraper.name.clone())),
|| scraper::scraper(&scraper, ¶meters, &sigint),
);
}));
}
// Spawn router
info!("spawning router");
let mut router = router::Router::new(&config.sinks, &config.parameters, &config.labels);
router.start();
// Spawn sinks
info!("spawning sinks");
let mut sinks: Vec<sink::Sink> = config
.sinks
.iter()
.map(|sink| sink::Sink::new(&sink, &config.parameters))
.collect();
sinks.iter_mut().for_each(|s| s.start());
info!("started");
// Wait for sigint
loop {
thread::sleep(Duration::from_millis(10));
if sigint.load(Ordering::Relaxed) {
break;
}
}
info!("shutting down");
for handle in handles {
handle.join().unwrap();
}
router.stop();
for s in sinks {
s.stop();
}
info!("halted");
} | let config = match config::load_config(&config_path) {
Ok(config) => config,
Err(err) => {
crit!("Fail to load config {}: {}", &config_path, err); | random_line_split |
main.rs | //! # Beamium.
//!
//! Beamium scrap Prometheus endpoint and forward metrics to Warp10.
extern crate backoff;
extern crate bytes;
extern crate cast;
extern crate clap;
extern crate core;
extern crate ctrlc;
extern crate flate2;
extern crate futures;
extern crate humantime;
extern crate hyper;
extern crate hyper_timeout;
extern crate hyper_tls;
extern crate nix;
extern crate regex;
#[macro_use]
extern crate slog;
extern crate slog_async;
#[macro_use]
extern crate slog_scope;
extern crate slog_stream;
extern crate slog_syslog;
extern crate slog_term;
extern crate time;
extern crate tokio_core;
extern crate tokio_timer;
extern crate yaml_rust;
use clap::App;
use std::fs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
mod config;
mod lib;
mod log;
mod router;
mod scraper;
mod sink;
include!("version.rs");
/// Main loop.
fn | () {
// Setup a bare logger
log::bootstrap();
let matches = App::new("beamium")
.version(&*format!(
"{} ({}#{})",
env!("CARGO_PKG_VERSION"),
COMMIT,
PROFILE,
))
.author("d33d33 <kevin@d33d33.fr>")
.about("Send Prometheus metrics to Warp10")
.args_from_usage(
"-c, --config=[FILE] 'Sets a custom config file'
\
-v... 'Increase verbosity level (console only)'
-t 'Test config'",
)
.get_matches();
// Bootstrap config
let config_path = matches.value_of("config").unwrap_or("");
let config = match config::load_config(&config_path) {
Ok(config) => config,
Err(err) => {
crit!("Fail to load config {}: {}", &config_path, err);
std::process::abort();
}
};
if matches.is_present("t") {
info!("config ok");
std::process::exit(0);
}
info!("starting");
// Setup logging
match log::log(&config.parameters, matches.occurrences_of("v")) {
Ok(()) => {}
Err(err) => {
crit!("Log setup failure: {}", err);
std::process::abort();
}
}
// Ensure dirs
match fs::create_dir_all(&config.parameters.source_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create source directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
match fs::create_dir_all(&config.parameters.sink_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create sink directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
// Synchronisation stuff
let sigint = Arc::new(AtomicBool::new(false));
let mut handles = Vec::with_capacity(config.scrapers.len());
// Sigint handling
let r = sigint.clone();
ctrlc::set_handler(move || {
r.store(true, Ordering::SeqCst);
}).expect("Error setting sigint handler");
// Spawn scrapers
info!("spawning scrapers");
for scraper in config.scrapers.clone() {
let (parameters, sigint) = (config.parameters.clone(), sigint.clone());
handles.push(thread::spawn(move || {
slog_scope::scope(
&slog_scope::logger().new(o!("scraper" => scraper.name.clone())),
|| scraper::scraper(&scraper, ¶meters, &sigint),
);
}));
}
// Spawn router
info!("spawning router");
let mut router = router::Router::new(&config.sinks, &config.parameters, &config.labels);
router.start();
// Spawn sinks
info!("spawning sinks");
let mut sinks: Vec<sink::Sink> = config
.sinks
.iter()
.map(|sink| sink::Sink::new(&sink, &config.parameters))
.collect();
sinks.iter_mut().for_each(|s| s.start());
info!("started");
// Wait for sigint
loop {
thread::sleep(Duration::from_millis(10));
if sigint.load(Ordering::Relaxed) {
break;
}
}
info!("shutting down");
for handle in handles {
handle.join().unwrap();
}
router.stop();
for s in sinks {
s.stop();
}
info!("halted");
}
| main | identifier_name |
main.rs | //! # Beamium.
//!
//! Beamium scrap Prometheus endpoint and forward metrics to Warp10.
extern crate backoff;
extern crate bytes;
extern crate cast;
extern crate clap;
extern crate core;
extern crate ctrlc;
extern crate flate2;
extern crate futures;
extern crate humantime;
extern crate hyper;
extern crate hyper_timeout;
extern crate hyper_tls;
extern crate nix;
extern crate regex;
#[macro_use]
extern crate slog;
extern crate slog_async;
#[macro_use]
extern crate slog_scope;
extern crate slog_stream;
extern crate slog_syslog;
extern crate slog_term;
extern crate time;
extern crate tokio_core;
extern crate tokio_timer;
extern crate yaml_rust;
use clap::App;
use std::fs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
mod config;
mod lib;
mod log;
mod router;
mod scraper;
mod sink;
include!("version.rs");
/// Main loop.
fn main() {
// Setup a bare logger
log::bootstrap();
let matches = App::new("beamium")
.version(&*format!(
"{} ({}#{})",
env!("CARGO_PKG_VERSION"),
COMMIT,
PROFILE,
))
.author("d33d33 <kevin@d33d33.fr>")
.about("Send Prometheus metrics to Warp10")
.args_from_usage(
"-c, --config=[FILE] 'Sets a custom config file'
\
-v... 'Increase verbosity level (console only)'
-t 'Test config'",
)
.get_matches();
// Bootstrap config
let config_path = matches.value_of("config").unwrap_or("");
let config = match config::load_config(&config_path) {
Ok(config) => config,
Err(err) => {
crit!("Fail to load config {}: {}", &config_path, err);
std::process::abort();
}
};
if matches.is_present("t") {
info!("config ok");
std::process::exit(0);
}
info!("starting");
// Setup logging
match log::log(&config.parameters, matches.occurrences_of("v")) {
Ok(()) => {}
Err(err) => {
crit!("Log setup failure: {}", err);
std::process::abort();
}
}
// Ensure dirs
match fs::create_dir_all(&config.parameters.source_dir) {
Ok(()) => {}
Err(err) => |
};
match fs::create_dir_all(&config.parameters.sink_dir) {
Ok(()) => {}
Err(err) => {
crit!(
"Fail to create sink directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
}
};
// Synchronisation stuff
let sigint = Arc::new(AtomicBool::new(false));
let mut handles = Vec::with_capacity(config.scrapers.len());
// Sigint handling
let r = sigint.clone();
ctrlc::set_handler(move || {
r.store(true, Ordering::SeqCst);
}).expect("Error setting sigint handler");
// Spawn scrapers
info!("spawning scrapers");
for scraper in config.scrapers.clone() {
let (parameters, sigint) = (config.parameters.clone(), sigint.clone());
handles.push(thread::spawn(move || {
slog_scope::scope(
&slog_scope::logger().new(o!("scraper" => scraper.name.clone())),
|| scraper::scraper(&scraper, ¶meters, &sigint),
);
}));
}
// Spawn router
info!("spawning router");
let mut router = router::Router::new(&config.sinks, &config.parameters, &config.labels);
router.start();
// Spawn sinks
info!("spawning sinks");
let mut sinks: Vec<sink::Sink> = config
.sinks
.iter()
.map(|sink| sink::Sink::new(&sink, &config.parameters))
.collect();
sinks.iter_mut().for_each(|s| s.start());
info!("started");
// Wait for sigint
loop {
thread::sleep(Duration::from_millis(10));
if sigint.load(Ordering::Relaxed) {
break;
}
}
info!("shutting down");
for handle in handles {
handle.join().unwrap();
}
router.stop();
for s in sinks {
s.stop();
}
info!("halted");
}
| {
crit!(
"Fail to create source directory {}: {}",
&config.parameters.source_dir,
err
);
std::process::abort();
} | conditional_block |
regex.rs | // Copyright (c) 2014 Michael Woerister
// 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 statemachine::{StateMachine, StateId, Char, Epsilon};
#[deriving(Clone, IterBytes, Eq)]
pub enum Regex {
Leaf(char),
Kleene(~Regex),
Seq(~Regex, ~Regex),
Union(~Regex, ~Regex),
}
impl Regex {
pub fn to_state_machine(&self) -> (StateMachine, StateId, StateId) {
match *self {
Leaf(c) => {
let mut sm = StateMachine::new();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, end_state, Char(c));
(sm, start_state, end_state)
}
Kleene(ref sub) => {
let (mut sm, sub_start, sub_end) = sub.to_state_machine();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, sub_start, Epsilon);
sm.add_transition(sub_end, sub_start, Epsilon);
sm.add_transition(sub_end, end_state, Epsilon);
sm.add_transition(start_state, end_state, Epsilon);
(sm, start_state, end_state)
}
Seq(ref left, ref right) => {
let (mut left_sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
left_sm.consume(right_sm);
left_sm.add_transition(left_end, right_start, Epsilon);
(left_sm, left_start, right_end)
}
Union(ref left, ref right) => {
let (mut sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
sm.consume(right_sm);
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, left_start, Epsilon);
sm.add_transition(start_state, right_start, Epsilon);
sm.add_transition(left_end, end_state, Epsilon);
sm.add_transition(right_end, end_state, Epsilon);
(sm, start_state, end_state)
}
}
}
}
#[cfg(test)]
mod test {
use super::{Regex, Seq, Union, Kleene, Leaf};
use statemachine::{StateMachine, StateId, StateSet, ToDfaResult};
fn compile(regex: &Regex) -> (StateMachine, StateId, ~[StateId]) {
let (sm, start, end) = regex.to_state_machine();
let end_states = [end];
let end_states: StateSet = end_states.iter().map(|x| *x).collect();
let ToDfaResult { dfa, start_state, end_state_map } = sm.to_dfa(start, &end_states);
let dfa_end_states = end_state_map.keys().map(|x| *x).to_owned_vec();
let partitioning = dfa.accepting_non_accepting_partitioning(dfa_end_states.iter().map(|s| *s));
let (minimized_dfa, state_map) = dfa.to_minimal(&partitioning);
let start_state = state_map.get_copy(&start_state);
let dfa_end_states = dfa_end_states.iter().map(|s| state_map.get_copy(s)).collect::<StateSet>();
(minimized_dfa, start_state, dfa_end_states.iter().map(|x| x.clone()).to_owned_vec())
}
fn matches(&(ref sm, start_state, ref end_states): &(StateMachine, StateId, ~[StateId]), s: &str) -> bool {
let result_state = sm.run(start_state, s);
end_states.iter().any(|&x| Some(x) == result_state)
}
#[test]
fn | () {
let sm = compile(&Kleene(~Leaf('a')));
assert!(matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "aaa"));
assert!(matches(&sm, "aaaaaaaaaaaaaaaaaaaaaaaaaa"));
assert!(!matches(&sm, "b"));
assert!(!matches(&sm, "caaaa"));
assert!(!matches(&sm, "daaa"));
assert!(!matches(&sm, "e"));
assert!(!matches(&sm, "ab"));
}
#[test]
fn test_seq() {
let sm = compile(&Seq(~Leaf('a'), ~Seq(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(!matches(&sm, "a"));
assert!(!matches(&sm, "ab"));
assert!(matches(&sm, "abc"));
assert!(!matches(&sm, "abcd"));
assert!(!matches(&sm, "bc"));
assert!(!matches(&sm, "c"));
assert!(!matches(&sm, "bca"));
}
#[test]
fn test_union() {
let sm = compile(&Union(~Leaf('a'), ~Union(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(!matches(&sm, "ab"));
assert!(!matches(&sm, "ac"));
assert!(!matches(&sm, "bc"));
}
#[test]
fn test_ident_like() {
let alpha = ~Union(
~Leaf('a'),
~Union(
~Leaf('b'),
~Union(
~Leaf('c'),
~Leaf('d')
)
)
);
let digit = ~Union(
~Leaf('1'),
~Union(
~Leaf('2'),
~Union(
~Leaf('3'),
~Leaf('4')
)
)
);
let regex = Seq(alpha.clone(), ~Kleene(~Union(alpha, digit)));
let sm = compile(®ex);
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(matches(&sm, "d"));
assert!(!matches(&sm, "1"));
assert!(!matches(&sm, "2"));
assert!(!matches(&sm, "3"));
assert!(!matches(&sm, "4"));
assert!(matches(&sm, "aaaa"));
assert!(matches(&sm, "a1b2"));
assert!(matches(&sm, "aab1a"));
assert!(matches(&sm, "dddaca"));
assert!(!matches(&sm, "1cbda"));
assert!(!matches(&sm, "2dca"));
assert!(!matches(&sm, "3da"));
assert!(!matches(&sm, "4d"));
assert!(!matches(&sm, "5ddda"));
}
} | test_kleene | identifier_name |
regex.rs | // Copyright (c) 2014 Michael Woerister
// 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 statemachine::{StateMachine, StateId, Char, Epsilon};
#[deriving(Clone, IterBytes, Eq)]
pub enum Regex {
Leaf(char),
Kleene(~Regex),
Seq(~Regex, ~Regex),
Union(~Regex, ~Regex),
}
impl Regex {
pub fn to_state_machine(&self) -> (StateMachine, StateId, StateId) {
match *self {
Leaf(c) => {
let mut sm = StateMachine::new();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, end_state, Char(c));
(sm, start_state, end_state)
}
Kleene(ref sub) => |
Seq(ref left, ref right) => {
let (mut left_sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
left_sm.consume(right_sm);
left_sm.add_transition(left_end, right_start, Epsilon);
(left_sm, left_start, right_end)
}
Union(ref left, ref right) => {
let (mut sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
sm.consume(right_sm);
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, left_start, Epsilon);
sm.add_transition(start_state, right_start, Epsilon);
sm.add_transition(left_end, end_state, Epsilon);
sm.add_transition(right_end, end_state, Epsilon);
(sm, start_state, end_state)
}
}
}
}
#[cfg(test)]
mod test {
use super::{Regex, Seq, Union, Kleene, Leaf};
use statemachine::{StateMachine, StateId, StateSet, ToDfaResult};
fn compile(regex: &Regex) -> (StateMachine, StateId, ~[StateId]) {
let (sm, start, end) = regex.to_state_machine();
let end_states = [end];
let end_states: StateSet = end_states.iter().map(|x| *x).collect();
let ToDfaResult { dfa, start_state, end_state_map } = sm.to_dfa(start, &end_states);
let dfa_end_states = end_state_map.keys().map(|x| *x).to_owned_vec();
let partitioning = dfa.accepting_non_accepting_partitioning(dfa_end_states.iter().map(|s| *s));
let (minimized_dfa, state_map) = dfa.to_minimal(&partitioning);
let start_state = state_map.get_copy(&start_state);
let dfa_end_states = dfa_end_states.iter().map(|s| state_map.get_copy(s)).collect::<StateSet>();
(minimized_dfa, start_state, dfa_end_states.iter().map(|x| x.clone()).to_owned_vec())
}
fn matches(&(ref sm, start_state, ref end_states): &(StateMachine, StateId, ~[StateId]), s: &str) -> bool {
let result_state = sm.run(start_state, s);
end_states.iter().any(|&x| Some(x) == result_state)
}
#[test]
fn test_kleene() {
let sm = compile(&Kleene(~Leaf('a')));
assert!(matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "aaa"));
assert!(matches(&sm, "aaaaaaaaaaaaaaaaaaaaaaaaaa"));
assert!(!matches(&sm, "b"));
assert!(!matches(&sm, "caaaa"));
assert!(!matches(&sm, "daaa"));
assert!(!matches(&sm, "e"));
assert!(!matches(&sm, "ab"));
}
#[test]
fn test_seq() {
let sm = compile(&Seq(~Leaf('a'), ~Seq(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(!matches(&sm, "a"));
assert!(!matches(&sm, "ab"));
assert!(matches(&sm, "abc"));
assert!(!matches(&sm, "abcd"));
assert!(!matches(&sm, "bc"));
assert!(!matches(&sm, "c"));
assert!(!matches(&sm, "bca"));
}
#[test]
fn test_union() {
let sm = compile(&Union(~Leaf('a'), ~Union(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(!matches(&sm, "ab"));
assert!(!matches(&sm, "ac"));
assert!(!matches(&sm, "bc"));
}
#[test]
fn test_ident_like() {
let alpha = ~Union(
~Leaf('a'),
~Union(
~Leaf('b'),
~Union(
~Leaf('c'),
~Leaf('d')
)
)
);
let digit = ~Union(
~Leaf('1'),
~Union(
~Leaf('2'),
~Union(
~Leaf('3'),
~Leaf('4')
)
)
);
let regex = Seq(alpha.clone(), ~Kleene(~Union(alpha, digit)));
let sm = compile(®ex);
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(matches(&sm, "d"));
assert!(!matches(&sm, "1"));
assert!(!matches(&sm, "2"));
assert!(!matches(&sm, "3"));
assert!(!matches(&sm, "4"));
assert!(matches(&sm, "aaaa"));
assert!(matches(&sm, "a1b2"));
assert!(matches(&sm, "aab1a"));
assert!(matches(&sm, "dddaca"));
assert!(!matches(&sm, "1cbda"));
assert!(!matches(&sm, "2dca"));
assert!(!matches(&sm, "3da"));
assert!(!matches(&sm, "4d"));
assert!(!matches(&sm, "5ddda"));
}
} | {
let (mut sm, sub_start, sub_end) = sub.to_state_machine();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, sub_start, Epsilon);
sm.add_transition(sub_end, sub_start, Epsilon);
sm.add_transition(sub_end, end_state, Epsilon);
sm.add_transition(start_state, end_state, Epsilon);
(sm, start_state, end_state)
} | conditional_block |
regex.rs | // Copyright (c) 2014 Michael Woerister
// 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 statemachine::{StateMachine, StateId, Char, Epsilon};
#[deriving(Clone, IterBytes, Eq)]
pub enum Regex {
Leaf(char),
Kleene(~Regex),
Seq(~Regex, ~Regex),
Union(~Regex, ~Regex),
}
impl Regex {
pub fn to_state_machine(&self) -> (StateMachine, StateId, StateId) {
match *self {
Leaf(c) => {
let mut sm = StateMachine::new();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, end_state, Char(c));
(sm, start_state, end_state)
}
Kleene(ref sub) => {
let (mut sm, sub_start, sub_end) = sub.to_state_machine();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, sub_start, Epsilon);
sm.add_transition(sub_end, sub_start, Epsilon);
sm.add_transition(sub_end, end_state, Epsilon);
sm.add_transition(start_state, end_state, Epsilon);
(sm, start_state, end_state)
}
Seq(ref left, ref right) => {
let (mut left_sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
left_sm.consume(right_sm);
left_sm.add_transition(left_end, right_start, Epsilon);
(left_sm, left_start, right_end)
}
Union(ref left, ref right) => {
let (mut sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
sm.consume(right_sm);
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, left_start, Epsilon);
sm.add_transition(start_state, right_start, Epsilon);
sm.add_transition(left_end, end_state, Epsilon);
sm.add_transition(right_end, end_state, Epsilon);
(sm, start_state, end_state)
}
}
}
}
#[cfg(test)]
mod test {
use super::{Regex, Seq, Union, Kleene, Leaf};
use statemachine::{StateMachine, StateId, StateSet, ToDfaResult};
fn compile(regex: &Regex) -> (StateMachine, StateId, ~[StateId]) {
let (sm, start, end) = regex.to_state_machine();
let end_states = [end];
let end_states: StateSet = end_states.iter().map(|x| *x).collect();
let ToDfaResult { dfa, start_state, end_state_map } = sm.to_dfa(start, &end_states);
let dfa_end_states = end_state_map.keys().map(|x| *x).to_owned_vec();
let partitioning = dfa.accepting_non_accepting_partitioning(dfa_end_states.iter().map(|s| *s));
let (minimized_dfa, state_map) = dfa.to_minimal(&partitioning);
let start_state = state_map.get_copy(&start_state);
let dfa_end_states = dfa_end_states.iter().map(|s| state_map.get_copy(s)).collect::<StateSet>();
(minimized_dfa, start_state, dfa_end_states.iter().map(|x| x.clone()).to_owned_vec())
}
fn matches(&(ref sm, start_state, ref end_states): &(StateMachine, StateId, ~[StateId]), s: &str) -> bool {
let result_state = sm.run(start_state, s);
end_states.iter().any(|&x| Some(x) == result_state)
}
#[test]
fn test_kleene() {
let sm = compile(&Kleene(~Leaf('a')));
assert!(matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "aaa"));
assert!(matches(&sm, "aaaaaaaaaaaaaaaaaaaaaaaaaa"));
| assert!(!matches(&sm, "ab"));
}
#[test]
fn test_seq() {
let sm = compile(&Seq(~Leaf('a'), ~Seq(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(!matches(&sm, "a"));
assert!(!matches(&sm, "ab"));
assert!(matches(&sm, "abc"));
assert!(!matches(&sm, "abcd"));
assert!(!matches(&sm, "bc"));
assert!(!matches(&sm, "c"));
assert!(!matches(&sm, "bca"));
}
#[test]
fn test_union() {
let sm = compile(&Union(~Leaf('a'), ~Union(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(!matches(&sm, "ab"));
assert!(!matches(&sm, "ac"));
assert!(!matches(&sm, "bc"));
}
#[test]
fn test_ident_like() {
let alpha = ~Union(
~Leaf('a'),
~Union(
~Leaf('b'),
~Union(
~Leaf('c'),
~Leaf('d')
)
)
);
let digit = ~Union(
~Leaf('1'),
~Union(
~Leaf('2'),
~Union(
~Leaf('3'),
~Leaf('4')
)
)
);
let regex = Seq(alpha.clone(), ~Kleene(~Union(alpha, digit)));
let sm = compile(®ex);
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(matches(&sm, "d"));
assert!(!matches(&sm, "1"));
assert!(!matches(&sm, "2"));
assert!(!matches(&sm, "3"));
assert!(!matches(&sm, "4"));
assert!(matches(&sm, "aaaa"));
assert!(matches(&sm, "a1b2"));
assert!(matches(&sm, "aab1a"));
assert!(matches(&sm, "dddaca"));
assert!(!matches(&sm, "1cbda"));
assert!(!matches(&sm, "2dca"));
assert!(!matches(&sm, "3da"));
assert!(!matches(&sm, "4d"));
assert!(!matches(&sm, "5ddda"));
}
} | assert!(!matches(&sm, "b"));
assert!(!matches(&sm, "caaaa"));
assert!(!matches(&sm, "daaa"));
assert!(!matches(&sm, "e")); | random_line_split |
regex.rs | // Copyright (c) 2014 Michael Woerister
// 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 statemachine::{StateMachine, StateId, Char, Epsilon};
#[deriving(Clone, IterBytes, Eq)]
pub enum Regex {
Leaf(char),
Kleene(~Regex),
Seq(~Regex, ~Regex),
Union(~Regex, ~Regex),
}
impl Regex {
pub fn to_state_machine(&self) -> (StateMachine, StateId, StateId) {
match *self {
Leaf(c) => {
let mut sm = StateMachine::new();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, end_state, Char(c));
(sm, start_state, end_state)
}
Kleene(ref sub) => {
let (mut sm, sub_start, sub_end) = sub.to_state_machine();
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, sub_start, Epsilon);
sm.add_transition(sub_end, sub_start, Epsilon);
sm.add_transition(sub_end, end_state, Epsilon);
sm.add_transition(start_state, end_state, Epsilon);
(sm, start_state, end_state)
}
Seq(ref left, ref right) => {
let (mut left_sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
left_sm.consume(right_sm);
left_sm.add_transition(left_end, right_start, Epsilon);
(left_sm, left_start, right_end)
}
Union(ref left, ref right) => {
let (mut sm, left_start, left_end) = left.to_state_machine();
let (right_sm, right_start, right_end) = right.to_state_machine();
sm.consume(right_sm);
let start_state = sm.add_state();
let end_state = sm.add_state();
sm.add_transition(start_state, left_start, Epsilon);
sm.add_transition(start_state, right_start, Epsilon);
sm.add_transition(left_end, end_state, Epsilon);
sm.add_transition(right_end, end_state, Epsilon);
(sm, start_state, end_state)
}
}
}
}
#[cfg(test)]
mod test {
use super::{Regex, Seq, Union, Kleene, Leaf};
use statemachine::{StateMachine, StateId, StateSet, ToDfaResult};
fn compile(regex: &Regex) -> (StateMachine, StateId, ~[StateId]) |
fn matches(&(ref sm, start_state, ref end_states): &(StateMachine, StateId, ~[StateId]), s: &str) -> bool {
let result_state = sm.run(start_state, s);
end_states.iter().any(|&x| Some(x) == result_state)
}
#[test]
fn test_kleene() {
let sm = compile(&Kleene(~Leaf('a')));
assert!(matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "aaa"));
assert!(matches(&sm, "aaaaaaaaaaaaaaaaaaaaaaaaaa"));
assert!(!matches(&sm, "b"));
assert!(!matches(&sm, "caaaa"));
assert!(!matches(&sm, "daaa"));
assert!(!matches(&sm, "e"));
assert!(!matches(&sm, "ab"));
}
#[test]
fn test_seq() {
let sm = compile(&Seq(~Leaf('a'), ~Seq(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(!matches(&sm, "a"));
assert!(!matches(&sm, "ab"));
assert!(matches(&sm, "abc"));
assert!(!matches(&sm, "abcd"));
assert!(!matches(&sm, "bc"));
assert!(!matches(&sm, "c"));
assert!(!matches(&sm, "bca"));
}
#[test]
fn test_union() {
let sm = compile(&Union(~Leaf('a'), ~Union(~Leaf('b'),~Leaf('c'))));
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(!matches(&sm, "ab"));
assert!(!matches(&sm, "ac"));
assert!(!matches(&sm, "bc"));
}
#[test]
fn test_ident_like() {
let alpha = ~Union(
~Leaf('a'),
~Union(
~Leaf('b'),
~Union(
~Leaf('c'),
~Leaf('d')
)
)
);
let digit = ~Union(
~Leaf('1'),
~Union(
~Leaf('2'),
~Union(
~Leaf('3'),
~Leaf('4')
)
)
);
let regex = Seq(alpha.clone(), ~Kleene(~Union(alpha, digit)));
let sm = compile(®ex);
assert!(!matches(&sm, ""));
assert!(matches(&sm, "a"));
assert!(matches(&sm, "b"));
assert!(matches(&sm, "c"));
assert!(matches(&sm, "d"));
assert!(!matches(&sm, "1"));
assert!(!matches(&sm, "2"));
assert!(!matches(&sm, "3"));
assert!(!matches(&sm, "4"));
assert!(matches(&sm, "aaaa"));
assert!(matches(&sm, "a1b2"));
assert!(matches(&sm, "aab1a"));
assert!(matches(&sm, "dddaca"));
assert!(!matches(&sm, "1cbda"));
assert!(!matches(&sm, "2dca"));
assert!(!matches(&sm, "3da"));
assert!(!matches(&sm, "4d"));
assert!(!matches(&sm, "5ddda"));
}
} | {
let (sm, start, end) = regex.to_state_machine();
let end_states = [end];
let end_states: StateSet = end_states.iter().map(|x| *x).collect();
let ToDfaResult { dfa, start_state, end_state_map } = sm.to_dfa(start, &end_states);
let dfa_end_states = end_state_map.keys().map(|x| *x).to_owned_vec();
let partitioning = dfa.accepting_non_accepting_partitioning(dfa_end_states.iter().map(|s| *s));
let (minimized_dfa, state_map) = dfa.to_minimal(&partitioning);
let start_state = state_map.get_copy(&start_state);
let dfa_end_states = dfa_end_states.iter().map(|s| state_map.get_copy(s)).collect::<StateSet>();
(minimized_dfa, start_state, dfa_end_states.iter().map(|x| x.clone()).to_owned_vec())
} | identifier_body |
regions-close-associated-type-into-object.rs | trait X {}
trait Iter {
type Item: X;
fn into_item(self) -> Self::Item;
fn as_item(&self) -> &Self::Item;
}
fn bad1<T: Iter>(v: T) -> Box<dyn X +'static>
{
let item = v.into_item();
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad2<T: Iter>(v: T) -> Box<dyn X +'static>
where Box<T::Item> : X
{
let item: Box<_> = Box::new(v.into_item());
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad3<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
{
let item = v.into_item();
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad4<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
where Box<T::Item> : X
|
fn ok1<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
where T::Item : 'a
{
let item = v.into_item();
Box::new(item) // OK, T::Item : 'a is declared
}
fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a>
where T::Item : Clone
{
let item = Clone::clone(w);
Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a, T: Iter>(v: &'a T) -> Box<dyn X + 'a>
where T::Item : Clone + 'a
{
let item = Clone::clone(v.as_item());
Box::new(item) // OK, T::Item : 'a was declared
}
fn meh1<'a, T: Iter>(v: &'a T) -> Box<dyn X + 'a>
where T::Item : Clone
{
// This case is kind of interesting. It's the same as `ok3` but
// without the explicit declaration. This is valid because `T: 'a
// => T::Item: 'a`, and the former we can deduce from our argument
// of type `&'a T`.
let item = Clone::clone(v.as_item());
Box::new(item)
}
fn main() {}
| {
let item: Box<_> = Box::new(v.into_item());
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
} | identifier_body |
regions-close-associated-type-into-object.rs | trait X {}
trait Iter {
type Item: X;
fn into_item(self) -> Self::Item;
fn as_item(&self) -> &Self::Item;
}
fn bad1<T: Iter>(v: T) -> Box<dyn X +'static>
{
let item = v.into_item();
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad2<T: Iter>(v: T) -> Box<dyn X +'static>
where Box<T::Item> : X
{
let item: Box<_> = Box::new(v.into_item());
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad3<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
{
let item = v.into_item();
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad4<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
where Box<T::Item> : X
{
let item: Box<_> = Box::new(v.into_item());
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn | <'a, T: Iter>(v: T) -> Box<dyn X + 'a>
where T::Item : 'a
{
let item = v.into_item();
Box::new(item) // OK, T::Item : 'a is declared
}
fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a>
where T::Item : Clone
{
let item = Clone::clone(w);
Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a, T: Iter>(v: &'a T) -> Box<dyn X + 'a>
where T::Item : Clone + 'a
{
let item = Clone::clone(v.as_item());
Box::new(item) // OK, T::Item : 'a was declared
}
fn meh1<'a, T: Iter>(v: &'a T) -> Box<dyn X + 'a>
where T::Item : Clone
{
// This case is kind of interesting. It's the same as `ok3` but
// without the explicit declaration. This is valid because `T: 'a
// => T::Item: 'a`, and the former we can deduce from our argument
// of type `&'a T`.
let item = Clone::clone(v.as_item());
Box::new(item)
}
fn main() {}
| ok1 | identifier_name |
regions-close-associated-type-into-object.rs | trait X {}
| trait Iter {
type Item: X;
fn into_item(self) -> Self::Item;
fn as_item(&self) -> &Self::Item;
}
fn bad1<T: Iter>(v: T) -> Box<dyn X +'static>
{
let item = v.into_item();
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad2<T: Iter>(v: T) -> Box<dyn X +'static>
where Box<T::Item> : X
{
let item: Box<_> = Box::new(v.into_item());
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad3<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
{
let item = v.into_item();
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn bad4<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
where Box<T::Item> : X
{
let item: Box<_> = Box::new(v.into_item());
Box::new(item) //~ ERROR associated type `<T as Iter>::Item` may not live long enough
}
fn ok1<'a, T: Iter>(v: T) -> Box<dyn X + 'a>
where T::Item : 'a
{
let item = v.into_item();
Box::new(item) // OK, T::Item : 'a is declared
}
fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<dyn X + 'a>
where T::Item : Clone
{
let item = Clone::clone(w);
Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a, T: Iter>(v: &'a T) -> Box<dyn X + 'a>
where T::Item : Clone + 'a
{
let item = Clone::clone(v.as_item());
Box::new(item) // OK, T::Item : 'a was declared
}
fn meh1<'a, T: Iter>(v: &'a T) -> Box<dyn X + 'a>
where T::Item : Clone
{
// This case is kind of interesting. It's the same as `ok3` but
// without the explicit declaration. This is valid because `T: 'a
// => T::Item: 'a`, and the former we can deduce from our argument
// of type `&'a T`.
let item = Clone::clone(v.as_item());
Box::new(item)
}
fn main() {} | random_line_split | |
test.rs | extern crate rimd;
use rimd::{SMF,SMFError};
use std::env::{args,Args};
use std::path::Path;
fn | () {
let mut args: Args = args();
args.next();
let pathstr = match args.next() {
Some(s) => s,
None => { panic!("Please pass a path to an SMF to test") },
};
println!("Reading: {}",pathstr);
match SMF::from_file(&Path::new(&pathstr[..])) {
Ok(smf) => {
println!("format: {}",smf.format);
println!("tracks: {}",smf.tracks.len());
println!("division: {}",smf.division);
let mut tnum = 1;
for track in smf.tracks.iter() {
let mut time: u64 = 0;
println!("\n{}: {}\nevents:",tnum,track);
tnum+=1;
for event in track.events.iter() {
println!(" {}",event.fmt_with_time_offset(time));
time += event.vtime;
}
}
}
Err(e) => {
match e {
SMFError::InvalidSMFFile(s) => {println!("{}",s);}
SMFError::Error(e) => {println!("io: {}",e);}
SMFError::MidiError(e) => {println!("Midi Error: {}",e);}
SMFError::MetaError(_) => {println!("Meta Error");}
}
}
}
}
| main | identifier_name |
test.rs | extern crate rimd;
use rimd::{SMF,SMFError};
use std::env::{args,Args};
use std::path::Path;
fn main() {
let mut args: Args = args();
args.next();
let pathstr = match args.next() {
Some(s) => s,
None => { panic!("Please pass a path to an SMF to test") },
};
println!("Reading: {}",pathstr);
match SMF::from_file(&Path::new(&pathstr[..])) {
Ok(smf) => {
println!("format: {}",smf.format);
println!("tracks: {}",smf.tracks.len()); | println!("\n{}: {}\nevents:",tnum,track);
tnum+=1;
for event in track.events.iter() {
println!(" {}",event.fmt_with_time_offset(time));
time += event.vtime;
}
}
}
Err(e) => {
match e {
SMFError::InvalidSMFFile(s) => {println!("{}",s);}
SMFError::Error(e) => {println!("io: {}",e);}
SMFError::MidiError(e) => {println!("Midi Error: {}",e);}
SMFError::MetaError(_) => {println!("Meta Error");}
}
}
}
} | println!("division: {}",smf.division);
let mut tnum = 1;
for track in smf.tracks.iter() {
let mut time: u64 = 0; | random_line_split |
test.rs | extern crate rimd;
use rimd::{SMF,SMFError};
use std::env::{args,Args};
use std::path::Path;
fn main() | time += event.vtime;
}
}
}
Err(e) => {
match e {
SMFError::InvalidSMFFile(s) => {println!("{}",s);}
SMFError::Error(e) => {println!("io: {}",e);}
SMFError::MidiError(e) => {println!("Midi Error: {}",e);}
SMFError::MetaError(_) => {println!("Meta Error");}
}
}
}
}
| {
let mut args: Args = args();
args.next();
let pathstr = match args.next() {
Some(s) => s,
None => { panic!("Please pass a path to an SMF to test") },
};
println!("Reading: {}",pathstr);
match SMF::from_file(&Path::new(&pathstr[..])) {
Ok(smf) => {
println!("format: {}",smf.format);
println!("tracks: {}",smf.tracks.len());
println!("division: {}",smf.division);
let mut tnum = 1;
for track in smf.tracks.iter() {
let mut time: u64 = 0;
println!("\n{}: {}\nevents:",tnum,track);
tnum+=1;
for event in track.events.iter() {
println!(" {}",event.fmt_with_time_offset(time)); | identifier_body |
timezoneapi.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! ApiSet Contract for api-ms-win-core-timezone-l1
pub const TIME_ZONE_ID_INVALID: ::DWORD = 0xFFFFFFFF;
STRUCT!{struct TIME_ZONE_INFORMATION {
Bias: ::LONG,
StandardName: [::WCHAR; 32],
StandardDate: ::SYSTEMTIME,
StandardBias: ::LONG,
DaylightName: [::WCHAR; 32],
DaylightDate: ::SYSTEMTIME,
DaylightBias: ::LONG,
}}
pub type PTIME_ZONE_INFORMATION = *mut TIME_ZONE_INFORMATION;
pub type LPTIME_ZONE_INFORMATION = *mut TIME_ZONE_INFORMATION;
STRUCT!{struct DYNAMIC_TIME_ZONE_INFORMATION {
Bias: ::LONG,
StandardName: [::WCHAR; 32],
StandardDate: ::SYSTEMTIME,
StandardBias: ::LONG,
DaylightName: [::WCHAR; 32],
DaylightDate: ::SYSTEMTIME,
DaylightBias: ::LONG,
TimeZoneKeyName: [::WCHAR; 128],
DynamicDaylightTimeDisabled: ::BOOLEAN,
}} | pub type PDYNAMIC_TIME_ZONE_INFORMATION = *mut DYNAMIC_TIME_ZONE_INFORMATION; | random_line_split | |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C:'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a, C> {
ComponentRef {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent.
pub fn get(self, Entity(idx): Entity) -> Option<&'a C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx)) => |
}
}
/// Fetch a component from given entity. Do not search parent entities.
pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> {
self.data.get(&idx).map_or(None, |x| x.as_ref())
}
}
/// Mutable component access.
pub struct ComponentRefMut<'a, C:'static> {
ecs: &'a mut Ecs,
/// Some(c) indicates the presence of a local component, None indicates
/// that there is no local component and that the component will not be
/// searched from the parent entity either. If the value is not present,
/// the component will be searched from a entity object if one exists.
data: &'a mut HashMap<usize, Option<C>>,
}
impl<'a, C: Clone> ComponentRefMut<'a, C> {
pub fn new(ecs: &'a mut Ecs, data: &'a mut HashMap<usize, Option<C>>) -> ComponentRefMut<'a, C> {
ComponentRefMut {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent. Copy-on-write
/// semantics: A component found on a parent entity will be copied on
/// local entity for mutation.
pub fn get(self, Entity(idx): Entity) -> Option<&'a mut C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx2)) if idx2 == idx => {
self.data.get_mut(&idx2).expect("missing component").as_mut()
}
Some(Entity(idx2)) => {
// Copy-on-write: Make a local copy of inherited component
// when asking for mutable access.
let cow = self.data.get(&idx2)
.expect("parent component lost").as_ref()
.expect("missing component").clone();
self.data.insert(idx, Some(cow));
self.data.get_mut(&idx).expect("missing component").as_mut()
}
}
}
/// Add a component to entity.
pub fn insert(self, Entity(idx): Entity, comp: C) {
self.data.insert(idx, Some(comp));
}
/// Clear a component from an entity. This will make a parent entity's
/// component visible instead, if there is one.
pub fn clear(self, Entity(idx): Entity) {
self.data.remove(&idx);
}
/// Make a component not show up on an entity even if it is present in the
/// parent entity. Hiding will be reset if the component is cleared.
pub fn hide(self, Entity(idx): Entity) {
self.data.insert(idx, None);
}
}
fn find_parent<P>(p: P, ecs: &Ecs, e: Entity) -> Option<Entity>
where P: Fn(Entity) -> bool
{
let mut current = e;
loop {
if p(current) { return Some(current); }
match ecs.parent(current) {
Some(parent) => { current = parent; }
None => { return None; }
}
}
}
| { self.data.get(&idx).expect("missing component").as_ref() } | conditional_block |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C:'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a, C> {
ComponentRef {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent.
pub fn get(self, Entity(idx): Entity) -> Option<&'a C> |
/// Fetch a component from given entity. Do not search parent entities.
pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> {
self.data.get(&idx).map_or(None, |x| x.as_ref())
}
}
/// Mutable component access.
pub struct ComponentRefMut<'a, C:'static> {
ecs: &'a mut Ecs,
/// Some(c) indicates the presence of a local component, None indicates
/// that there is no local component and that the component will not be
/// searched from the parent entity either. If the value is not present,
/// the component will be searched from a entity object if one exists.
data: &'a mut HashMap<usize, Option<C>>,
}
impl<'a, C: Clone> ComponentRefMut<'a, C> {
pub fn new(ecs: &'a mut Ecs, data: &'a mut HashMap<usize, Option<C>>) -> ComponentRefMut<'a, C> {
ComponentRefMut {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent. Copy-on-write
/// semantics: A component found on a parent entity will be copied on
/// local entity for mutation.
pub fn get(self, Entity(idx): Entity) -> Option<&'a mut C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx2)) if idx2 == idx => {
self.data.get_mut(&idx2).expect("missing component").as_mut()
}
Some(Entity(idx2)) => {
// Copy-on-write: Make a local copy of inherited component
// when asking for mutable access.
let cow = self.data.get(&idx2)
.expect("parent component lost").as_ref()
.expect("missing component").clone();
self.data.insert(idx, Some(cow));
self.data.get_mut(&idx).expect("missing component").as_mut()
}
}
}
/// Add a component to entity.
pub fn insert(self, Entity(idx): Entity, comp: C) {
self.data.insert(idx, Some(comp));
}
/// Clear a component from an entity. This will make a parent entity's
/// component visible instead, if there is one.
pub fn clear(self, Entity(idx): Entity) {
self.data.remove(&idx);
}
/// Make a component not show up on an entity even if it is present in the
/// parent entity. Hiding will be reset if the component is cleared.
pub fn hide(self, Entity(idx): Entity) {
self.data.insert(idx, None);
}
}
fn find_parent<P>(p: P, ecs: &Ecs, e: Entity) -> Option<Entity>
where P: Fn(Entity) -> bool
{
let mut current = e;
loop {
if p(current) { return Some(current); }
match ecs.parent(current) {
Some(parent) => { current = parent; }
None => { return None; }
}
}
}
| {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx)) => { self.data.get(&idx).expect("missing component").as_ref() }
}
} | identifier_body |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C:'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn | (ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a, C> {
ComponentRef {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent.
pub fn get(self, Entity(idx): Entity) -> Option<&'a C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx)) => { self.data.get(&idx).expect("missing component").as_ref() }
}
}
/// Fetch a component from given entity. Do not search parent entities.
pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> {
self.data.get(&idx).map_or(None, |x| x.as_ref())
}
}
/// Mutable component access.
pub struct ComponentRefMut<'a, C:'static> {
ecs: &'a mut Ecs,
/// Some(c) indicates the presence of a local component, None indicates
/// that there is no local component and that the component will not be
/// searched from the parent entity either. If the value is not present,
/// the component will be searched from a entity object if one exists.
data: &'a mut HashMap<usize, Option<C>>,
}
impl<'a, C: Clone> ComponentRefMut<'a, C> {
pub fn new(ecs: &'a mut Ecs, data: &'a mut HashMap<usize, Option<C>>) -> ComponentRefMut<'a, C> {
ComponentRefMut {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent. Copy-on-write
/// semantics: A component found on a parent entity will be copied on
/// local entity for mutation.
pub fn get(self, Entity(idx): Entity) -> Option<&'a mut C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx2)) if idx2 == idx => {
self.data.get_mut(&idx2).expect("missing component").as_mut()
}
Some(Entity(idx2)) => {
// Copy-on-write: Make a local copy of inherited component
// when asking for mutable access.
let cow = self.data.get(&idx2)
.expect("parent component lost").as_ref()
.expect("missing component").clone();
self.data.insert(idx, Some(cow));
self.data.get_mut(&idx).expect("missing component").as_mut()
}
}
}
/// Add a component to entity.
pub fn insert(self, Entity(idx): Entity, comp: C) {
self.data.insert(idx, Some(comp));
}
/// Clear a component from an entity. This will make a parent entity's
/// component visible instead, if there is one.
pub fn clear(self, Entity(idx): Entity) {
self.data.remove(&idx);
}
/// Make a component not show up on an entity even if it is present in the
/// parent entity. Hiding will be reset if the component is cleared.
pub fn hide(self, Entity(idx): Entity) {
self.data.insert(idx, None);
}
}
fn find_parent<P>(p: P, ecs: &Ecs, e: Entity) -> Option<Entity>
where P: Fn(Entity) -> bool
{
let mut current = e;
loop {
if p(current) { return Some(current); }
match ecs.parent(current) {
Some(parent) => { current = parent; }
None => { return None; }
}
}
}
| new | identifier_name |
component_ref.rs | use std::collections::HashMap;
use ecs::Ecs;
use entity::Entity;
/// Immutable component access.
pub struct ComponentRef<'a, C:'static> {
ecs: &'a Ecs,
data: &'a HashMap<usize, Option<C>>,
}
impl<'a, C> ComponentRef<'a, C> {
pub fn new(ecs: &'a Ecs, data: &'a HashMap<usize, Option<C>>) -> ComponentRef<'a, C> {
ComponentRef {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent.
pub fn get(self, Entity(idx): Entity) -> Option<&'a C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx)) => { self.data.get(&idx).expect("missing component").as_ref() }
}
}
/// Fetch a component from given entity. Do not search parent entities.
pub fn get_local(self, Entity(idx): Entity) -> Option<&'a C> {
self.data.get(&idx).map_or(None, |x| x.as_ref())
}
}
/// Mutable component access.
pub struct ComponentRefMut<'a, C:'static> {
ecs: &'a mut Ecs,
/// Some(c) indicates the presence of a local component, None indicates
/// that there is no local component and that the component will not be
/// searched from the parent entity either. If the value is not present,
/// the component will be searched from a entity object if one exists.
data: &'a mut HashMap<usize, Option<C>>,
}
impl<'a, C: Clone> ComponentRefMut<'a, C> {
pub fn new(ecs: &'a mut Ecs, data: &'a mut HashMap<usize, Option<C>>) -> ComponentRefMut<'a, C> {
ComponentRefMut {
ecs: ecs,
data: data,
}
}
/// Fetch a component from given entity or its parent. Copy-on-write
/// semantics: A component found on a parent entity will be copied on
/// local entity for mutation.
pub fn get(self, Entity(idx): Entity) -> Option<&'a mut C> {
match find_parent(|Entity(idx)| self.data.contains_key(&idx), self.ecs, Entity(idx)) {
None => { None }
Some(Entity(idx2)) if idx2 == idx => {
self.data.get_mut(&idx2).expect("missing component").as_mut()
}
Some(Entity(idx2)) => { | // Copy-on-write: Make a local copy of inherited component
// when asking for mutable access.
let cow = self.data.get(&idx2)
.expect("parent component lost").as_ref()
.expect("missing component").clone();
self.data.insert(idx, Some(cow));
self.data.get_mut(&idx).expect("missing component").as_mut()
}
}
}
/// Add a component to entity.
pub fn insert(self, Entity(idx): Entity, comp: C) {
self.data.insert(idx, Some(comp));
}
/// Clear a component from an entity. This will make a parent entity's
/// component visible instead, if there is one.
pub fn clear(self, Entity(idx): Entity) {
self.data.remove(&idx);
}
/// Make a component not show up on an entity even if it is present in the
/// parent entity. Hiding will be reset if the component is cleared.
pub fn hide(self, Entity(idx): Entity) {
self.data.insert(idx, None);
}
}
fn find_parent<P>(p: P, ecs: &Ecs, e: Entity) -> Option<Entity>
where P: Fn(Entity) -> bool
{
let mut current = e;
loop {
if p(current) { return Some(current); }
match ecs.parent(current) {
Some(parent) => { current = parent; }
None => { return None; }
}
}
} | random_line_split | |
parser.rs | /// Parsers for the message body of the VSL records
///
/// This should not allocate memory but do primitive conversion when applicable
/// To keep this simple they will be returning tuples.
/// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`.
///
/// Parsing:
/// * numeric types are parsed out - this is done with 0 allocation by mapping bytes as string and convertion
/// * strings
/// * `symbol` - this are comming from Varnish code (strings or numbers/IP) so they will be mapped to &str or
/// parsing will fail; symbols can be trusted to be UTF-8 compatible (ASCII)
/// * `maybe_str` - foreign string: URL, headers, methods, etc. - we cannot trust them to be UTF-8 so they
/// will be provided as bytes to the caller - this is to avoid mem alloc of lossless convertion and let the
/// client do the checking, logging and converstion etc
use std::str::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirection,
};
/// Wrap result in MaybeStr type
macro_rules! maybe_str {
($i:expr, $submac:ident!( $($args:tt)* )) => {
map!($i, $submac!($($args)*), MaybeStr::from_bytes)
};
($i:expr, $f:expr) => {
map!($i, call!($f), MaybeStr::from_bytes)
};
}
//TODO: benchmark symbol unsafe conversion (from_utf8_unchecked)
named!(token<&[u8], &[u8]>, terminated!(is_not!(b" "), alt_complete!(space | eof)));
named!(label<&[u8], &str>, map_res!(terminated!(take_until!(b": "), tag!(b": ")), from_utf8));
named!(symbol<&[u8], &str>, map_res!(token, from_utf8));
named!(header_name<&[u8], &MaybeStr>, maybe_str!(
terminated!(take_until!(b":"), tag!(b":"))));
named!(header_value<&[u8], Option<&MaybeStr> >,
delimited!(opt!(space), opt!(maybe_str!(non_empty)), eof));
macro_rules! named_parsed_symbol {
($name:ident<$parse:ty>) => {
named!($name<&[u8], $parse>, map_res!(symbol, FromStr::from_str));
}
}
named_parsed_symbol!(vsl_ident<VslIdent>);
named_parsed_symbol!(byte_count<ByteCount>);
named_parsed_symbol!(bit_count<BitCount>); | named_parsed_symbol!(duration<Duration>);
named_parsed_symbol!(port<Port>);
named_parsed_symbol!(file_descriptor<FileDescriptor>);
fn map_opt_duration(duration: Duration) -> Option<Duration> {
if duration < 0.0 {
None
} else {
Some(duration)
}
}
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Type (b"sess", "req" or "bereq")
vsl_ident, // Parent vxid
symbol)); // Reason
named!(pub slt_timestamp<&[u8], (&str, TimeStamp, Duration, Duration)>, tuple!(
label, // Event label
time_stamp, // Absolute time of event
duration, // Time since start of work unit
duration)); // Time since last timestamp
named!(pub slt_req_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count, // Total bytes received
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count)); // Total bytes transmitted
named!(pub slt_bereq_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count, // Total bytes transmitted
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count)); // Total bytes received
named!(pub slt_pipe_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Client request headers
byte_count, // Backend request headers
byte_count, // Piped bytes from client
byte_count)); // Piped bytes to client
named!(pub slt_method<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_url<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_protocol<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_status<&[u8], Status>, call!(
status));
named!(pub slt_reason<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_header<&[u8], (&MaybeStr, Option<&MaybeStr>)>, tuple!(
header_name,
header_value));
named!(pub slt_sess_open<&[u8], ((&str, Port), &str, Option<(&str, Port)>, TimeStamp, FileDescriptor)>, tuple!(
// Remote IPv4/6 address
// Remote TCP port
tuple!(symbol, port),
symbol, // Listen socket (-a argument)
// Local IPv4/6 address ('-' if!$log_local_addr)
// Local TCP port ('-' if!$log_local_addr)
chain!(
some: map!(peek!(tuple!(token, token)), |(ip, port)| { ip!= b"-" && port!= b"-" }) ~
addr: cond!(some, tuple!(symbol, port)),
|| { addr }),
time_stamp, // Time stamp
file_descriptor)); // File descriptor number
named!(pub slt_proxy<&[u8], (&str, (&str, Port), (&str, Port))>, tuple!(
symbol, // PROXY protocol version
// Client IPv4/6 address
// Client TCP port
tuple!(symbol, port),
// Server IPv4/6 address ('-' if!$log_local_addr)
// Server TCP port ('-' if!$log_local_addr)
tuple!(symbol, port)
));
named!(pub slt_link<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Child type ("req" or "bereq")
vsl_ident, // Child vxid
symbol)); // Reason
named!(pub slt_sess_close<&[u8], (&str, Duration)>, tuple!(
symbol, // Why the connection closed
duration)); // How long the session was open
named!(pub slt_hit<&[u8], VslIdent>, call!(
vsl_ident)); // Object looked up in cache; Shows the VXID of the object
named!(pub slt_hit_pass<&[u8], VslIdent>, call!(
vsl_ident)); // Hit-for-pass object looked up in cache; Shows the VXID of the hit-for-pass object
named!(pub slt_hit_miss<&[u8], (VslIdent, Duration)>, tuple!(
vsl_ident, // VXID of the object
duration)); // Remaining TTL
named!(pub slt_vcl_call<&[u8], &str>, call!(
symbol)); // VCL method name
named!(pub slt_vcl_return<&[u8], &str>, call!(
symbol)); // VCL method terminating statement
named!(pub slt_vcl_acl<&[u8], (AclResult, &str, Option<&MaybeStr>)>, chain!(
// ACL result (MATCH, NO_MATCH)
mat: terminated!(alt_complete!(tag!(b"NO_MATCH") | tag!(b"MATCH")), space) ~
name: symbol ~ // ACL name
// matched address
addr: opt!(maybe_str!(non_empty)),
|| (match mat {
b"MATCH" => AclResult::Match,
b"NO_MATCH" => AclResult::NoMatch,
_ => unreachable!()
}, name, addr)));
named!(pub slt_storage<&[u8], (&str, &str)>, tuple!(
symbol, // Type ("malloc", "file", "persistent" etc.)
symbol)); // Name of storage backend
named!(pub slt_ttl<&[u8], (&str, Option<Duration>, Option<Duration>, Option<Duration>, TimeStamp,
Option<(TimeStamp, TimeStamp, TimeStamp, Duration)>)>, tuple!(
symbol, // "RFC" or "VCL"
opt_duration, // TTL (-1 for unset)
opt_duration, // Grace (-1 for unset)
opt_duration, // Keep (-1 for unset)
time_stamp, // Reference time for TTL
opt!(tuple!(
time_stamp, // Now - Age header (origin time)
time_stamp, // Date header
time_stamp, // Expires header
duration // Max-Age from Cache-Control header
)))); // The last four fields are only present in "RFC" headers.
named!(pub slt_fetch_body<&[u8], (FetchMode, &str, bool)>, tuple!(
fech_mode, // Body fetch mode
symbol, // Text description of body fetch mode
//'stream' or '-'
terminated!(map!(alt_complete!(tag!(b"stream") | tag!(b"-")),
|s| s == b"stream"
), eof)));
named!(pub slt_gzip<&[u8], Result<(CompressionOperation, CompressionDirection, bool, ByteCount, ByteCount, BitCount, BitCount, BitCount), &MaybeStr> >, alt_complete!(
map!(tuple!(
// 'G': Gzip, 'U': Gunzip, 'u': Gunzip-test\n"
// Note: somehow match won't compile here
terminated!(map!(alt!(tag!(b"G") | tag!(b"U") | tag!(b"u")),
|s| if s == b"G" {
CompressionOperation::Gzip
} else if s == b"U" {
CompressionOperation::Gunzip
} else {
CompressionOperation::GunzipTest
}), space),
// 'F': Fetch, 'D': Deliver
terminated!(map!(alt!(tag!(b"F") | tag!(b"D")),
|s| if s == b"F" {
CompressionDirection::Fetch
} else {
CompressionDirection::Deliver
}), space),
// 'E': ESI, '-': Plain object
terminated!(map!(alt!(tag!(b"E") | tag!(b"-")),
|o| o == b"E"
), space),
byte_count,
byte_count,
bit_count,
bit_count,
bit_count), |t| Ok(t)) |
map!(maybe_str!(non_empty), |m| Err(m))));
named!(pub slt_vcl_log<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_req_start<&[u8], (&str, Port)>, tuple!(
symbol, // Client IP4/6 address
port)); // Client Port number
named!(pub slt_backend_open<&[u8], (FileDescriptor, &str, Option<(&str, Port)>, (&str, Port))>, tuple!(
file_descriptor, // Connection file descriptor
symbol, // Backend display name
// Note: this can be <none> <none> if backend socket is not connected
alt!(map!(terminated!(tag!(b"<none> <none>"), space), |_| None) | map!(tuple!(symbol, port), |t| Some(t))), // Remote IPv4/6 address Remote TCP port
tuple!(symbol, port))); // Local IPv4/6 address Local TCP port | named_parsed_symbol!(fech_mode<FetchMode>);
named_parsed_symbol!(status<Status>);
named_parsed_symbol!(time_stamp<TimeStamp>); | random_line_split |
parser.rs | /// Parsers for the message body of the VSL records
///
/// This should not allocate memory but do primitive conversion when applicable
/// To keep this simple they will be returning tuples.
/// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`.
///
/// Parsing:
/// * numeric types are parsed out - this is done with 0 allocation by mapping bytes as string and convertion
/// * strings
/// * `symbol` - this are comming from Varnish code (strings or numbers/IP) so they will be mapped to &str or
/// parsing will fail; symbols can be trusted to be UTF-8 compatible (ASCII)
/// * `maybe_str` - foreign string: URL, headers, methods, etc. - we cannot trust them to be UTF-8 so they
/// will be provided as bytes to the caller - this is to avoid mem alloc of lossless convertion and let the
/// client do the checking, logging and converstion etc
use std::str::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirection,
};
/// Wrap result in MaybeStr type
macro_rules! maybe_str {
($i:expr, $submac:ident!( $($args:tt)* )) => {
map!($i, $submac!($($args)*), MaybeStr::from_bytes)
};
($i:expr, $f:expr) => {
map!($i, call!($f), MaybeStr::from_bytes)
};
}
//TODO: benchmark symbol unsafe conversion (from_utf8_unchecked)
named!(token<&[u8], &[u8]>, terminated!(is_not!(b" "), alt_complete!(space | eof)));
named!(label<&[u8], &str>, map_res!(terminated!(take_until!(b": "), tag!(b": ")), from_utf8));
named!(symbol<&[u8], &str>, map_res!(token, from_utf8));
named!(header_name<&[u8], &MaybeStr>, maybe_str!(
terminated!(take_until!(b":"), tag!(b":"))));
named!(header_value<&[u8], Option<&MaybeStr> >,
delimited!(opt!(space), opt!(maybe_str!(non_empty)), eof));
macro_rules! named_parsed_symbol {
($name:ident<$parse:ty>) => {
named!($name<&[u8], $parse>, map_res!(symbol, FromStr::from_str));
}
}
named_parsed_symbol!(vsl_ident<VslIdent>);
named_parsed_symbol!(byte_count<ByteCount>);
named_parsed_symbol!(bit_count<BitCount>);
named_parsed_symbol!(fech_mode<FetchMode>);
named_parsed_symbol!(status<Status>);
named_parsed_symbol!(time_stamp<TimeStamp>);
named_parsed_symbol!(duration<Duration>);
named_parsed_symbol!(port<Port>);
named_parsed_symbol!(file_descriptor<FileDescriptor>);
fn map_opt_duration(duration: Duration) -> Option<Duration> {
if duration < 0.0 {
None
} else |
}
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Type (b"sess", "req" or "bereq")
vsl_ident, // Parent vxid
symbol)); // Reason
named!(pub slt_timestamp<&[u8], (&str, TimeStamp, Duration, Duration)>, tuple!(
label, // Event label
time_stamp, // Absolute time of event
duration, // Time since start of work unit
duration)); // Time since last timestamp
named!(pub slt_req_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count, // Total bytes received
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count)); // Total bytes transmitted
named!(pub slt_bereq_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count, // Total bytes transmitted
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count)); // Total bytes received
named!(pub slt_pipe_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Client request headers
byte_count, // Backend request headers
byte_count, // Piped bytes from client
byte_count)); // Piped bytes to client
named!(pub slt_method<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_url<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_protocol<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_status<&[u8], Status>, call!(
status));
named!(pub slt_reason<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_header<&[u8], (&MaybeStr, Option<&MaybeStr>)>, tuple!(
header_name,
header_value));
named!(pub slt_sess_open<&[u8], ((&str, Port), &str, Option<(&str, Port)>, TimeStamp, FileDescriptor)>, tuple!(
// Remote IPv4/6 address
// Remote TCP port
tuple!(symbol, port),
symbol, // Listen socket (-a argument)
// Local IPv4/6 address ('-' if!$log_local_addr)
// Local TCP port ('-' if!$log_local_addr)
chain!(
some: map!(peek!(tuple!(token, token)), |(ip, port)| { ip!= b"-" && port!= b"-" }) ~
addr: cond!(some, tuple!(symbol, port)),
|| { addr }),
time_stamp, // Time stamp
file_descriptor)); // File descriptor number
named!(pub slt_proxy<&[u8], (&str, (&str, Port), (&str, Port))>, tuple!(
symbol, // PROXY protocol version
// Client IPv4/6 address
// Client TCP port
tuple!(symbol, port),
// Server IPv4/6 address ('-' if!$log_local_addr)
// Server TCP port ('-' if!$log_local_addr)
tuple!(symbol, port)
));
named!(pub slt_link<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Child type ("req" or "bereq")
vsl_ident, // Child vxid
symbol)); // Reason
named!(pub slt_sess_close<&[u8], (&str, Duration)>, tuple!(
symbol, // Why the connection closed
duration)); // How long the session was open
named!(pub slt_hit<&[u8], VslIdent>, call!(
vsl_ident)); // Object looked up in cache; Shows the VXID of the object
named!(pub slt_hit_pass<&[u8], VslIdent>, call!(
vsl_ident)); // Hit-for-pass object looked up in cache; Shows the VXID of the hit-for-pass object
named!(pub slt_hit_miss<&[u8], (VslIdent, Duration)>, tuple!(
vsl_ident, // VXID of the object
duration)); // Remaining TTL
named!(pub slt_vcl_call<&[u8], &str>, call!(
symbol)); // VCL method name
named!(pub slt_vcl_return<&[u8], &str>, call!(
symbol)); // VCL method terminating statement
named!(pub slt_vcl_acl<&[u8], (AclResult, &str, Option<&MaybeStr>)>, chain!(
// ACL result (MATCH, NO_MATCH)
mat: terminated!(alt_complete!(tag!(b"NO_MATCH") | tag!(b"MATCH")), space) ~
name: symbol ~ // ACL name
// matched address
addr: opt!(maybe_str!(non_empty)),
|| (match mat {
b"MATCH" => AclResult::Match,
b"NO_MATCH" => AclResult::NoMatch,
_ => unreachable!()
}, name, addr)));
named!(pub slt_storage<&[u8], (&str, &str)>, tuple!(
symbol, // Type ("malloc", "file", "persistent" etc.)
symbol)); // Name of storage backend
named!(pub slt_ttl<&[u8], (&str, Option<Duration>, Option<Duration>, Option<Duration>, TimeStamp,
Option<(TimeStamp, TimeStamp, TimeStamp, Duration)>)>, tuple!(
symbol, // "RFC" or "VCL"
opt_duration, // TTL (-1 for unset)
opt_duration, // Grace (-1 for unset)
opt_duration, // Keep (-1 for unset)
time_stamp, // Reference time for TTL
opt!(tuple!(
time_stamp, // Now - Age header (origin time)
time_stamp, // Date header
time_stamp, // Expires header
duration // Max-Age from Cache-Control header
)))); // The last four fields are only present in "RFC" headers.
named!(pub slt_fetch_body<&[u8], (FetchMode, &str, bool)>, tuple!(
fech_mode, // Body fetch mode
symbol, // Text description of body fetch mode
//'stream' or '-'
terminated!(map!(alt_complete!(tag!(b"stream") | tag!(b"-")),
|s| s == b"stream"
), eof)));
named!(pub slt_gzip<&[u8], Result<(CompressionOperation, CompressionDirection, bool, ByteCount, ByteCount, BitCount, BitCount, BitCount), &MaybeStr> >, alt_complete!(
map!(tuple!(
// 'G': Gzip, 'U': Gunzip, 'u': Gunzip-test\n"
// Note: somehow match won't compile here
terminated!(map!(alt!(tag!(b"G") | tag!(b"U") | tag!(b"u")),
|s| if s == b"G" {
CompressionOperation::Gzip
} else if s == b"U" {
CompressionOperation::Gunzip
} else {
CompressionOperation::GunzipTest
}), space),
// 'F': Fetch, 'D': Deliver
terminated!(map!(alt!(tag!(b"F") | tag!(b"D")),
|s| if s == b"F" {
CompressionDirection::Fetch
} else {
CompressionDirection::Deliver
}), space),
// 'E': ESI, '-': Plain object
terminated!(map!(alt!(tag!(b"E") | tag!(b"-")),
|o| o == b"E"
), space),
byte_count,
byte_count,
bit_count,
bit_count,
bit_count), |t| Ok(t)) |
map!(maybe_str!(non_empty), |m| Err(m))));
named!(pub slt_vcl_log<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_req_start<&[u8], (&str, Port)>, tuple!(
symbol, // Client IP4/6 address
port)); // Client Port number
named!(pub slt_backend_open<&[u8], (FileDescriptor, &str, Option<(&str, Port)>, (&str, Port))>, tuple!(
file_descriptor, // Connection file descriptor
symbol, // Backend display name
// Note: this can be <none> <none> if backend socket is not connected
alt!(map!(terminated!(tag!(b"<none> <none>"), space), |_| None) | map!(tuple!(symbol, port), |t| Some(t))), // Remote IPv4/6 address Remote TCP port
tuple!(symbol, port))); // Local IPv4/6 address Local TCP port
| {
Some(duration)
} | conditional_block |
parser.rs | /// Parsers for the message body of the VSL records
///
/// This should not allocate memory but do primitive conversion when applicable
/// To keep this simple they will be returning tuples.
/// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`.
///
/// Parsing:
/// * numeric types are parsed out - this is done with 0 allocation by mapping bytes as string and convertion
/// * strings
/// * `symbol` - this are comming from Varnish code (strings or numbers/IP) so they will be mapped to &str or
/// parsing will fail; symbols can be trusted to be UTF-8 compatible (ASCII)
/// * `maybe_str` - foreign string: URL, headers, methods, etc. - we cannot trust them to be UTF-8 so they
/// will be provided as bytes to the caller - this is to avoid mem alloc of lossless convertion and let the
/// client do the checking, logging and converstion etc
use std::str::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirection,
};
/// Wrap result in MaybeStr type
macro_rules! maybe_str {
($i:expr, $submac:ident!( $($args:tt)* )) => {
map!($i, $submac!($($args)*), MaybeStr::from_bytes)
};
($i:expr, $f:expr) => {
map!($i, call!($f), MaybeStr::from_bytes)
};
}
//TODO: benchmark symbol unsafe conversion (from_utf8_unchecked)
named!(token<&[u8], &[u8]>, terminated!(is_not!(b" "), alt_complete!(space | eof)));
named!(label<&[u8], &str>, map_res!(terminated!(take_until!(b": "), tag!(b": ")), from_utf8));
named!(symbol<&[u8], &str>, map_res!(token, from_utf8));
named!(header_name<&[u8], &MaybeStr>, maybe_str!(
terminated!(take_until!(b":"), tag!(b":"))));
named!(header_value<&[u8], Option<&MaybeStr> >,
delimited!(opt!(space), opt!(maybe_str!(non_empty)), eof));
macro_rules! named_parsed_symbol {
($name:ident<$parse:ty>) => {
named!($name<&[u8], $parse>, map_res!(symbol, FromStr::from_str));
}
}
named_parsed_symbol!(vsl_ident<VslIdent>);
named_parsed_symbol!(byte_count<ByteCount>);
named_parsed_symbol!(bit_count<BitCount>);
named_parsed_symbol!(fech_mode<FetchMode>);
named_parsed_symbol!(status<Status>);
named_parsed_symbol!(time_stamp<TimeStamp>);
named_parsed_symbol!(duration<Duration>);
named_parsed_symbol!(port<Port>);
named_parsed_symbol!(file_descriptor<FileDescriptor>);
fn | (duration: Duration) -> Option<Duration> {
if duration < 0.0 {
None
} else {
Some(duration)
}
}
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Type (b"sess", "req" or "bereq")
vsl_ident, // Parent vxid
symbol)); // Reason
named!(pub slt_timestamp<&[u8], (&str, TimeStamp, Duration, Duration)>, tuple!(
label, // Event label
time_stamp, // Absolute time of event
duration, // Time since start of work unit
duration)); // Time since last timestamp
named!(pub slt_req_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count, // Total bytes received
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count)); // Total bytes transmitted
named!(pub slt_bereq_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count, // Total bytes transmitted
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count)); // Total bytes received
named!(pub slt_pipe_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Client request headers
byte_count, // Backend request headers
byte_count, // Piped bytes from client
byte_count)); // Piped bytes to client
named!(pub slt_method<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_url<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_protocol<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_status<&[u8], Status>, call!(
status));
named!(pub slt_reason<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_header<&[u8], (&MaybeStr, Option<&MaybeStr>)>, tuple!(
header_name,
header_value));
named!(pub slt_sess_open<&[u8], ((&str, Port), &str, Option<(&str, Port)>, TimeStamp, FileDescriptor)>, tuple!(
// Remote IPv4/6 address
// Remote TCP port
tuple!(symbol, port),
symbol, // Listen socket (-a argument)
// Local IPv4/6 address ('-' if!$log_local_addr)
// Local TCP port ('-' if!$log_local_addr)
chain!(
some: map!(peek!(tuple!(token, token)), |(ip, port)| { ip!= b"-" && port!= b"-" }) ~
addr: cond!(some, tuple!(symbol, port)),
|| { addr }),
time_stamp, // Time stamp
file_descriptor)); // File descriptor number
named!(pub slt_proxy<&[u8], (&str, (&str, Port), (&str, Port))>, tuple!(
symbol, // PROXY protocol version
// Client IPv4/6 address
// Client TCP port
tuple!(symbol, port),
// Server IPv4/6 address ('-' if!$log_local_addr)
// Server TCP port ('-' if!$log_local_addr)
tuple!(symbol, port)
));
named!(pub slt_link<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Child type ("req" or "bereq")
vsl_ident, // Child vxid
symbol)); // Reason
named!(pub slt_sess_close<&[u8], (&str, Duration)>, tuple!(
symbol, // Why the connection closed
duration)); // How long the session was open
named!(pub slt_hit<&[u8], VslIdent>, call!(
vsl_ident)); // Object looked up in cache; Shows the VXID of the object
named!(pub slt_hit_pass<&[u8], VslIdent>, call!(
vsl_ident)); // Hit-for-pass object looked up in cache; Shows the VXID of the hit-for-pass object
named!(pub slt_hit_miss<&[u8], (VslIdent, Duration)>, tuple!(
vsl_ident, // VXID of the object
duration)); // Remaining TTL
named!(pub slt_vcl_call<&[u8], &str>, call!(
symbol)); // VCL method name
named!(pub slt_vcl_return<&[u8], &str>, call!(
symbol)); // VCL method terminating statement
named!(pub slt_vcl_acl<&[u8], (AclResult, &str, Option<&MaybeStr>)>, chain!(
// ACL result (MATCH, NO_MATCH)
mat: terminated!(alt_complete!(tag!(b"NO_MATCH") | tag!(b"MATCH")), space) ~
name: symbol ~ // ACL name
// matched address
addr: opt!(maybe_str!(non_empty)),
|| (match mat {
b"MATCH" => AclResult::Match,
b"NO_MATCH" => AclResult::NoMatch,
_ => unreachable!()
}, name, addr)));
named!(pub slt_storage<&[u8], (&str, &str)>, tuple!(
symbol, // Type ("malloc", "file", "persistent" etc.)
symbol)); // Name of storage backend
named!(pub slt_ttl<&[u8], (&str, Option<Duration>, Option<Duration>, Option<Duration>, TimeStamp,
Option<(TimeStamp, TimeStamp, TimeStamp, Duration)>)>, tuple!(
symbol, // "RFC" or "VCL"
opt_duration, // TTL (-1 for unset)
opt_duration, // Grace (-1 for unset)
opt_duration, // Keep (-1 for unset)
time_stamp, // Reference time for TTL
opt!(tuple!(
time_stamp, // Now - Age header (origin time)
time_stamp, // Date header
time_stamp, // Expires header
duration // Max-Age from Cache-Control header
)))); // The last four fields are only present in "RFC" headers.
named!(pub slt_fetch_body<&[u8], (FetchMode, &str, bool)>, tuple!(
fech_mode, // Body fetch mode
symbol, // Text description of body fetch mode
//'stream' or '-'
terminated!(map!(alt_complete!(tag!(b"stream") | tag!(b"-")),
|s| s == b"stream"
), eof)));
named!(pub slt_gzip<&[u8], Result<(CompressionOperation, CompressionDirection, bool, ByteCount, ByteCount, BitCount, BitCount, BitCount), &MaybeStr> >, alt_complete!(
map!(tuple!(
// 'G': Gzip, 'U': Gunzip, 'u': Gunzip-test\n"
// Note: somehow match won't compile here
terminated!(map!(alt!(tag!(b"G") | tag!(b"U") | tag!(b"u")),
|s| if s == b"G" {
CompressionOperation::Gzip
} else if s == b"U" {
CompressionOperation::Gunzip
} else {
CompressionOperation::GunzipTest
}), space),
// 'F': Fetch, 'D': Deliver
terminated!(map!(alt!(tag!(b"F") | tag!(b"D")),
|s| if s == b"F" {
CompressionDirection::Fetch
} else {
CompressionDirection::Deliver
}), space),
// 'E': ESI, '-': Plain object
terminated!(map!(alt!(tag!(b"E") | tag!(b"-")),
|o| o == b"E"
), space),
byte_count,
byte_count,
bit_count,
bit_count,
bit_count), |t| Ok(t)) |
map!(maybe_str!(non_empty), |m| Err(m))));
named!(pub slt_vcl_log<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_req_start<&[u8], (&str, Port)>, tuple!(
symbol, // Client IP4/6 address
port)); // Client Port number
named!(pub slt_backend_open<&[u8], (FileDescriptor, &str, Option<(&str, Port)>, (&str, Port))>, tuple!(
file_descriptor, // Connection file descriptor
symbol, // Backend display name
// Note: this can be <none> <none> if backend socket is not connected
alt!(map!(terminated!(tag!(b"<none> <none>"), space), |_| None) | map!(tuple!(symbol, port), |t| Some(t))), // Remote IPv4/6 address Remote TCP port
tuple!(symbol, port))); // Local IPv4/6 address Local TCP port
| map_opt_duration | identifier_name |
parser.rs | /// Parsers for the message body of the VSL records
///
/// This should not allocate memory but do primitive conversion when applicable
/// To keep this simple they will be returning tuples.
/// Format and comments are form `include/tbl/vsl_tags.h` and `include/tbl/vsl_tags_http.h`.
///
/// Parsing:
/// * numeric types are parsed out - this is done with 0 allocation by mapping bytes as string and convertion
/// * strings
/// * `symbol` - this are comming from Varnish code (strings or numbers/IP) so they will be mapped to &str or
/// parsing will fail; symbols can be trusted to be UTF-8 compatible (ASCII)
/// * `maybe_str` - foreign string: URL, headers, methods, etc. - we cannot trust them to be UTF-8 so they
/// will be provided as bytes to the caller - this is to avoid mem alloc of lossless convertion and let the
/// client do the checking, logging and converstion etc
use std::str::{FromStr, from_utf8};
use nom::{non_empty, space, eof};
use crate::vsl::record::VslIdent;
use crate::maybe_string::MaybeStr;
use super::{
TimeStamp,
Duration,
ByteCount,
BitCount,
FetchMode,
Status,
Port,
FileDescriptor,
AclResult,
CompressionOperation,
CompressionDirection,
};
/// Wrap result in MaybeStr type
macro_rules! maybe_str {
($i:expr, $submac:ident!( $($args:tt)* )) => {
map!($i, $submac!($($args)*), MaybeStr::from_bytes)
};
($i:expr, $f:expr) => {
map!($i, call!($f), MaybeStr::from_bytes)
};
}
//TODO: benchmark symbol unsafe conversion (from_utf8_unchecked)
named!(token<&[u8], &[u8]>, terminated!(is_not!(b" "), alt_complete!(space | eof)));
named!(label<&[u8], &str>, map_res!(terminated!(take_until!(b": "), tag!(b": ")), from_utf8));
named!(symbol<&[u8], &str>, map_res!(token, from_utf8));
named!(header_name<&[u8], &MaybeStr>, maybe_str!(
terminated!(take_until!(b":"), tag!(b":"))));
named!(header_value<&[u8], Option<&MaybeStr> >,
delimited!(opt!(space), opt!(maybe_str!(non_empty)), eof));
macro_rules! named_parsed_symbol {
($name:ident<$parse:ty>) => {
named!($name<&[u8], $parse>, map_res!(symbol, FromStr::from_str));
}
}
named_parsed_symbol!(vsl_ident<VslIdent>);
named_parsed_symbol!(byte_count<ByteCount>);
named_parsed_symbol!(bit_count<BitCount>);
named_parsed_symbol!(fech_mode<FetchMode>);
named_parsed_symbol!(status<Status>);
named_parsed_symbol!(time_stamp<TimeStamp>);
named_parsed_symbol!(duration<Duration>);
named_parsed_symbol!(port<Port>);
named_parsed_symbol!(file_descriptor<FileDescriptor>);
fn map_opt_duration(duration: Duration) -> Option<Duration> |
named!(opt_duration<&[u8], Option<Duration> >, map!(duration, map_opt_duration));
// VSL record message parsers by tag
named!(pub slt_begin<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Type (b"sess", "req" or "bereq")
vsl_ident, // Parent vxid
symbol)); // Reason
named!(pub slt_timestamp<&[u8], (&str, TimeStamp, Duration, Duration)>, tuple!(
label, // Event label
time_stamp, // Absolute time of event
duration, // Time since start of work unit
duration)); // Time since last timestamp
named!(pub slt_req_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count, // Total bytes received
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count)); // Total bytes transmitted
named!(pub slt_bereq_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Header bytes transmitted
byte_count, // Body bytes transmitted
byte_count, // Total bytes transmitted
byte_count, // Header bytes received
byte_count, // Body bytes received
byte_count)); // Total bytes received
named!(pub slt_pipe_acct<&[u8], (ByteCount, ByteCount, ByteCount, ByteCount) >, tuple!(
byte_count, // Client request headers
byte_count, // Backend request headers
byte_count, // Piped bytes from client
byte_count)); // Piped bytes to client
named!(pub slt_method<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_url<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_protocol<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_status<&[u8], Status>, call!(
status));
named!(pub slt_reason<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_header<&[u8], (&MaybeStr, Option<&MaybeStr>)>, tuple!(
header_name,
header_value));
named!(pub slt_sess_open<&[u8], ((&str, Port), &str, Option<(&str, Port)>, TimeStamp, FileDescriptor)>, tuple!(
// Remote IPv4/6 address
// Remote TCP port
tuple!(symbol, port),
symbol, // Listen socket (-a argument)
// Local IPv4/6 address ('-' if!$log_local_addr)
// Local TCP port ('-' if!$log_local_addr)
chain!(
some: map!(peek!(tuple!(token, token)), |(ip, port)| { ip!= b"-" && port!= b"-" }) ~
addr: cond!(some, tuple!(symbol, port)),
|| { addr }),
time_stamp, // Time stamp
file_descriptor)); // File descriptor number
named!(pub slt_proxy<&[u8], (&str, (&str, Port), (&str, Port))>, tuple!(
symbol, // PROXY protocol version
// Client IPv4/6 address
// Client TCP port
tuple!(symbol, port),
// Server IPv4/6 address ('-' if!$log_local_addr)
// Server TCP port ('-' if!$log_local_addr)
tuple!(symbol, port)
));
named!(pub slt_link<&[u8], (&str, VslIdent, &str)>, tuple!(
symbol, // Child type ("req" or "bereq")
vsl_ident, // Child vxid
symbol)); // Reason
named!(pub slt_sess_close<&[u8], (&str, Duration)>, tuple!(
symbol, // Why the connection closed
duration)); // How long the session was open
named!(pub slt_hit<&[u8], VslIdent>, call!(
vsl_ident)); // Object looked up in cache; Shows the VXID of the object
named!(pub slt_hit_pass<&[u8], VslIdent>, call!(
vsl_ident)); // Hit-for-pass object looked up in cache; Shows the VXID of the hit-for-pass object
named!(pub slt_hit_miss<&[u8], (VslIdent, Duration)>, tuple!(
vsl_ident, // VXID of the object
duration)); // Remaining TTL
named!(pub slt_vcl_call<&[u8], &str>, call!(
symbol)); // VCL method name
named!(pub slt_vcl_return<&[u8], &str>, call!(
symbol)); // VCL method terminating statement
named!(pub slt_vcl_acl<&[u8], (AclResult, &str, Option<&MaybeStr>)>, chain!(
// ACL result (MATCH, NO_MATCH)
mat: terminated!(alt_complete!(tag!(b"NO_MATCH") | tag!(b"MATCH")), space) ~
name: symbol ~ // ACL name
// matched address
addr: opt!(maybe_str!(non_empty)),
|| (match mat {
b"MATCH" => AclResult::Match,
b"NO_MATCH" => AclResult::NoMatch,
_ => unreachable!()
}, name, addr)));
named!(pub slt_storage<&[u8], (&str, &str)>, tuple!(
symbol, // Type ("malloc", "file", "persistent" etc.)
symbol)); // Name of storage backend
named!(pub slt_ttl<&[u8], (&str, Option<Duration>, Option<Duration>, Option<Duration>, TimeStamp,
Option<(TimeStamp, TimeStamp, TimeStamp, Duration)>)>, tuple!(
symbol, // "RFC" or "VCL"
opt_duration, // TTL (-1 for unset)
opt_duration, // Grace (-1 for unset)
opt_duration, // Keep (-1 for unset)
time_stamp, // Reference time for TTL
opt!(tuple!(
time_stamp, // Now - Age header (origin time)
time_stamp, // Date header
time_stamp, // Expires header
duration // Max-Age from Cache-Control header
)))); // The last four fields are only present in "RFC" headers.
named!(pub slt_fetch_body<&[u8], (FetchMode, &str, bool)>, tuple!(
fech_mode, // Body fetch mode
symbol, // Text description of body fetch mode
//'stream' or '-'
terminated!(map!(alt_complete!(tag!(b"stream") | tag!(b"-")),
|s| s == b"stream"
), eof)));
named!(pub slt_gzip<&[u8], Result<(CompressionOperation, CompressionDirection, bool, ByteCount, ByteCount, BitCount, BitCount, BitCount), &MaybeStr> >, alt_complete!(
map!(tuple!(
// 'G': Gzip, 'U': Gunzip, 'u': Gunzip-test\n"
// Note: somehow match won't compile here
terminated!(map!(alt!(tag!(b"G") | tag!(b"U") | tag!(b"u")),
|s| if s == b"G" {
CompressionOperation::Gzip
} else if s == b"U" {
CompressionOperation::Gunzip
} else {
CompressionOperation::GunzipTest
}), space),
// 'F': Fetch, 'D': Deliver
terminated!(map!(alt!(tag!(b"F") | tag!(b"D")),
|s| if s == b"F" {
CompressionDirection::Fetch
} else {
CompressionDirection::Deliver
}), space),
// 'E': ESI, '-': Plain object
terminated!(map!(alt!(tag!(b"E") | tag!(b"-")),
|o| o == b"E"
), space),
byte_count,
byte_count,
bit_count,
bit_count,
bit_count), |t| Ok(t)) |
map!(maybe_str!(non_empty), |m| Err(m))));
named!(pub slt_vcl_log<&[u8], &MaybeStr>, maybe_str!(
non_empty));
named!(pub slt_req_start<&[u8], (&str, Port)>, tuple!(
symbol, // Client IP4/6 address
port)); // Client Port number
named!(pub slt_backend_open<&[u8], (FileDescriptor, &str, Option<(&str, Port)>, (&str, Port))>, tuple!(
file_descriptor, // Connection file descriptor
symbol, // Backend display name
// Note: this can be <none> <none> if backend socket is not connected
alt!(map!(terminated!(tag!(b"<none> <none>"), space), |_| None) | map!(tuple!(symbol, port), |t| Some(t))), // Remote IPv4/6 address Remote TCP port
tuple!(symbol, port))); // Local IPv4/6 address Local TCP port
| {
if duration < 0.0 {
None
} else {
Some(duration)
}
} | identifier_body |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() | buffer[offset + 2] = 0;
}
}
}).unwrap();
renderer.clear();
renderer.copy(&texture, None, Some(Rect::new_unwrap(100, 100, 256, 256)));
renderer.copy_ex(&texture, None, Some(Rect::new_unwrap(450, 100, 256, 256)), 30.0, None, (false, false));
renderer.present();
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape),.. } => {
break 'running
},
_ => {}
}
}
// The rest of the game loop goes here...
}
}
| {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap();
let mut texture = renderer.create_texture_streaming(PixelFormatEnum::RGB24, (256, 256)).unwrap();
// Create a red-green gradient
texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
for y in (0..256) {
for x in (0..256) {
let offset = y*pitch + x*3;
buffer[offset + 0] = x as u8;
buffer[offset + 1] = y as u8; | identifier_body |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap();
let mut texture = renderer.create_texture_streaming(PixelFormatEnum::RGB24, (256, 256)).unwrap();
// Create a red-green gradient
texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
for y in (0..256) {
for x in (0..256) {
let offset = y*pitch + x*3;
buffer[offset + 0] = x as u8;
buffer[offset + 1] = y as u8;
buffer[offset + 2] = 0;
}
}
}).unwrap();
renderer.clear();
renderer.copy(&texture, None, Some(Rect::new_unwrap(100, 100, 256, 256)));
renderer.copy_ex(&texture, None, Some(Rect::new_unwrap(450, 100, 256, 256)), 30.0, None, (false, false));
renderer.present();
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape),.. } => {
break 'running
},
_ => {}
}
} | } | // The rest of the game loop goes here...
} | random_line_split |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap();
let mut texture = renderer.create_texture_streaming(PixelFormatEnum::RGB24, (256, 256)).unwrap();
// Create a red-green gradient
texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
for y in (0..256) {
for x in (0..256) {
let offset = y*pitch + x*3;
buffer[offset + 0] = x as u8;
buffer[offset + 1] = y as u8;
buffer[offset + 2] = 0;
}
}
}).unwrap();
renderer.clear();
renderer.copy(&texture, None, Some(Rect::new_unwrap(100, 100, 256, 256)));
renderer.copy_ex(&texture, None, Some(Rect::new_unwrap(450, 100, 256, 256)), 30.0, None, (false, false));
renderer.present();
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape),.. } => {
break 'running
},
_ => |
}
}
// The rest of the game loop goes here...
}
}
| {} | conditional_block |
renderer-texture.rs | extern crate sdl2;
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
pub fn | () {
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.renderer().build().unwrap();
let mut texture = renderer.create_texture_streaming(PixelFormatEnum::RGB24, (256, 256)).unwrap();
// Create a red-green gradient
texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
for y in (0..256) {
for x in (0..256) {
let offset = y*pitch + x*3;
buffer[offset + 0] = x as u8;
buffer[offset + 1] = y as u8;
buffer[offset + 2] = 0;
}
}
}).unwrap();
renderer.clear();
renderer.copy(&texture, None, Some(Rect::new_unwrap(100, 100, 256, 256)));
renderer.copy_ex(&texture, None, Some(Rect::new_unwrap(450, 100, 256, 256)), 30.0, None, (false, false));
renderer.present();
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
for event in event_pump.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape),.. } => {
break 'running
},
_ => {}
}
}
// The rest of the game loop goes here...
}
}
| main | identifier_name |
picture.rs | use chrono::naive::NaiveDateTime;
use exif::{Exif, In, Tag};
use serde::{Deserialize, Serialize};
use validator::Validate;
use anyhow::{Error, Result};
use image::GenericImageView;
use image::{imageops, DynamicImage};
use crate::schema::pictures;
use crate::utils::image_base_path;
#[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)]
pub struct Picture {
pub id: i32,
pub author_id: i32,
pub in_reply_to: Option<String>,
pub webmentions_count: i32,
pub image_file_name: String,
pub image_content_type: String,
pub image_file_size: i32,
pub image_updated_at: NaiveDateTime,
pub inserted_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub title: String,
pub posse: bool,
pub show_in_index: bool,
pub content: String,
pub lang: String,
pub alt: Option<String>,
}
#[derive(Deserialize, Serialize, Debug, Insertable, Clone, Validate, Default)]
#[table_name = "pictures"]
pub struct NewPicture {
pub author_id: Option<i32>,
#[validate(length(min = 5))]
pub title: String,
#[validate(length(min = 5))]
pub alt: Option<String>,
#[validate(url)]
pub in_reply_to: Option<String>,
#[validate(length(min = 2, max = 2))]
pub lang: String,
#[serde(default)]
pub posse: bool,
#[serde(default)]
pub show_in_index: bool,
#[validate(required, length(min = 5))]
pub content: Option<String>,
pub image_file_name: Option<String>,
pub image_content_type: Option<String>,
pub image_file_size: Option<i32>,
pub image_updated_at: Option<NaiveDateTime>,
pub inserted_at: Option<NaiveDateTime>,
pub updated_at: Option<NaiveDateTime>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct NewJsonPicture {
#[serde(flatten)]
pub new_picture: NewPicture,
pub picture: Option<String>,
}
const THUMB_ASPEC_RATIO: f32 = 1.0;
fn read_exif(path: &str) -> Result<Exif, Error> {
let file = std::fs::File::open(path)?;
let mut bufreader = std::io::BufReader::new(&file);
let exifreader = exif::Reader::new();
Ok(exifreader
.read_from_container(&mut bufreader)
.map_err(|_| anyhow!("error reading file"))?)
}
fn correct_orientation(mut img: DynamicImage, orientation: u32) -> DynamicImage {
if orientation <= 1 || orientation > 8 {
return img;
}
if orientation >= 5 {
img = img.rotate90().fliph();
}
if orientation == 3 || orientation == 4 || orientation == 7 || orientation == 8 {
img = img.rotate180();
}
if orientation % 2 == 0 {
img = img.fliph();
}
img
}
pub fn generate_pictures(picture: &Picture) -> Result<()> {
let path = format!(
"{}/{}/original/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let exif = read_exif(&path)?;
let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) {
Some(orientation) => match orientation.value.get_uint(0) {
Some(v @ 1..=8) => v,
_ => 0,
},
None => 0,
};
let mut img = image::open(path)?;
img = correct_orientation(img, orientation);
let path = format!("{}/{}/large/{}", image_base_path(), picture.id, picture.image_file_name);
let new_img = img.resize(800, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
let path = format!(
"{}/{}/thumbnail/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let (width, height) = img.dimensions();
let aspect_ratio = width as f32 / height as f32;
let img = if aspect_ratio!= THUMB_ASPEC_RATIO {
let mid_x = width / 2;
let mid_y = height / 2;
if width > height {
img.crop(mid_x - (height / 2), mid_y - (height / 2), height, height) | } else {
img.crop(mid_x - (width / 2), mid_y - (width / 2), width, width)
}
} else {
img
};
let new_img = img.resize_exact(600, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
Ok(())
} | random_line_split | |
picture.rs | use chrono::naive::NaiveDateTime;
use exif::{Exif, In, Tag};
use serde::{Deserialize, Serialize};
use validator::Validate;
use anyhow::{Error, Result};
use image::GenericImageView;
use image::{imageops, DynamicImage};
use crate::schema::pictures;
use crate::utils::image_base_path;
#[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)]
pub struct Picture {
pub id: i32,
pub author_id: i32,
pub in_reply_to: Option<String>,
pub webmentions_count: i32,
pub image_file_name: String,
pub image_content_type: String,
pub image_file_size: i32,
pub image_updated_at: NaiveDateTime,
pub inserted_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub title: String,
pub posse: bool,
pub show_in_index: bool,
pub content: String,
pub lang: String,
pub alt: Option<String>,
}
#[derive(Deserialize, Serialize, Debug, Insertable, Clone, Validate, Default)]
#[table_name = "pictures"]
pub struct NewPicture {
pub author_id: Option<i32>,
#[validate(length(min = 5))]
pub title: String,
#[validate(length(min = 5))]
pub alt: Option<String>,
#[validate(url)]
pub in_reply_to: Option<String>,
#[validate(length(min = 2, max = 2))]
pub lang: String,
#[serde(default)]
pub posse: bool,
#[serde(default)]
pub show_in_index: bool,
#[validate(required, length(min = 5))]
pub content: Option<String>,
pub image_file_name: Option<String>,
pub image_content_type: Option<String>,
pub image_file_size: Option<i32>,
pub image_updated_at: Option<NaiveDateTime>,
pub inserted_at: Option<NaiveDateTime>,
pub updated_at: Option<NaiveDateTime>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct NewJsonPicture {
#[serde(flatten)]
pub new_picture: NewPicture,
pub picture: Option<String>,
}
const THUMB_ASPEC_RATIO: f32 = 1.0;
fn read_exif(path: &str) -> Result<Exif, Error> {
let file = std::fs::File::open(path)?;
let mut bufreader = std::io::BufReader::new(&file);
let exifreader = exif::Reader::new();
Ok(exifreader
.read_from_container(&mut bufreader)
.map_err(|_| anyhow!("error reading file"))?)
}
fn correct_orientation(mut img: DynamicImage, orientation: u32) -> DynamicImage {
if orientation <= 1 || orientation > 8 {
return img;
}
if orientation >= 5 {
img = img.rotate90().fliph();
}
if orientation == 3 || orientation == 4 || orientation == 7 || orientation == 8 {
img = img.rotate180();
}
if orientation % 2 == 0 {
img = img.fliph();
}
img
}
pub fn generate_pictures(picture: &Picture) -> Result<()> | let path = format!("{}/{}/large/{}", image_base_path(), picture.id, picture.image_file_name);
let new_img = img.resize(800, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
let path = format!(
"{}/{}/thumbnail/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let (width, height) = img.dimensions();
let aspect_ratio = width as f32 / height as f32;
let img = if aspect_ratio!= THUMB_ASPEC_RATIO {
let mid_x = width / 2;
let mid_y = height / 2;
if width > height {
img.crop(mid_x - (height / 2), mid_y - (height / 2), height, height)
} else {
img.crop(mid_x - (width / 2), mid_y - (width / 2), width, width)
}
} else {
img
};
let new_img = img.resize_exact(600, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
Ok(())
}
| {
let path = format!(
"{}/{}/original/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let exif = read_exif(&path)?;
let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) {
Some(orientation) => match orientation.value.get_uint(0) {
Some(v @ 1..=8) => v,
_ => 0,
},
None => 0,
};
let mut img = image::open(path)?;
img = correct_orientation(img, orientation);
| identifier_body |
picture.rs | use chrono::naive::NaiveDateTime;
use exif::{Exif, In, Tag};
use serde::{Deserialize, Serialize};
use validator::Validate;
use anyhow::{Error, Result};
use image::GenericImageView;
use image::{imageops, DynamicImage};
use crate::schema::pictures;
use crate::utils::image_base_path;
#[derive(Debug, Clone, Queryable, Insertable, Serialize, Deserialize)]
pub struct Picture {
pub id: i32,
pub author_id: i32,
pub in_reply_to: Option<String>,
pub webmentions_count: i32,
pub image_file_name: String,
pub image_content_type: String,
pub image_file_size: i32,
pub image_updated_at: NaiveDateTime,
pub inserted_at: NaiveDateTime,
pub updated_at: NaiveDateTime,
pub title: String,
pub posse: bool,
pub show_in_index: bool,
pub content: String,
pub lang: String,
pub alt: Option<String>,
}
#[derive(Deserialize, Serialize, Debug, Insertable, Clone, Validate, Default)]
#[table_name = "pictures"]
pub struct NewPicture {
pub author_id: Option<i32>,
#[validate(length(min = 5))]
pub title: String,
#[validate(length(min = 5))]
pub alt: Option<String>,
#[validate(url)]
pub in_reply_to: Option<String>,
#[validate(length(min = 2, max = 2))]
pub lang: String,
#[serde(default)]
pub posse: bool,
#[serde(default)]
pub show_in_index: bool,
#[validate(required, length(min = 5))]
pub content: Option<String>,
pub image_file_name: Option<String>,
pub image_content_type: Option<String>,
pub image_file_size: Option<i32>,
pub image_updated_at: Option<NaiveDateTime>,
pub inserted_at: Option<NaiveDateTime>,
pub updated_at: Option<NaiveDateTime>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct NewJsonPicture {
#[serde(flatten)]
pub new_picture: NewPicture,
pub picture: Option<String>,
}
const THUMB_ASPEC_RATIO: f32 = 1.0;
fn read_exif(path: &str) -> Result<Exif, Error> {
let file = std::fs::File::open(path)?;
let mut bufreader = std::io::BufReader::new(&file);
let exifreader = exif::Reader::new();
Ok(exifreader
.read_from_container(&mut bufreader)
.map_err(|_| anyhow!("error reading file"))?)
}
fn correct_orientation(mut img: DynamicImage, orientation: u32) -> DynamicImage {
if orientation <= 1 || orientation > 8 {
return img;
}
if orientation >= 5 {
img = img.rotate90().fliph();
}
if orientation == 3 || orientation == 4 || orientation == 7 || orientation == 8 {
img = img.rotate180();
}
if orientation % 2 == 0 {
img = img.fliph();
}
img
}
pub fn | (picture: &Picture) -> Result<()> {
let path = format!(
"{}/{}/original/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let exif = read_exif(&path)?;
let orientation = match exif.get_field(Tag::Orientation, In::PRIMARY) {
Some(orientation) => match orientation.value.get_uint(0) {
Some(v @ 1..=8) => v,
_ => 0,
},
None => 0,
};
let mut img = image::open(path)?;
img = correct_orientation(img, orientation);
let path = format!("{}/{}/large/{}", image_base_path(), picture.id, picture.image_file_name);
let new_img = img.resize(800, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
let path = format!(
"{}/{}/thumbnail/{}",
image_base_path(),
picture.id,
picture.image_file_name
);
let (width, height) = img.dimensions();
let aspect_ratio = width as f32 / height as f32;
let img = if aspect_ratio!= THUMB_ASPEC_RATIO {
let mid_x = width / 2;
let mid_y = height / 2;
if width > height {
img.crop(mid_x - (height / 2), mid_y - (height / 2), height, height)
} else {
img.crop(mid_x - (width / 2), mid_y - (width / 2), width, width)
}
} else {
img
};
let new_img = img.resize_exact(600, 600, imageops::FilterType::CatmullRom);
new_img.save(path)?;
Ok(())
}
| generate_pictures | identifier_name |
wasm.rs | pub struct NativeManager {
}
impl NativeManager {
pub(crate) fn new() -> NativeManager {
NativeManager { /*devices: Vec::new()*/ }
}
/// Do a search for controllers. Returns number of controllers.
pub(crate) fn search(&mut self) -> (usize, usize) {
/* let devices = find_devices();
// Add devices
for mut i in devices {
if self.devices.contains(&i) {
continue;
}
open_joystick(&mut i);
// Setup device for asynchronous reads
if i.fd!= -1 {
println!("New Joystick");
joystick_async(i.fd);
let index = self.add(i);
let (min, max, _) = joystick_abs(self.devices[index].fd);
let (_, id, _) = joystick_id(self.devices[index].fd);
let effect = joystick_haptic(self.devices[index].fd);
self.devices[index].min = min;
self.devices[index].max = max;
self.devices[index].id = id;
self.devices[index].effect = effect;
return (self.devices.len(), index);
}
}*/
(self.num_plugged_in(), ::std::usize::MAX)
}
pub(crate) fn get_id(&self, id: usize) -> (i32, bool) {
// if id >= self.devices.len() {
(0, true)
/* } else {
let (_, a, b) = joystick_id(self.devices[id].fd);
(a, b)
}*/
}
pub(crate) fn get_fd(&self, id: usize) -> (i32, bool, bool) {
/* let (_, unplug) = self.get_id(id);
(self.devices[id].fd, unplug, self.devices[id].name == None)*/
(0, false, false)
}
pub(crate) fn num_plugged_in(&self) -> usize {
// self.devices.len()
0
}
pub(crate) fn disconnect(&mut self, _fd: i32) -> () {
/* for i in 0..self.devices.len() {
if self.devices[i].fd == fd {
joystick_drop(fd);
self.devices[i].name = None;
return;
}
}
panic!("There was no fd of {}", fd);*/
}
pub(crate) fn | (&self, _i: usize, _state: &mut crate::hid::HidState) {
/* if (state.output & crate::hid::Output::HapticStart as u32)!= 0 {
self.rumble(i, true);
state.output = 0;
} else if (state.output & crate::hid::Output::HapticStop as u32)!= 0 {
self.rumble(i, false);
state.output = 0;
}
while joystick_poll_event(self.devices[i].fd, state, self.devices[i].min, self.devices[i].max, self.devices[i].id) {
}*/
}
/* fn add(&mut self, _device: Device) -> usize {
let mut r = 0;
for i in &mut self.devices {
if i.name == None {
*i = device;
return r;
}
r += 1;
}
self.devices.push(device);
r
0
}*/
pub(crate) fn rumble(&self, _i: usize, _on: bool) {
// println!("RMBLE {}", on);
// joystick_rumble(self.devices[i].fd, self.devices[i].effect, on);
}
}
| poll_event | identifier_name |
wasm.rs | pub struct NativeManager {
}
impl NativeManager {
pub(crate) fn new() -> NativeManager |
/// Do a search for controllers. Returns number of controllers.
pub(crate) fn search(&mut self) -> (usize, usize) {
/* let devices = find_devices();
// Add devices
for mut i in devices {
if self.devices.contains(&i) {
continue;
}
open_joystick(&mut i);
// Setup device for asynchronous reads
if i.fd!= -1 {
println!("New Joystick");
joystick_async(i.fd);
let index = self.add(i);
let (min, max, _) = joystick_abs(self.devices[index].fd);
let (_, id, _) = joystick_id(self.devices[index].fd);
let effect = joystick_haptic(self.devices[index].fd);
self.devices[index].min = min;
self.devices[index].max = max;
self.devices[index].id = id;
self.devices[index].effect = effect;
return (self.devices.len(), index);
}
}*/
(self.num_plugged_in(), ::std::usize::MAX)
}
pub(crate) fn get_id(&self, id: usize) -> (i32, bool) {
// if id >= self.devices.len() {
(0, true)
/* } else {
let (_, a, b) = joystick_id(self.devices[id].fd);
(a, b)
}*/
}
pub(crate) fn get_fd(&self, id: usize) -> (i32, bool, bool) {
/* let (_, unplug) = self.get_id(id);
(self.devices[id].fd, unplug, self.devices[id].name == None)*/
(0, false, false)
}
pub(crate) fn num_plugged_in(&self) -> usize {
// self.devices.len()
0
}
pub(crate) fn disconnect(&mut self, _fd: i32) -> () {
/* for i in 0..self.devices.len() {
if self.devices[i].fd == fd {
joystick_drop(fd);
self.devices[i].name = None;
return;
}
}
panic!("There was no fd of {}", fd);*/
}
pub(crate) fn poll_event(&self, _i: usize, _state: &mut crate::hid::HidState) {
/* if (state.output & crate::hid::Output::HapticStart as u32)!= 0 {
self.rumble(i, true);
state.output = 0;
} else if (state.output & crate::hid::Output::HapticStop as u32)!= 0 {
self.rumble(i, false);
state.output = 0;
}
while joystick_poll_event(self.devices[i].fd, state, self.devices[i].min, self.devices[i].max, self.devices[i].id) {
}*/
}
/* fn add(&mut self, _device: Device) -> usize {
let mut r = 0;
for i in &mut self.devices {
if i.name == None {
*i = device;
return r;
}
r += 1;
}
self.devices.push(device);
r
0
}*/
pub(crate) fn rumble(&self, _i: usize, _on: bool) {
// println!("RMBLE {}", on);
// joystick_rumble(self.devices[i].fd, self.devices[i].effect, on);
}
}
| {
NativeManager { /*devices: Vec::new()*/ }
} | identifier_body |
wasm.rs | pub struct NativeManager {
}
impl NativeManager {
pub(crate) fn new() -> NativeManager {
NativeManager { /*devices: Vec::new()*/ }
}
/// Do a search for controllers. Returns number of controllers.
pub(crate) fn search(&mut self) -> (usize, usize) {
/* let devices = find_devices();
// Add devices
for mut i in devices {
if self.devices.contains(&i) {
continue;
}
open_joystick(&mut i);
// Setup device for asynchronous reads
if i.fd!= -1 {
println!("New Joystick");
joystick_async(i.fd);
let index = self.add(i);
let (min, max, _) = joystick_abs(self.devices[index].fd); | let effect = joystick_haptic(self.devices[index].fd);
self.devices[index].min = min;
self.devices[index].max = max;
self.devices[index].id = id;
self.devices[index].effect = effect;
return (self.devices.len(), index);
}
}*/
(self.num_plugged_in(), ::std::usize::MAX)
}
pub(crate) fn get_id(&self, id: usize) -> (i32, bool) {
// if id >= self.devices.len() {
(0, true)
/* } else {
let (_, a, b) = joystick_id(self.devices[id].fd);
(a, b)
}*/
}
pub(crate) fn get_fd(&self, id: usize) -> (i32, bool, bool) {
/* let (_, unplug) = self.get_id(id);
(self.devices[id].fd, unplug, self.devices[id].name == None)*/
(0, false, false)
}
pub(crate) fn num_plugged_in(&self) -> usize {
// self.devices.len()
0
}
pub(crate) fn disconnect(&mut self, _fd: i32) -> () {
/* for i in 0..self.devices.len() {
if self.devices[i].fd == fd {
joystick_drop(fd);
self.devices[i].name = None;
return;
}
}
panic!("There was no fd of {}", fd);*/
}
pub(crate) fn poll_event(&self, _i: usize, _state: &mut crate::hid::HidState) {
/* if (state.output & crate::hid::Output::HapticStart as u32)!= 0 {
self.rumble(i, true);
state.output = 0;
} else if (state.output & crate::hid::Output::HapticStop as u32)!= 0 {
self.rumble(i, false);
state.output = 0;
}
while joystick_poll_event(self.devices[i].fd, state, self.devices[i].min, self.devices[i].max, self.devices[i].id) {
}*/
}
/* fn add(&mut self, _device: Device) -> usize {
let mut r = 0;
for i in &mut self.devices {
if i.name == None {
*i = device;
return r;
}
r += 1;
}
self.devices.push(device);
r
0
}*/
pub(crate) fn rumble(&self, _i: usize, _on: bool) {
// println!("RMBLE {}", on);
// joystick_rumble(self.devices[i].fd, self.devices[i].effect, on);
}
} | let (_, id, _) = joystick_id(self.devices[index].fd); | random_line_split |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces,
Differentiable,
Function,
Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// On-policy variant of Watkins' Q-learning with eligibility traces (aka
/// "modified Q-learning").
///
/// # References
/// - Rummery, G. A. (1995). Problem Solving with Reinforcement Learning. Ph.D
/// thesis, Cambridge University.
/// - Singh, S. P., Sutton, R. S. (1996). Reinforcement learning with replacing
/// eligibility traces. Machine Learning 22:123–158.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct SARSALambda<Q, P, T> {
#[weights]
pub fa_theta: Q,
pub policy: P,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, P, R> Handler<&'m Transition<S, P::Action>> for SARSALambda<
Q, P, Tr<&'m S, &'m P::Action, Q, R>
>
where
Q: Function<(&'m S, P::Action), Output = f64> +
Differentiable<(&'m S, &'m P::Action), Output = f64> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, &'m P::Action, Q, R>>>,
P: Policy<&'m S>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, &'m P::Action)>>::Jacobian>,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, P::Action>) -> Result<Self::Response, Self::Error> {
let s = t.from.state();
let qsa = self.fa_theta.evaluate((s, &t.action));
// Update trace with latest feature vector:
self.trace.update(&self.fa_theta.grad((s, &t.action)));
// Update weight vectors:
let td_error = if t.terminated() {
| lse {
let ns = t.to.state();
let na = self.policy.sample(&mut thread_rng(), ns);
let nqsna = self.fa_theta.evaluate((ns, na));
let residual = t.reward + self.gamma * nqsna - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
}
| let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} e | conditional_block |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces,
Differentiable,
Function,
Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// On-policy variant of Watkins' Q-learning with eligibility traces (aka
/// "modified Q-learning").
///
/// # References
/// - Rummery, G. A. (1995). Problem Solving with Reinforcement Learning. Ph.D
/// thesis, Cambridge University.
/// - Singh, S. P., Sutton, R. S. (1996). Reinforcement learning with replacing
/// eligibility traces. Machine Learning 22:123–158.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct SARSALambda<Q, P, T> {
#[weights]
pub fa_theta: Q,
pub policy: P,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, P, R> Handler<&'m Transition<S, P::Action>> for SARSALambda<
Q, P, Tr<&'m S, &'m P::Action, Q, R>
>
where
Q: Function<(&'m S, P::Action), Output = f64> +
Differentiable<(&'m S, &'m P::Action), Output = f64> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, &'m P::Action, Q, R>>>,
P: Policy<&'m S>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, &'m P::Action)>>::Jacobian>,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, P::Action>) -> Result<Self::Response, Self::Error> {
| let nqsna = self.fa_theta.evaluate((ns, na));
let residual = t.reward + self.gamma * nqsna - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
}
| let s = t.from.state();
let qsa = self.fa_theta.evaluate((s, &t.action));
// Update trace with latest feature vector:
self.trace.update(&self.fa_theta.grad((s, &t.action)));
// Update weight vectors:
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} else {
let ns = t.to.state();
let na = self.policy.sample(&mut thread_rng(), ns); | identifier_body |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces,
Differentiable,
Function,
Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// On-policy variant of Watkins' Q-learning with eligibility traces (aka
/// "modified Q-learning").
///
/// # References
/// - Rummery, G. A. (1995). Problem Solving with Reinforcement Learning. Ph.D
/// thesis, Cambridge University.
/// - Singh, S. P., Sutton, R. S. (1996). Reinforcement learning with replacing
/// eligibility traces. Machine Learning 22:123–158.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct SA | , P, T> {
#[weights]
pub fa_theta: Q,
pub policy: P,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, P, R> Handler<&'m Transition<S, P::Action>> for SARSALambda<
Q, P, Tr<&'m S, &'m P::Action, Q, R>
>
where
Q: Function<(&'m S, P::Action), Output = f64> +
Differentiable<(&'m S, &'m P::Action), Output = f64> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, &'m P::Action, Q, R>>>,
P: Policy<&'m S>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, &'m P::Action)>>::Jacobian>,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, P::Action>) -> Result<Self::Response, Self::Error> {
let s = t.from.state();
let qsa = self.fa_theta.evaluate((s, &t.action));
// Update trace with latest feature vector:
self.trace.update(&self.fa_theta.grad((s, &t.action)));
// Update weight vectors:
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} else {
let ns = t.to.state();
let na = self.policy.sample(&mut thread_rng(), ns);
let nqsna = self.fa_theta.evaluate((ns, na));
let residual = t.reward + self.gamma * nqsna - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
}
| RSALambda<Q | identifier_name |
sarsa_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
policies::Policy,
traces, | Handler,
Parameterised,
};
use rand::thread_rng;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct Response {
td_error: f64,
}
/// On-policy variant of Watkins' Q-learning with eligibility traces (aka
/// "modified Q-learning").
///
/// # References
/// - Rummery, G. A. (1995). Problem Solving with Reinforcement Learning. Ph.D
/// thesis, Cambridge University.
/// - Singh, S. P., Sutton, R. S. (1996). Reinforcement learning with replacing
/// eligibility traces. Machine Learning 22:123–158.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct SARSALambda<Q, P, T> {
#[weights]
pub fa_theta: Q,
pub policy: P,
pub trace: T,
pub alpha: f64,
pub gamma: f64,
}
type Tr<S, A, Q, R> = traces::Trace<<Q as Differentiable<(S, A)>>::Jacobian, R>;
impl<'m, S, Q, P, R> Handler<&'m Transition<S, P::Action>> for SARSALambda<
Q, P, Tr<&'m S, &'m P::Action, Q, R>
>
where
Q: Function<(&'m S, P::Action), Output = f64> +
Differentiable<(&'m S, &'m P::Action), Output = f64> +
for<'j> Handler<ScaledGradientUpdate<&'j Tr<&'m S, &'m P::Action, Q, R>>>,
P: Policy<&'m S>,
R: traces::UpdateRule<<Q as Differentiable<(&'m S, &'m P::Action)>>::Jacobian>,
{
type Response = Response;
type Error = ();
fn handle(&mut self, t: &'m Transition<S, P::Action>) -> Result<Self::Response, Self::Error> {
let s = t.from.state();
let qsa = self.fa_theta.evaluate((s, &t.action));
// Update trace with latest feature vector:
self.trace.update(&self.fa_theta.grad((s, &t.action)));
// Update weight vectors:
let td_error = if t.terminated() {
let residual = t.reward - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
self.trace.reset();
residual
} else {
let ns = t.to.state();
let na = self.policy.sample(&mut thread_rng(), ns);
let nqsna = self.fa_theta.evaluate((ns, na));
let residual = t.reward + self.gamma * nqsna - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
}).map_err(|_| ())?;
residual
};
Ok(Response { td_error, })
}
} | Differentiable,
Function, | random_line_split |
tsm_vte.rs | #![feature(libc)]
extern crate libc;
extern crate regex; |
use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::ptr;
use std::slice;
use tsm_sys::*;
#[test]
fn tsm_vte_stuff_works() {
let mut screen = ptr::null_mut();
let err = unsafe { tsm::tsm_screen_new(&mut screen, None, ptr::null_mut()) };
assert_eq!(0, err);
let mut vte = ptr::null_mut();
extern "C" fn write_cb(_: *mut tsm::TsmVte, input_ptr: *const c_char, input_size: size_t, output: *mut c_void) {
let output: &mut Output = unsafe { &mut *(output as *mut Output) };
let input = unsafe { slice::from_raw_parts(input_ptr, input_size as usize) };
for c in input {
output.string.push(*c as u8 as char);
}
}
struct Output { string: String }
let mut output = Output { string: "".to_string() };
let output_ptr: *mut c_void = &mut output as *mut _ as *mut c_void;
unsafe { tsm::tsm_vte_new(&mut vte, screen, write_cb, output_ptr, None, ptr::null_mut() ) };
unsafe { tsm::tsm_vte_reset(vte) }
unsafe { tsm::tsm_vte_hard_reset(vte) }
for c in "hello world".chars() {
unsafe { tsm::tsm_vte_handle_keyboard(vte, 0, 0, 0, c as u32); }
}
assert_eq!(&output.string, "hello world");
} | extern crate tsm_sys; | random_line_split |
tsm_vte.rs | #![feature(libc)]
extern crate libc;
extern crate regex;
extern crate tsm_sys;
use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::ptr;
use std::slice;
use tsm_sys::*;
#[test]
fn tsm_vte_stuff_works() {
let mut screen = ptr::null_mut();
let err = unsafe { tsm::tsm_screen_new(&mut screen, None, ptr::null_mut()) };
assert_eq!(0, err);
let mut vte = ptr::null_mut();
extern "C" fn write_cb(_: *mut tsm::TsmVte, input_ptr: *const c_char, input_size: size_t, output: *mut c_void) {
let output: &mut Output = unsafe { &mut *(output as *mut Output) };
let input = unsafe { slice::from_raw_parts(input_ptr, input_size as usize) };
for c in input {
output.string.push(*c as u8 as char);
}
}
struct | { string: String }
let mut output = Output { string: "".to_string() };
let output_ptr: *mut c_void = &mut output as *mut _ as *mut c_void;
unsafe { tsm::tsm_vte_new(&mut vte, screen, write_cb, output_ptr, None, ptr::null_mut() ) };
unsafe { tsm::tsm_vte_reset(vte) }
unsafe { tsm::tsm_vte_hard_reset(vte) }
for c in "hello world".chars() {
unsafe { tsm::tsm_vte_handle_keyboard(vte, 0, 0, 0, c as u32); }
}
assert_eq!(&output.string, "hello world");
}
| Output | identifier_name |
metrics.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use prometheus::*;
use prometheus_static_metric::*;
make_static_metric! {
pub label_enum MvccConflictKind {
prewrite_write_conflict,
rolled_back,
commit_lock_not_found,
rollback_committed,
acquire_pessimistic_lock_conflict,
pipelined_acquire_pessimistic_lock_amend_fail,
pipelined_acquire_pessimistic_lock_amend_success,
}
pub label_enum MvccDuplicateCommandKind {
prewrite,
commit,
rollback,
acquire_pessimistic_lock,
}
pub label_enum MvccCheckTxnStatusKind {
rollback,
update_ts,
get_commit_info,
pessimistic_rollback,
}
pub struct MvccConflictCounterVec: IntCounter {
"type" => MvccConflictKind,
}
pub struct MvccDuplicateCmdCounterVec: IntCounter {
"type" => MvccDuplicateCommandKind,
}
pub struct MvccCheckTxnStatusCounterVec: IntCounter {
"type" => MvccCheckTxnStatusKind,
}
}
lazy_static! {
pub static ref MVCC_VERSIONS_HISTOGRAM: Histogram = register_histogram!(
"tikv_storage_mvcc_versions",
"Histogram of versions for each key",
exponential_buckets(1.0, 2.0, 30).unwrap()
)
.unwrap();
pub static ref GC_DELETE_VERSIONS_HISTOGRAM: Histogram = register_histogram!(
"tikv_storage_mvcc_gc_delete_versions",
"Histogram of versions deleted by gc for each key",
exponential_buckets(1.0, 2.0, 30).unwrap()
)
.unwrap();
pub static ref CONCURRENCY_MANAGER_LOCK_DURATION_HISTOGRAM: Histogram = register_histogram!(
"tikv_concurrency_manager_lock_duration",
"Histogram of the duration of lock key in the concurrency manager",
exponential_buckets(1e-7, 2.0, 20).unwrap() // 100ns ~ 100ms
)
.unwrap();
pub static ref MVCC_CONFLICT_COUNTER: MvccConflictCounterVec = {
register_static_int_counter_vec!(
MvccConflictCounterVec,
"tikv_storage_mvcc_conflict_counter",
"Total number of conflict error",
&["type"]
) | MvccDuplicateCmdCounterVec,
"tikv_storage_mvcc_duplicate_cmd_counter",
"Total number of duplicated commands",
&["type"]
)
.unwrap()
};
pub static ref MVCC_CHECK_TXN_STATUS_COUNTER_VEC: MvccCheckTxnStatusCounterVec = {
register_static_int_counter_vec!(
MvccCheckTxnStatusCounterVec,
"tikv_storage_mvcc_check_txn_status",
"Counter of different results of check_txn_status",
&["type"]
)
.unwrap()
};
} | .unwrap()
};
pub static ref MVCC_DUPLICATE_CMD_COUNTER_VEC: MvccDuplicateCmdCounterVec = {
register_static_int_counter_vec!( | random_line_split |
main.rs | use std::io::File;
use map_generator::HeightMap;
use coordinate_formula::CoordinateFormula;
mod map_generator;
mod coordinate_formula;
static FILENAME: &'static str = "height_map.out";
fn main() | map_generator::drop_particles(drop_point.as_slice(), (x, y), &mut height_map);
coordinate_formula = coordinate_formula.change_iteration();
}
// output height map in YAML format
let path = Path::new(FILENAME);
let mut file = match File::create(&path) {
Err(why) => fail!("couldn't create {}: {}", FILENAME, why.desc),
Ok(file) => file,
};
file.write_line("---");
for n in range(0u, size * size) {
file.write_line(format!("- {}", *height_map.map.get_mut(n)).as_slice());
}
}
| {
let size = 50;
let number_of_drop_points = 20;
let min_particles = 400;
let max_particles = 2000;
let number_of_passes = 5;
let mut coordinate_formula = CoordinateFormula::new();
let mut height_map: HeightMap = HeightMap::new(size);
let drops: Vec<Box<Vec<int>>>;
drops = Vec::from_fn(number_of_passes,
|_| map_generator::create_drop_points(number_of_drop_points *
number_of_passes / 2,
min_particles,
max_particles));
for drop_point in drops.iter() {
let (x, y) = coordinate_formula.calculate_coordinates(size); | identifier_body |
main.rs | use std::io::File;
use map_generator::HeightMap;
use coordinate_formula::CoordinateFormula;
mod map_generator;
mod coordinate_formula;
static FILENAME: &'static str = "height_map.out";
fn | () {
let size = 50;
let number_of_drop_points = 20;
let min_particles = 400;
let max_particles = 2000;
let number_of_passes = 5;
let mut coordinate_formula = CoordinateFormula::new();
let mut height_map: HeightMap = HeightMap::new(size);
let drops: Vec<Box<Vec<int>>>;
drops = Vec::from_fn(number_of_passes,
|_| map_generator::create_drop_points(number_of_drop_points *
number_of_passes / 2,
min_particles,
max_particles));
for drop_point in drops.iter() {
let (x, y) = coordinate_formula.calculate_coordinates(size);
map_generator::drop_particles(drop_point.as_slice(), (x, y), &mut height_map);
coordinate_formula = coordinate_formula.change_iteration();
}
// output height map in YAML format
let path = Path::new(FILENAME);
let mut file = match File::create(&path) {
Err(why) => fail!("couldn't create {}: {}", FILENAME, why.desc),
Ok(file) => file,
};
file.write_line("---");
for n in range(0u, size * size) {
file.write_line(format!("- {}", *height_map.map.get_mut(n)).as_slice());
}
}
| main | identifier_name |
main.rs | use std::io::File;
use map_generator::HeightMap;
use coordinate_formula::CoordinateFormula;
mod map_generator;
mod coordinate_formula;
static FILENAME: &'static str = "height_map.out";
fn main() {
let size = 50;
let number_of_drop_points = 20;
let min_particles = 400;
let max_particles = 2000;
let number_of_passes = 5;
let mut coordinate_formula = CoordinateFormula::new();
let mut height_map: HeightMap = HeightMap::new(size);
let drops: Vec<Box<Vec<int>>>;
drops = Vec::from_fn(number_of_passes,
|_| map_generator::create_drop_points(number_of_drop_points *
number_of_passes / 2,
min_particles,
max_particles));
for drop_point in drops.iter() {
let (x, y) = coordinate_formula.calculate_coordinates(size);
map_generator::drop_particles(drop_point.as_slice(), (x, y), &mut height_map);
coordinate_formula = coordinate_formula.change_iteration();
}
// output height map in YAML format
let path = Path::new(FILENAME);
let mut file = match File::create(&path) {
Err(why) => fail!("couldn't create {}: {}", FILENAME, why.desc),
Ok(file) => file,
};
file.write_line("---"); | for n in range(0u, size * size) {
file.write_line(format!("- {}", *height_map.map.get_mut(n)).as_slice());
}
} | random_line_split | |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use clap::{App, ArgMatches, SubCommand};
use cli::arguments::{
a2_mode_arg, config_path_arg, config_project_arg, local_arg, no_open_arg, pipeline_arg,
project_arg, project_specific_args, scp_args, u_e_s_o_args, value_of,
};
use cli::Options;
use config::Config;
use fips;
use project;
use types::DeliveryResult;
pub const SUBCOMMAND_NAME: &'static str = "init";
#[derive(Debug)]
pub struct InitClapOptions<'n> {
pub user: &'n str,
pub server: &'n str,
pub ent: &'n str,
pub org: &'n str,
pub project: &'n str,
pub pipeline: &'n str,
pub config_json: &'n str,
pub generator: &'n str,
pub github_org_name: &'n str,
pub bitbucket_project_key: &'n str,
pub repo_name: &'n str,
pub no_v_ssl: bool,
pub no_open: bool,
pub skip_build_cookbook: bool,
pub local: bool,
pub fips: bool,
pub fips_git_port: &'n str,
pub fips_custom_cert_filename: &'n str,
pub a2_mode: Option<bool>,
}
impl<'n> Default for InitClapOptions<'n> {
fn default() -> Self {
InitClapOptions {
user: "",
server: "",
ent: "",
org: "",
project: "",
pipeline: "master",
config_json: "",
generator: "",
github_org_name: "",
bitbucket_project_key: "",
repo_name: "",
no_v_ssl: false,
no_open: false,
skip_build_cookbook: false,
local: false,
fips: false,
fips_git_port: "",
fips_custom_cert_filename: "",
a2_mode: None,
}
}
}
impl<'n> InitClapOptions<'n> {
pub fn new(matches: &'n ArgMatches<'n>) -> Self {
InitClapOptions {
user: value_of(&matches, "user"),
server: value_of(&matches, "server"),
ent: value_of(&matches, "ent"),
org: value_of(&matches, "org"),
project: value_of(&matches, "project"),
pipeline: value_of(&matches, "pipeline"),
config_json: value_of(&matches, "config-json"),
generator: value_of(&matches, "generator"),
github_org_name: value_of(&matches, "github"),
bitbucket_project_key: value_of(&matches, "bitbucket"),
repo_name: value_of(&matches, "repo-name"),
no_v_ssl: matches.is_present("no-verify-ssl"),
no_open: matches.is_present("no-open"),
skip_build_cookbook: matches.is_present("skip-build-cookbook"),
local: matches.is_present("local"),
fips: matches.is_present("fips"),
fips_git_port: value_of(&matches, "fips-git-port"),
fips_custom_cert_filename: value_of(&matches, "fips-custom-cert-filename"),
a2_mode: if matches.is_present("a2-mode") {
Some(true)
} else {
None
},
}
}
}
impl<'n> Options for InitClapOptions<'n> {
fn merge_options_and_config(&self, config: Config) -> DeliveryResult<Config> {
let project = try!(project::project_or_from_cwd(&self.project));
let new_config = config
.set_user(&self.user)
.set_server(&self.server)
.set_enterprise(&self.ent)
.set_organization(&self.org)
.set_project(&project)
.set_pipeline(&self.pipeline)
.set_generator(&self.generator)
.set_a2_mode_if_def(self.a2_mode)
.set_config_json(&self.config_json);
fips::merge_fips_options_and_config(
self.fips,
self.fips_git_port,
self.fips_custom_cert_filename,
new_config,
)
}
}
pub fn | <'c>() -> App<'c, 'c> {
SubCommand::with_name(SUBCOMMAND_NAME)
.about(
"Initialize a Delivery project \
(and lots more!)",
)
.args(&vec![
config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_project_arg(),
])
.args_from_usage(
"--generator=[generator] 'Local path or Git repo URL to a \
custom ChefDK build_cookbook generator (default:github)'
--skip-build-cookbook 'Do not create a build cookbook'",
)
.args(&u_e_s_o_args())
.args(&scp_args())
.args(&pipeline_arg())
.args(&project_specific_args())
.args(&vec![a2_mode_arg()])
}
| clap_subcommand | identifier_name |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use clap::{App, ArgMatches, SubCommand};
use cli::arguments::{
a2_mode_arg, config_path_arg, config_project_arg, local_arg, no_open_arg, pipeline_arg,
project_arg, project_specific_args, scp_args, u_e_s_o_args, value_of,
};
use cli::Options;
use config::Config;
use fips;
use project;
use types::DeliveryResult;
pub const SUBCOMMAND_NAME: &'static str = "init";
#[derive(Debug)]
pub struct InitClapOptions<'n> {
pub user: &'n str,
pub server: &'n str,
pub ent: &'n str,
pub org: &'n str,
pub project: &'n str,
pub pipeline: &'n str,
pub config_json: &'n str,
pub generator: &'n str,
pub github_org_name: &'n str,
pub bitbucket_project_key: &'n str,
pub repo_name: &'n str,
pub no_v_ssl: bool,
pub no_open: bool,
pub skip_build_cookbook: bool,
pub local: bool,
pub fips: bool,
pub fips_git_port: &'n str,
pub fips_custom_cert_filename: &'n str,
pub a2_mode: Option<bool>,
}
impl<'n> Default for InitClapOptions<'n> {
fn default() -> Self {
InitClapOptions {
user: "",
server: "",
ent: "",
org: "",
project: "",
pipeline: "master",
config_json: "",
generator: "",
github_org_name: "",
bitbucket_project_key: "",
repo_name: "",
no_v_ssl: false,
no_open: false,
skip_build_cookbook: false,
local: false,
fips: false,
fips_git_port: "",
fips_custom_cert_filename: "",
a2_mode: None,
}
}
}
impl<'n> InitClapOptions<'n> {
pub fn new(matches: &'n ArgMatches<'n>) -> Self {
InitClapOptions {
user: value_of(&matches, "user"),
server: value_of(&matches, "server"),
ent: value_of(&matches, "ent"),
org: value_of(&matches, "org"),
project: value_of(&matches, "project"),
pipeline: value_of(&matches, "pipeline"),
config_json: value_of(&matches, "config-json"),
generator: value_of(&matches, "generator"),
github_org_name: value_of(&matches, "github"),
bitbucket_project_key: value_of(&matches, "bitbucket"),
repo_name: value_of(&matches, "repo-name"),
no_v_ssl: matches.is_present("no-verify-ssl"),
no_open: matches.is_present("no-open"),
skip_build_cookbook: matches.is_present("skip-build-cookbook"),
local: matches.is_present("local"),
fips: matches.is_present("fips"),
fips_git_port: value_of(&matches, "fips-git-port"),
fips_custom_cert_filename: value_of(&matches, "fips-custom-cert-filename"),
a2_mode: if matches.is_present("a2-mode") {
Some(true)
} else | ,
}
}
}
impl<'n> Options for InitClapOptions<'n> {
fn merge_options_and_config(&self, config: Config) -> DeliveryResult<Config> {
let project = try!(project::project_or_from_cwd(&self.project));
let new_config = config
.set_user(&self.user)
.set_server(&self.server)
.set_enterprise(&self.ent)
.set_organization(&self.org)
.set_project(&project)
.set_pipeline(&self.pipeline)
.set_generator(&self.generator)
.set_a2_mode_if_def(self.a2_mode)
.set_config_json(&self.config_json);
fips::merge_fips_options_and_config(
self.fips,
self.fips_git_port,
self.fips_custom_cert_filename,
new_config,
)
}
}
pub fn clap_subcommand<'c>() -> App<'c, 'c> {
SubCommand::with_name(SUBCOMMAND_NAME)
.about(
"Initialize a Delivery project \
(and lots more!)",
)
.args(&vec![
config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_project_arg(),
])
.args_from_usage(
"--generator=[generator] 'Local path or Git repo URL to a \
custom ChefDK build_cookbook generator (default:github)'
--skip-build-cookbook 'Do not create a build cookbook'",
)
.args(&u_e_s_o_args())
.args(&scp_args())
.args(&pipeline_arg())
.args(&project_specific_args())
.args(&vec![a2_mode_arg()])
}
| {
None
} | conditional_block |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use clap::{App, ArgMatches, SubCommand};
use cli::arguments::{
a2_mode_arg, config_path_arg, config_project_arg, local_arg, no_open_arg, pipeline_arg,
project_arg, project_specific_args, scp_args, u_e_s_o_args, value_of,
};
use cli::Options;
use config::Config;
use fips;
use project;
use types::DeliveryResult;
pub const SUBCOMMAND_NAME: &'static str = "init";
#[derive(Debug)]
pub struct InitClapOptions<'n> {
pub user: &'n str,
pub server: &'n str,
pub ent: &'n str,
pub org: &'n str,
pub project: &'n str,
pub pipeline: &'n str,
pub config_json: &'n str,
pub generator: &'n str,
pub github_org_name: &'n str,
pub bitbucket_project_key: &'n str,
pub repo_name: &'n str,
pub no_v_ssl: bool,
pub no_open: bool,
pub skip_build_cookbook: bool,
pub local: bool,
pub fips: bool,
pub fips_git_port: &'n str,
pub fips_custom_cert_filename: &'n str,
pub a2_mode: Option<bool>,
}
impl<'n> Default for InitClapOptions<'n> {
fn default() -> Self {
InitClapOptions {
user: "",
server: "",
ent: "",
org: "",
project: "",
pipeline: "master",
config_json: "",
generator: "",
github_org_name: "",
bitbucket_project_key: "",
repo_name: "",
no_v_ssl: false,
no_open: false,
skip_build_cookbook: false,
local: false,
fips: false,
fips_git_port: "",
fips_custom_cert_filename: "",
a2_mode: None,
}
}
}
impl<'n> InitClapOptions<'n> {
pub fn new(matches: &'n ArgMatches<'n>) -> Self {
InitClapOptions {
user: value_of(&matches, "user"),
server: value_of(&matches, "server"),
ent: value_of(&matches, "ent"),
org: value_of(&matches, "org"),
project: value_of(&matches, "project"),
pipeline: value_of(&matches, "pipeline"),
config_json: value_of(&matches, "config-json"),
generator: value_of(&matches, "generator"),
github_org_name: value_of(&matches, "github"),
bitbucket_project_key: value_of(&matches, "bitbucket"),
repo_name: value_of(&matches, "repo-name"),
no_v_ssl: matches.is_present("no-verify-ssl"),
no_open: matches.is_present("no-open"),
skip_build_cookbook: matches.is_present("skip-build-cookbook"),
local: matches.is_present("local"),
fips: matches.is_present("fips"),
fips_git_port: value_of(&matches, "fips-git-port"),
fips_custom_cert_filename: value_of(&matches, "fips-custom-cert-filename"),
a2_mode: if matches.is_present("a2-mode") {
Some(true)
} else {
None
},
}
}
}
impl<'n> Options for InitClapOptions<'n> {
fn merge_options_and_config(&self, config: Config) -> DeliveryResult<Config> {
let project = try!(project::project_or_from_cwd(&self.project));
let new_config = config
.set_user(&self.user)
.set_server(&self.server)
.set_enterprise(&self.ent)
.set_organization(&self.org)
.set_project(&project)
.set_pipeline(&self.pipeline)
.set_generator(&self.generator)
.set_a2_mode_if_def(self.a2_mode)
.set_config_json(&self.config_json);
fips::merge_fips_options_and_config(
self.fips,
self.fips_git_port,
self.fips_custom_cert_filename,
new_config,
)
}
}
pub fn clap_subcommand<'c>() -> App<'c, 'c> {
SubCommand::with_name(SUBCOMMAND_NAME)
.about(
"Initialize a Delivery project \
(and lots more!)",
)
.args(&vec![ | config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_project_arg(),
])
.args_from_usage(
"--generator=[generator] 'Local path or Git repo URL to a \
custom ChefDK build_cookbook generator (default:github)'
--skip-build-cookbook 'Do not create a build cookbook'",
)
.args(&u_e_s_o_args())
.args(&scp_args())
.args(&pipeline_arg())
.args(&project_specific_args())
.args(&vec![a2_mode_arg()])
} | random_line_split | |
init.rs | //
// Copyright:: Copyright (c) 2016 Chef Software, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use clap::{App, ArgMatches, SubCommand};
use cli::arguments::{
a2_mode_arg, config_path_arg, config_project_arg, local_arg, no_open_arg, pipeline_arg,
project_arg, project_specific_args, scp_args, u_e_s_o_args, value_of,
};
use cli::Options;
use config::Config;
use fips;
use project;
use types::DeliveryResult;
pub const SUBCOMMAND_NAME: &'static str = "init";
#[derive(Debug)]
pub struct InitClapOptions<'n> {
pub user: &'n str,
pub server: &'n str,
pub ent: &'n str,
pub org: &'n str,
pub project: &'n str,
pub pipeline: &'n str,
pub config_json: &'n str,
pub generator: &'n str,
pub github_org_name: &'n str,
pub bitbucket_project_key: &'n str,
pub repo_name: &'n str,
pub no_v_ssl: bool,
pub no_open: bool,
pub skip_build_cookbook: bool,
pub local: bool,
pub fips: bool,
pub fips_git_port: &'n str,
pub fips_custom_cert_filename: &'n str,
pub a2_mode: Option<bool>,
}
impl<'n> Default for InitClapOptions<'n> {
fn default() -> Self {
InitClapOptions {
user: "",
server: "",
ent: "",
org: "",
project: "",
pipeline: "master",
config_json: "",
generator: "",
github_org_name: "",
bitbucket_project_key: "",
repo_name: "",
no_v_ssl: false,
no_open: false,
skip_build_cookbook: false,
local: false,
fips: false,
fips_git_port: "",
fips_custom_cert_filename: "",
a2_mode: None,
}
}
}
impl<'n> InitClapOptions<'n> {
pub fn new(matches: &'n ArgMatches<'n>) -> Self {
InitClapOptions {
user: value_of(&matches, "user"),
server: value_of(&matches, "server"),
ent: value_of(&matches, "ent"),
org: value_of(&matches, "org"),
project: value_of(&matches, "project"),
pipeline: value_of(&matches, "pipeline"),
config_json: value_of(&matches, "config-json"),
generator: value_of(&matches, "generator"),
github_org_name: value_of(&matches, "github"),
bitbucket_project_key: value_of(&matches, "bitbucket"),
repo_name: value_of(&matches, "repo-name"),
no_v_ssl: matches.is_present("no-verify-ssl"),
no_open: matches.is_present("no-open"),
skip_build_cookbook: matches.is_present("skip-build-cookbook"),
local: matches.is_present("local"),
fips: matches.is_present("fips"),
fips_git_port: value_of(&matches, "fips-git-port"),
fips_custom_cert_filename: value_of(&matches, "fips-custom-cert-filename"),
a2_mode: if matches.is_present("a2-mode") {
Some(true)
} else {
None
},
}
}
}
impl<'n> Options for InitClapOptions<'n> {
fn merge_options_and_config(&self, config: Config) -> DeliveryResult<Config> {
let project = try!(project::project_or_from_cwd(&self.project));
let new_config = config
.set_user(&self.user)
.set_server(&self.server)
.set_enterprise(&self.ent)
.set_organization(&self.org)
.set_project(&project)
.set_pipeline(&self.pipeline)
.set_generator(&self.generator)
.set_a2_mode_if_def(self.a2_mode)
.set_config_json(&self.config_json);
fips::merge_fips_options_and_config(
self.fips,
self.fips_git_port,
self.fips_custom_cert_filename,
new_config,
)
}
}
pub fn clap_subcommand<'c>() -> App<'c, 'c> | .args(&pipeline_arg())
.args(&project_specific_args())
.args(&vec![a2_mode_arg()])
}
| {
SubCommand::with_name(SUBCOMMAND_NAME)
.about(
"Initialize a Delivery project \
(and lots more!)",
)
.args(&vec![
config_path_arg(),
no_open_arg(),
project_arg(),
local_arg(),
config_project_arg(),
])
.args_from_usage(
"--generator=[generator] 'Local path or Git repo URL to a \
custom ChefDK build_cookbook generator (default:github)'
--skip-build-cookbook 'Do not create a build cookbook'",
)
.args(&u_e_s_o_args())
.args(&scp_args()) | identifier_body |
metadata_basic.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
#[test]
pub fn new_predicate_named_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"], bytes, uint64))
})
})
}
#[test]
pub fn | () {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})
})
}
#[test]
pub fn predicate_roundtrip() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})?;
let pred = holmes.get_predicate("test_pred")?.unwrap();
assert_eq!(pred.description.as_ref().unwrap(), "This is a test predicate");
assert_eq!(pred.fields[0].name.as_ref().unwrap(), "first");
assert_eq!(pred.fields[0].description.as_ref().unwrap(), "This is the first element");
Ok(())
})
}
#[test]
pub fn named_field_rule() {
single(&|holmes: &mut Engine, core: &mut Core| {
holmes_exec!(holmes, {
predicate!(test_pred([foo string],
uint64,
[bar string]));
predicate!(out_pred(string));
rule!(test_to_out: out_pred(x) <= test_pred {bar = x, foo = ("woo")});
fact!(test_pred("woo", 3, "Right"));
fact!(test_pred("wow", 4, "Wrong"))
})?;
core.run(holmes.quiesce()).unwrap();
let ans = query!(holmes, out_pred(x))?;
assert_eq!(ans, vec![["Right".to_value()]]);
Ok(())
})
}
| new_predicate_doc_all | identifier_name |
metadata_basic.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
#[test]
pub fn new_predicate_named_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_field() |
#[test]
pub fn new_predicate_doc_all() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})
})
}
#[test]
pub fn predicate_roundtrip() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})?;
let pred = holmes.get_predicate("test_pred")?.unwrap();
assert_eq!(pred.description.as_ref().unwrap(), "This is a test predicate");
assert_eq!(pred.fields[0].name.as_ref().unwrap(), "first");
assert_eq!(pred.fields[0].description.as_ref().unwrap(), "This is the first element");
Ok(())
})
}
#[test]
pub fn named_field_rule() {
single(&|holmes: &mut Engine, core: &mut Core| {
holmes_exec!(holmes, {
predicate!(test_pred([foo string],
uint64,
[bar string]));
predicate!(out_pred(string));
rule!(test_to_out: out_pred(x) <= test_pred {bar = x, foo = ("woo")});
fact!(test_pred("woo", 3, "Right"));
fact!(test_pred("wow", 4, "Wrong"))
})?;
core.run(holmes.quiesce()).unwrap();
let ans = query!(holmes, out_pred(x))?;
assert_eq!(ans, vec![["Right".to_value()]]);
Ok(())
})
}
| {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"], bytes, uint64))
})
})
} | identifier_body |
metadata_basic.rs | #[macro_use]
extern crate holmes;
use holmes::simple::*;
#[test]
pub fn new_predicate_named_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_field() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"], bytes, uint64))
})
})
}
#[test]
pub fn new_predicate_doc_all() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate") | })
}
#[test]
pub fn predicate_roundtrip() {
single(&|holmes: &mut Engine, _| {
holmes_exec!(holmes, {
predicate!(test_pred([first string "This is the first element"],
bytes, uint64)
: "This is a test predicate")
})?;
let pred = holmes.get_predicate("test_pred")?.unwrap();
assert_eq!(pred.description.as_ref().unwrap(), "This is a test predicate");
assert_eq!(pred.fields[0].name.as_ref().unwrap(), "first");
assert_eq!(pred.fields[0].description.as_ref().unwrap(), "This is the first element");
Ok(())
})
}
#[test]
pub fn named_field_rule() {
single(&|holmes: &mut Engine, core: &mut Core| {
holmes_exec!(holmes, {
predicate!(test_pred([foo string],
uint64,
[bar string]));
predicate!(out_pred(string));
rule!(test_to_out: out_pred(x) <= test_pred {bar = x, foo = ("woo")});
fact!(test_pred("woo", 3, "Right"));
fact!(test_pred("wow", 4, "Wrong"))
})?;
core.run(holmes.quiesce()).unwrap();
let ans = query!(holmes, out_pred(x))?;
assert_eq!(ans, vec![["Right".to_value()]]);
Ok(())
})
} | }) | random_line_split |
mod.rs | pub mod packet;
use std::net;
use std::io;
use std::time::Duration;
use time;
use protocol::raknet;
macro_rules! check_raknet_packet {
() => {};
}
#[derive(Clone, Debug)]
pub struct ServerInfo {
pub name: String,
pub protocol_version: String,
pub client_version: String,
pub players_count: u32,
pub max_players: u32
}
impl ServerInfo {
pub fn request<A: net::ToSocketAddrs>(address: A) -> io::Result<ServerInfo> {
let mut session = raknet::Session::new("0.0.0.0:0", address)?;
session.send_packet(&raknet::packet::UnconnectedPing1 {
time: time::now().tm_sec as i64 * 1000,
magic: raknet::types::Magic
}.into())?;
match session.receive_packet()? {
raknet::packet::PacketTypes::UnconnectedPong(packet) => ServerInfo::from_string(
&packet.server_info.into()),
_ => Err(io::Error::new(io::ErrorKind::InvalidData, "Unexpected response"))
}
}
pub fn from_string(s: &String) -> io::Result<ServerInfo> {
let error = || io::Error::new(io::ErrorKind::InvalidData, "Invalid server info string");
let mut split = s.split(';');
split.next().ok_or(error())?.to_string(); // skip "MCPE"
Ok(ServerInfo {
name: split.next().ok_or(error())?.to_string(),
protocol_version: split.next().ok_or(error())?.to_string(),
client_version: split.next().ok_or(error())?.to_string(),
players_count: split.next().ok_or(error())?.parse().map_err(|_| error())?,
max_players: split.next().ok_or(error())?.parse().map_err(|_| error())?
})
}
}
pub struct ClientSession {
session: raknet::Session,
guid: i64
}
impl ClientSession {
pub fn new<A: net::ToSocketAddrs>(addr: A) -> io::Result<ClientSession> {
let mut ret = ClientSession {
session: raknet::Session::new("0.0.0.0:0", addr)?,
guid: 0x1111
};
ret.connect()?;
Ok(ret)
}
fn connect(&mut self) -> io::Result<()> | use_security: false
}.into(), raknet::types::Reliability::Reliable)?;
//println!("{:?}", self.session.receive_packet()?);
let listen_addr = self.session.listen_address().clone();
self.session.send_encapsulate(&raknet::packet::ClientHandshake {
client_addr: listen_addr.into(),
internal_id: [listen_addr.into(); 10],
request_time: 0,
time: 0
}.into(), raknet::types::Reliability::Reliable)?;
loop {println!("{:?}", self.session.receive_packet()?)};
Ok(())
}
fn find_mtu(&mut self) -> io::Result<u16> {
for mtu in (1..(1500 - 46 + 1) / 10).rev() {
self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 {
magic: raknet::types::Magic,
protocol_version: 8,
mtu: vec![0; mtu * 10]
}.into())?;
match self.session.receive_packet() {
Ok(raknet::packet::PacketTypes::OfflineConnectionResponse1(packet)) => {
return Ok(packet.mtu as u16)
},
Ok(_) => {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Unexpected response"))
},
_ => ()
}
}
Err(io::Error::new(io::ErrorKind::Other, "Server not response"))
}
}
| {
self.session.set_read_timeout(Some(Duration::from_millis(500)))?;
let mtu = self.find_mtu()?;
self.session.mtu = mtu as usize;
self.session.set_read_timeout(Some(Duration::from_secs(5)))?;
self.session.send_packet(&raknet::packet::OfflineConnectionRequest2 {
magic: raknet::types::Magic,
server_addr: self.session.target_address().into(),
mtu: mtu as i16,
client_guid: self.guid
}.into())?;
println!("{:?}", self.session.receive_packet()?);
self.session.send_encapsulate(&raknet::packet::OnlineConnectionRequest {
guid: self.guid,
time: time::now().tm_sec as i64 * 1000, | identifier_body |
mod.rs | pub mod packet;
use std::net;
use std::io;
use std::time::Duration;
use time;
use protocol::raknet;
macro_rules! check_raknet_packet {
() => {};
}
#[derive(Clone, Debug)]
pub struct ServerInfo {
pub name: String,
pub protocol_version: String,
pub client_version: String,
pub players_count: u32,
pub max_players: u32
}
impl ServerInfo {
pub fn request<A: net::ToSocketAddrs>(address: A) -> io::Result<ServerInfo> {
let mut session = raknet::Session::new("0.0.0.0:0", address)?;
session.send_packet(&raknet::packet::UnconnectedPing1 {
time: time::now().tm_sec as i64 * 1000,
magic: raknet::types::Magic
}.into())?;
match session.receive_packet()? {
raknet::packet::PacketTypes::UnconnectedPong(packet) => ServerInfo::from_string(
&packet.server_info.into()),
_ => Err(io::Error::new(io::ErrorKind::InvalidData, "Unexpected response"))
}
}
pub fn from_string(s: &String) -> io::Result<ServerInfo> {
let error = || io::Error::new(io::ErrorKind::InvalidData, "Invalid server info string");
let mut split = s.split(';');
split.next().ok_or(error())?.to_string(); // skip "MCPE"
Ok(ServerInfo {
name: split.next().ok_or(error())?.to_string(),
protocol_version: split.next().ok_or(error())?.to_string(),
client_version: split.next().ok_or(error())?.to_string(),
players_count: split.next().ok_or(error())?.parse().map_err(|_| error())?,
max_players: split.next().ok_or(error())?.parse().map_err(|_| error())?
})
}
}
pub struct ClientSession {
session: raknet::Session,
guid: i64
}
impl ClientSession {
pub fn new<A: net::ToSocketAddrs>(addr: A) -> io::Result<ClientSession> {
let mut ret = ClientSession {
session: raknet::Session::new("0.0.0.0:0", addr)?,
guid: 0x1111
};
ret.connect()?;
Ok(ret)
}
fn connect(&mut self) -> io::Result<()> {
self.session.set_read_timeout(Some(Duration::from_millis(500)))?;
let mtu = self.find_mtu()?;
self.session.mtu = mtu as usize;
self.session.set_read_timeout(Some(Duration::from_secs(5)))?;
self.session.send_packet(&raknet::packet::OfflineConnectionRequest2 {
magic: raknet::types::Magic,
server_addr: self.session.target_address().into(),
mtu: mtu as i16,
client_guid: self.guid
}.into())?;
println!("{:?}", self.session.receive_packet()?);
self.session.send_encapsulate(&raknet::packet::OnlineConnectionRequest {
guid: self.guid,
time: time::now().tm_sec as i64 * 1000,
use_security: false
}.into(), raknet::types::Reliability::Reliable)?;
//println!("{:?}", self.session.receive_packet()?);
let listen_addr = self.session.listen_address().clone();
self.session.send_encapsulate(&raknet::packet::ClientHandshake {
client_addr: listen_addr.into(),
internal_id: [listen_addr.into(); 10],
request_time: 0,
time: 0
}.into(), raknet::types::Reliability::Reliable)?;
loop {println!("{:?}", self.session.receive_packet()?)};
Ok(())
}
fn | (&mut self) -> io::Result<u16> {
for mtu in (1..(1500 - 46 + 1) / 10).rev() {
self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 {
magic: raknet::types::Magic,
protocol_version: 8,
mtu: vec![0; mtu * 10]
}.into())?;
match self.session.receive_packet() {
Ok(raknet::packet::PacketTypes::OfflineConnectionResponse1(packet)) => {
return Ok(packet.mtu as u16)
},
Ok(_) => {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Unexpected response"))
},
_ => ()
}
}
Err(io::Error::new(io::ErrorKind::Other, "Server not response"))
}
}
| find_mtu | identifier_name |
mod.rs | pub mod packet;
use std::net;
use std::io;
use std::time::Duration;
use time;
use protocol::raknet;
macro_rules! check_raknet_packet {
() => {};
}
#[derive(Clone, Debug)]
pub struct ServerInfo {
pub name: String,
pub protocol_version: String,
pub client_version: String,
pub players_count: u32,
pub max_players: u32
}
impl ServerInfo {
pub fn request<A: net::ToSocketAddrs>(address: A) -> io::Result<ServerInfo> {
let mut session = raknet::Session::new("0.0.0.0:0", address)?;
session.send_packet(&raknet::packet::UnconnectedPing1 {
time: time::now().tm_sec as i64 * 1000,
magic: raknet::types::Magic
}.into())?;
match session.receive_packet()? {
raknet::packet::PacketTypes::UnconnectedPong(packet) => ServerInfo::from_string(
&packet.server_info.into()),
_ => Err(io::Error::new(io::ErrorKind::InvalidData, "Unexpected response"))
}
}
pub fn from_string(s: &String) -> io::Result<ServerInfo> {
let error = || io::Error::new(io::ErrorKind::InvalidData, "Invalid server info string");
let mut split = s.split(';');
split.next().ok_or(error())?.to_string(); // skip "MCPE"
Ok(ServerInfo {
name: split.next().ok_or(error())?.to_string(),
protocol_version: split.next().ok_or(error())?.to_string(),
client_version: split.next().ok_or(error())?.to_string(),
players_count: split.next().ok_or(error())?.parse().map_err(|_| error())?,
max_players: split.next().ok_or(error())?.parse().map_err(|_| error())?
})
}
}
pub struct ClientSession {
session: raknet::Session,
guid: i64
}
impl ClientSession {
pub fn new<A: net::ToSocketAddrs>(addr: A) -> io::Result<ClientSession> {
let mut ret = ClientSession {
session: raknet::Session::new("0.0.0.0:0", addr)?,
guid: 0x1111
};
ret.connect()?;
Ok(ret)
}
fn connect(&mut self) -> io::Result<()> {
self.session.set_read_timeout(Some(Duration::from_millis(500)))?;
let mtu = self.find_mtu()?;
self.session.mtu = mtu as usize;
self.session.set_read_timeout(Some(Duration::from_secs(5)))?;
self.session.send_packet(&raknet::packet::OfflineConnectionRequest2 {
magic: raknet::types::Magic,
server_addr: self.session.target_address().into(),
mtu: mtu as i16,
client_guid: self.guid
}.into())?;
println!("{:?}", self.session.receive_packet()?);
self.session.send_encapsulate(&raknet::packet::OnlineConnectionRequest {
guid: self.guid,
time: time::now().tm_sec as i64 * 1000,
use_security: false
}.into(), raknet::types::Reliability::Reliable)?;
//println!("{:?}", self.session.receive_packet()?);
let listen_addr = self.session.listen_address().clone();
self.session.send_encapsulate(&raknet::packet::ClientHandshake {
client_addr: listen_addr.into(),
internal_id: [listen_addr.into(); 10],
request_time: 0,
time: 0
}.into(), raknet::types::Reliability::Reliable)?;
loop {println!("{:?}", self.session.receive_packet()?)};
Ok(())
}
| for mtu in (1..(1500 - 46 + 1) / 10).rev() {
self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 {
magic: raknet::types::Magic,
protocol_version: 8,
mtu: vec![0; mtu * 10]
}.into())?;
match self.session.receive_packet() {
Ok(raknet::packet::PacketTypes::OfflineConnectionResponse1(packet)) => {
return Ok(packet.mtu as u16)
},
Ok(_) => {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Unexpected response"))
},
_ => ()
}
}
Err(io::Error::new(io::ErrorKind::Other, "Server not response"))
}
} | fn find_mtu(&mut self) -> io::Result<u16> { | random_line_split |
floatobject.rs | use libc::{c_int, c_double};
use object::*;
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
}
#[inline(always)]
pub unsafe fn PyFloat_Check(op : *mut PyObject) -> c_int {
PyObject_TypeCheck(op, &mut PyFloat_Type)
}
#[inline(always)]
pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyFloat_Type) as c_int
}
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub fn PyFloat_GetMax() -> c_double; | pub fn PyFloat_GetInfo() -> *mut PyObject;
pub fn PyFloat_FromString(arg1: *mut PyObject) -> *mut PyObject;
pub fn PyFloat_FromDouble(arg1: c_double) -> *mut PyObject;
pub fn PyFloat_AsDouble(arg1: *mut PyObject) -> c_double;
} | pub fn PyFloat_GetMin() -> c_double; | random_line_split |
floatobject.rs | use libc::{c_int, c_double};
use object::*;
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
}
#[inline(always)]
pub unsafe fn | (op : *mut PyObject) -> c_int {
PyObject_TypeCheck(op, &mut PyFloat_Type)
}
#[inline(always)]
pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyFloat_Type) as c_int
}
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub fn PyFloat_GetMax() -> c_double;
pub fn PyFloat_GetMin() -> c_double;
pub fn PyFloat_GetInfo() -> *mut PyObject;
pub fn PyFloat_FromString(arg1: *mut PyObject) -> *mut PyObject;
pub fn PyFloat_FromDouble(arg1: c_double) -> *mut PyObject;
pub fn PyFloat_AsDouble(arg1: *mut PyObject) -> c_double;
}
| PyFloat_Check | identifier_name |
floatobject.rs | use libc::{c_int, c_double};
use object::*;
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
}
#[inline(always)]
pub unsafe fn PyFloat_Check(op : *mut PyObject) -> c_int |
#[inline(always)]
pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyFloat_Type) as c_int
}
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub fn PyFloat_GetMax() -> c_double;
pub fn PyFloat_GetMin() -> c_double;
pub fn PyFloat_GetInfo() -> *mut PyObject;
pub fn PyFloat_FromString(arg1: *mut PyObject) -> *mut PyObject;
pub fn PyFloat_FromDouble(arg1: c_double) -> *mut PyObject;
pub fn PyFloat_AsDouble(arg1: *mut PyObject) -> c_double;
}
| {
PyObject_TypeCheck(op, &mut PyFloat_Type)
} | identifier_body |
brainruck.rs | use std::os;
use std::str;
use std::fmt;
fn main() {
let args = os::args();
if args.len() == 1 {
fail!("no arguments");
}
run(tokenize(parse_args(args)));
}
fn parse_args(args: ~[~str]) -> ~str {
args[1]
}
fn tokenize(text: ~str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec::new();
for c in text.chars() {
match c {
'>' => {tokens.push(Right)},
'<' => {tokens.push(Left)},
'+' => {tokens.push(Plus)},
'-' => {tokens.push(Minus)},
'.' => {tokens.push(Out)},
',' => {tokens.push(In)},
'[' => {tokens.push(Jump)},
']' => {tokens.push(Loop)},
_ => {}
};
}
return tokens;
}
fn run(tokens: Vec<Token>) {
let mut data: Vec<u8> = Vec::new();
let mut jump_stack: Vec<uint> = Vec::new();
let mut pointer: uint = 0;
let mut token_index: uint = 0;
let token_slice = tokens.as_slice();
data.push(0);
while token_index < tokens.len() {
let token = token_slice[token_index];
match token {
Right => {
pointer += 1;
if pointer == data.len() {
data.push(0);
}
token_index += 1;
},
Left => {
if pointer == 0 {
fail!("index out of bounds");
}
pointer -= 1;
token_index += 1;
},
Plus => {
*data.get_mut(pointer) += 1;
token_index += 1;
},
Minus => {
*data.get_mut(pointer) -= 1;
token_index += 1;
},
Out => {
match str::from_utf8(data.slice(pointer, pointer + 1)) {
Some(c) => {print!("{}", c)},
None => {}
}
token_index += 1;
},
In => {
match std::io::stdin().read_byte() {
Ok(b) => {*data.get_mut(pointer) = b},
Err(e) => {fail!("{}", e)}
}
token_index += 1;
},
Jump => {
// Jump to end of the loop when the value at the pointer is zero.
if *data.get_mut(pointer) == 0 {
let mut jump_count = 0;
loop {
token_index += 1;
if token_index > tokens.len() {
fail!("no matching ]");
}
match token_slice[token_index] {
Loop => {
if jump_count == 0 {
token_index += 1;
break;
} else {
jump_count -= 1;
}
},
Jump => {
jump_count += 1;
},
_ => {}
}
}
} else {
jump_stack.push(token_index);
token_index += 1;
}
},
Loop => {
match jump_stack.pop() {
Some(i) => {token_index = i},
None => {fail!("no matching [")}
}
},
}
}
print!("\n");
}
#[deriving(Clone, Eq, TotalEq)]
enum Token {
Right,
Left,
Plus,
Minus,
Out,
In,
Jump,
Loop
}
impl fmt::Show for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", match *self {
Right => '>',
Left => '<',
Plus => '+',
Minus => '-',
Out => '.',
In => ',',
Jump => '[',
Loop => ']',
})
}
}
#[test]
fn testTokenizer() |
#[test]
fn testArgParser() {
assert_eq!(parse_args(["brainruck".to_owned(), "><+-.,[]".to_owned()].to_owned()),
"><+-.,[]".to_owned());
}
| {
// Check the tokenizer is getting the right outputs.
assert_eq!(tokenize("><+-.,[]".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
// Make sure junk is ignored.
assert_eq!(tokenize(">a<b+c-d. ,1[2]3 ".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
} | identifier_body |
brainruck.rs | use std::os;
use std::str;
use std::fmt;
fn main() {
let args = os::args();
if args.len() == 1 {
fail!("no arguments");
}
run(tokenize(parse_args(args)));
}
fn parse_args(args: ~[~str]) -> ~str {
args[1]
}
fn tokenize(text: ~str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec::new();
for c in text.chars() {
match c {
'>' => {tokens.push(Right)},
'<' => {tokens.push(Left)},
'+' => {tokens.push(Plus)},
'-' => {tokens.push(Minus)},
'.' => {tokens.push(Out)},
',' => {tokens.push(In)},
'[' => {tokens.push(Jump)},
']' => {tokens.push(Loop)},
_ => {}
};
}
return tokens;
}
fn run(tokens: Vec<Token>) {
let mut data: Vec<u8> = Vec::new();
let mut jump_stack: Vec<uint> = Vec::new();
let mut pointer: uint = 0;
let mut token_index: uint = 0;
let token_slice = tokens.as_slice();
data.push(0);
while token_index < tokens.len() {
let token = token_slice[token_index];
match token {
Right => {
pointer += 1;
if pointer == data.len() {
data.push(0);
}
token_index += 1;
},
Left => {
if pointer == 0 {
fail!("index out of bounds");
}
pointer -= 1;
token_index += 1;
},
Plus => {
*data.get_mut(pointer) += 1;
token_index += 1;
},
Minus => {
*data.get_mut(pointer) -= 1;
token_index += 1;
},
Out => {
match str::from_utf8(data.slice(pointer, pointer + 1)) {
Some(c) => {print!("{}", c)},
None => {}
}
token_index += 1;
},
In => {
match std::io::stdin().read_byte() {
Ok(b) => {*data.get_mut(pointer) = b},
Err(e) => {fail!("{}", e)}
}
token_index += 1;
},
Jump => {
// Jump to end of the loop when the value at the pointer is zero.
if *data.get_mut(pointer) == 0 {
let mut jump_count = 0;
loop {
token_index += 1;
if token_index > tokens.len() {
fail!("no matching ]");
}
match token_slice[token_index] {
Loop => {
if jump_count == 0 {
token_index += 1;
break;
} else {
jump_count -= 1;
}
},
Jump => {
jump_count += 1;
},
_ => {}
}
}
} else {
jump_stack.push(token_index);
token_index += 1;
}
},
Loop => {
match jump_stack.pop() {
Some(i) => {token_index = i},
None => {fail!("no matching [")}
}
},
}
}
print!("\n");
}
#[deriving(Clone, Eq, TotalEq)]
enum | {
Right,
Left,
Plus,
Minus,
Out,
In,
Jump,
Loop
}
impl fmt::Show for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", match *self {
Right => '>',
Left => '<',
Plus => '+',
Minus => '-',
Out => '.',
In => ',',
Jump => '[',
Loop => ']',
})
}
}
#[test]
fn testTokenizer() {
// Check the tokenizer is getting the right outputs.
assert_eq!(tokenize("><+-.,[]".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
// Make sure junk is ignored.
assert_eq!(tokenize(">a<b+c-d.,1[2]3 ".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
}
#[test]
fn testArgParser() {
assert_eq!(parse_args(["brainruck".to_owned(), "><+-.,[]".to_owned()].to_owned()),
"><+-.,[]".to_owned());
}
| Token | identifier_name |
brainruck.rs | use std::os;
use std::str;
use std::fmt;
fn main() {
let args = os::args();
if args.len() == 1 {
fail!("no arguments");
}
run(tokenize(parse_args(args)));
}
fn parse_args(args: ~[~str]) -> ~str {
args[1]
}
fn tokenize(text: ~str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec::new();
for c in text.chars() {
match c {
'>' => {tokens.push(Right)},
'<' => {tokens.push(Left)},
'+' => {tokens.push(Plus)},
'-' => {tokens.push(Minus)},
'.' => {tokens.push(Out)},
',' => {tokens.push(In)},
'[' => {tokens.push(Jump)},
']' => {tokens.push(Loop)},
_ => {}
};
}
return tokens;
}
fn run(tokens: Vec<Token>) {
let mut data: Vec<u8> = Vec::new();
let mut jump_stack: Vec<uint> = Vec::new();
let mut pointer: uint = 0;
let mut token_index: uint = 0;
let token_slice = tokens.as_slice();
data.push(0);
while token_index < tokens.len() {
let token = token_slice[token_index];
match token {
Right => {
pointer += 1;
if pointer == data.len() {
data.push(0);
}
token_index += 1;
},
Left => {
if pointer == 0 {
fail!("index out of bounds");
}
pointer -= 1;
token_index += 1;
},
Plus => {
*data.get_mut(pointer) += 1;
token_index += 1;
},
Minus => {
*data.get_mut(pointer) -= 1;
token_index += 1;
},
Out => {
match str::from_utf8(data.slice(pointer, pointer + 1)) {
Some(c) => {print!("{}", c)}, |
In => {
match std::io::stdin().read_byte() {
Ok(b) => {*data.get_mut(pointer) = b},
Err(e) => {fail!("{}", e)}
}
token_index += 1;
},
Jump => {
// Jump to end of the loop when the value at the pointer is zero.
if *data.get_mut(pointer) == 0 {
let mut jump_count = 0;
loop {
token_index += 1;
if token_index > tokens.len() {
fail!("no matching ]");
}
match token_slice[token_index] {
Loop => {
if jump_count == 0 {
token_index += 1;
break;
} else {
jump_count -= 1;
}
},
Jump => {
jump_count += 1;
},
_ => {}
}
}
} else {
jump_stack.push(token_index);
token_index += 1;
}
},
Loop => {
match jump_stack.pop() {
Some(i) => {token_index = i},
None => {fail!("no matching [")}
}
},
}
}
print!("\n");
}
#[deriving(Clone, Eq, TotalEq)]
enum Token {
Right,
Left,
Plus,
Minus,
Out,
In,
Jump,
Loop
}
impl fmt::Show for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", match *self {
Right => '>',
Left => '<',
Plus => '+',
Minus => '-',
Out => '.',
In => ',',
Jump => '[',
Loop => ']',
})
}
}
#[test]
fn testTokenizer() {
// Check the tokenizer is getting the right outputs.
assert_eq!(tokenize("><+-.,[]".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
// Make sure junk is ignored.
assert_eq!(tokenize(">a<b+c-d.,1[2]3 ".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
}
#[test]
fn testArgParser() {
assert_eq!(parse_args(["brainruck".to_owned(), "><+-.,[]".to_owned()].to_owned()),
"><+-.,[]".to_owned());
} | None => {}
}
token_index += 1;
}, | random_line_split |
object-lifetime-default-elision.rs | // Test various cases where the old rules under lifetime elision
// yield slightly different results than the new rules.
#![allow(dead_code)]
trait SomeTrait {
fn dummy(&self) { }
}
struct SomeStruct<'a> {
r: Box<dyn SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worrying about whether a
// move out would actually be legal
loop { }
}
fn | <'a>(ss: &'a Box<dyn SomeTrait>) -> Box<dyn SomeTrait> {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a Box<SomeTrait+'b>) -> Box<SomeTrait+'a>
//
// Under new rules the result is:
//
// for<'a> fn(&'a Box<SomeTrait+'static>) -> Box<SomeTrait+'static>
//
// Therefore, no type error.
deref(ss)
}
fn load1(ss: &dyn SomeTrait) -> &dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a (SomeTrait+'b)) -> &'a (SomeTrait+'a)
//
// Under new rules the result is:
//
// for<'a> fn(&'a (SomeTrait+'a)) -> &'a (SomeTrait+'a)
//
// In both cases, returning `ss` is legal.
ss
}
fn load2<'a>(ss: &'a dyn SomeTrait) -> &dyn SomeTrait {
// Same as `load1` but with an explicit name thrown in for fun.
ss
}
fn load3<'a,'b>(ss: &'a dyn SomeTrait) -> &'b dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTrait+'a)
//
// Based on the input/output types, the compiler could infer that
// 'c : 'a
// 'b : 'a
// must hold, and therefore it permitted `&'a (Sometrait+'c)` to be
// coerced to `&'b (SomeTrait+'a)`.
//
// Under the newer defaults, though, we get:
//
// for<'a,'b> fn(&'a (SomeTrait+'a)) -> &'b (SomeTrait+'b)
//
// which fails to type check.
ss
//~^ ERROR cannot infer
//~| ERROR cannot infer
}
fn main() {
}
| load0 | identifier_name |
object-lifetime-default-elision.rs | // Test various cases where the old rules under lifetime elision
// yield slightly different results than the new rules. |
#![allow(dead_code)]
trait SomeTrait {
fn dummy(&self) { }
}
struct SomeStruct<'a> {
r: Box<dyn SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worrying about whether a
// move out would actually be legal
loop { }
}
fn load0<'a>(ss: &'a Box<dyn SomeTrait>) -> Box<dyn SomeTrait> {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a Box<SomeTrait+'b>) -> Box<SomeTrait+'a>
//
// Under new rules the result is:
//
// for<'a> fn(&'a Box<SomeTrait+'static>) -> Box<SomeTrait+'static>
//
// Therefore, no type error.
deref(ss)
}
fn load1(ss: &dyn SomeTrait) -> &dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a (SomeTrait+'b)) -> &'a (SomeTrait+'a)
//
// Under new rules the result is:
//
// for<'a> fn(&'a (SomeTrait+'a)) -> &'a (SomeTrait+'a)
//
// In both cases, returning `ss` is legal.
ss
}
fn load2<'a>(ss: &'a dyn SomeTrait) -> &dyn SomeTrait {
// Same as `load1` but with an explicit name thrown in for fun.
ss
}
fn load3<'a,'b>(ss: &'a dyn SomeTrait) -> &'b dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTrait+'a)
//
// Based on the input/output types, the compiler could infer that
// 'c : 'a
// 'b : 'a
// must hold, and therefore it permitted `&'a (Sometrait+'c)` to be
// coerced to `&'b (SomeTrait+'a)`.
//
// Under the newer defaults, though, we get:
//
// for<'a,'b> fn(&'a (SomeTrait+'a)) -> &'b (SomeTrait+'b)
//
// which fails to type check.
ss
//~^ ERROR cannot infer
//~| ERROR cannot infer
}
fn main() {
} | random_line_split | |
object-lifetime-default-elision.rs | // Test various cases where the old rules under lifetime elision
// yield slightly different results than the new rules.
#![allow(dead_code)]
trait SomeTrait {
fn dummy(&self) { }
}
struct SomeStruct<'a> {
r: Box<dyn SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worrying about whether a
// move out would actually be legal
loop { }
}
fn load0<'a>(ss: &'a Box<dyn SomeTrait>) -> Box<dyn SomeTrait> {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a Box<SomeTrait+'b>) -> Box<SomeTrait+'a>
//
// Under new rules the result is:
//
// for<'a> fn(&'a Box<SomeTrait+'static>) -> Box<SomeTrait+'static>
//
// Therefore, no type error.
deref(ss)
}
fn load1(ss: &dyn SomeTrait) -> &dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a (SomeTrait+'b)) -> &'a (SomeTrait+'a)
//
// Under new rules the result is:
//
// for<'a> fn(&'a (SomeTrait+'a)) -> &'a (SomeTrait+'a)
//
// In both cases, returning `ss` is legal.
ss
}
fn load2<'a>(ss: &'a dyn SomeTrait) -> &dyn SomeTrait |
fn load3<'a,'b>(ss: &'a dyn SomeTrait) -> &'b dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTrait+'a)
//
// Based on the input/output types, the compiler could infer that
// 'c : 'a
// 'b : 'a
// must hold, and therefore it permitted `&'a (Sometrait+'c)` to be
// coerced to `&'b (SomeTrait+'a)`.
//
// Under the newer defaults, though, we get:
//
// for<'a,'b> fn(&'a (SomeTrait+'a)) -> &'b (SomeTrait+'b)
//
// which fails to type check.
ss
//~^ ERROR cannot infer
//~| ERROR cannot infer
}
fn main() {
}
| {
// Same as `load1` but with an explicit name thrown in for fun.
ss
} | identifier_body |
uint.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.
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::add_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::add_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::sub_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::sub_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::mul_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::mul_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
pub fn bswap(x: uint) -> uint {
::i32::bswap(x as i32) as uint
}
#[cfg(target_word_size = "64")]
pub fn bswap(x: uint) -> uint {
::i64::bswap(x as u64) as uint
}
#[cfg(target_endian = "big")]
pub fn to_be(x: uint) -> uint |
#[cfg(target_endian = "little")]
pub fn to_be(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "big")]
pub fn to_le(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "little")]
pub fn to_le(x: uint) -> uint {
x
}
| {
x
} | identifier_body |
uint.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.
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::add_with_overflow(x as u32, y as u32);
(a as uint, b) | #[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::add_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::sub_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::sub_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::mul_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::mul_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
pub fn bswap(x: uint) -> uint {
::i32::bswap(x as i32) as uint
}
#[cfg(target_word_size = "64")]
pub fn bswap(x: uint) -> uint {
::i64::bswap(x as u64) as uint
}
#[cfg(target_endian = "big")]
pub fn to_be(x: uint) -> uint {
x
}
#[cfg(target_endian = "little")]
pub fn to_be(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "big")]
pub fn to_le(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "little")]
pub fn to_le(x: uint) -> uint {
x
} | }
#[cfg(target_word_size = "64")] | random_line_split |
uint.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.
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::add_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::add_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn | (x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::sub_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::sub_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::mul_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn mul_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::mul_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
pub fn bswap(x: uint) -> uint {
::i32::bswap(x as i32) as uint
}
#[cfg(target_word_size = "64")]
pub fn bswap(x: uint) -> uint {
::i64::bswap(x as u64) as uint
}
#[cfg(target_endian = "big")]
pub fn to_be(x: uint) -> uint {
x
}
#[cfg(target_endian = "little")]
pub fn to_be(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "big")]
pub fn to_le(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "little")]
pub fn to_le(x: uint) -> uint {
x
}
| sub_with_overflow | identifier_name |
reward.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Builds the blinded output and related signature proof for the block
//! reward.
use crate::consensus::reward;
use crate::core::{KernelFeatures, Output, OutputFeatures, TxKernel};
use crate::libtx::error::Error;
use crate::libtx::{
aggsig,
proof::{self, ProofBuild},
};
use keychain::{Identifier, Keychain, SwitchCommitmentType};
use util::{secp, static_secp_instance};
/// output a reward output
pub fn output<K, B>(
keychain: &K,
builder: &B,
key_id: &Identifier,
fees: u64,
test_mode: bool,
) -> Result<(Output, TxKernel), Error>
where
K: Keychain,
B: ProofBuild,
{
let value = reward(fees);
// TODO: proper support for different switch commitment schemes
let switch = SwitchCommitmentType::Regular;
let commit = keychain.commit(value, key_id, switch)?;
trace!("Block reward - Pedersen Commit is: {:?}", commit,);
let proof = proof::create(keychain, builder, value, key_id, switch, commit, None)?;
let output = Output::new(OutputFeatures::Coinbase, commit, proof);
let secp = static_secp_instance();
let secp = secp.lock();
let over_commit = secp.commit_value(reward(fees))?;
let out_commit = output.commitment();
let excess = secp.commit_sum(vec![out_commit], vec![over_commit])?;
let pubkey = excess.to_pubkey(&secp)?;
let features = KernelFeatures::Coinbase;
let msg = features.kernel_sig_msg()?;
let sig = match test_mode {
true => {
let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?;
aggsig::sign_from_key_id(
&secp,
keychain,
&msg,
value,
&key_id,
Some(&test_nonce),
Some(&pubkey),
)?
}
false => {
aggsig::sign_from_key_id(&secp, keychain, &msg, value, &key_id, None, Some(&pubkey))?
}
};
let kernel = TxKernel {
features: KernelFeatures::Coinbase,
excess,
excess_sig: sig,
};
Ok((output, kernel))
} | // Copyright 2021 The Grin Developers
// | random_line_split | |
reward.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Builds the blinded output and related signature proof for the block
//! reward.
use crate::consensus::reward;
use crate::core::{KernelFeatures, Output, OutputFeatures, TxKernel};
use crate::libtx::error::Error;
use crate::libtx::{
aggsig,
proof::{self, ProofBuild},
};
use keychain::{Identifier, Keychain, SwitchCommitmentType};
use util::{secp, static_secp_instance};
/// output a reward output
pub fn | <K, B>(
keychain: &K,
builder: &B,
key_id: &Identifier,
fees: u64,
test_mode: bool,
) -> Result<(Output, TxKernel), Error>
where
K: Keychain,
B: ProofBuild,
{
let value = reward(fees);
// TODO: proper support for different switch commitment schemes
let switch = SwitchCommitmentType::Regular;
let commit = keychain.commit(value, key_id, switch)?;
trace!("Block reward - Pedersen Commit is: {:?}", commit,);
let proof = proof::create(keychain, builder, value, key_id, switch, commit, None)?;
let output = Output::new(OutputFeatures::Coinbase, commit, proof);
let secp = static_secp_instance();
let secp = secp.lock();
let over_commit = secp.commit_value(reward(fees))?;
let out_commit = output.commitment();
let excess = secp.commit_sum(vec![out_commit], vec![over_commit])?;
let pubkey = excess.to_pubkey(&secp)?;
let features = KernelFeatures::Coinbase;
let msg = features.kernel_sig_msg()?;
let sig = match test_mode {
true => {
let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?;
aggsig::sign_from_key_id(
&secp,
keychain,
&msg,
value,
&key_id,
Some(&test_nonce),
Some(&pubkey),
)?
}
false => {
aggsig::sign_from_key_id(&secp, keychain, &msg, value, &key_id, None, Some(&pubkey))?
}
};
let kernel = TxKernel {
features: KernelFeatures::Coinbase,
excess,
excess_sig: sig,
};
Ok((output, kernel))
}
| output | identifier_name |
reward.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Builds the blinded output and related signature proof for the block
//! reward.
use crate::consensus::reward;
use crate::core::{KernelFeatures, Output, OutputFeatures, TxKernel};
use crate::libtx::error::Error;
use crate::libtx::{
aggsig,
proof::{self, ProofBuild},
};
use keychain::{Identifier, Keychain, SwitchCommitmentType};
use util::{secp, static_secp_instance};
/// output a reward output
pub fn output<K, B>(
keychain: &K,
builder: &B,
key_id: &Identifier,
fees: u64,
test_mode: bool,
) -> Result<(Output, TxKernel), Error>
where
K: Keychain,
B: ProofBuild,
| let msg = features.kernel_sig_msg()?;
let sig = match test_mode {
true => {
let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?;
aggsig::sign_from_key_id(
&secp,
keychain,
&msg,
value,
&key_id,
Some(&test_nonce),
Some(&pubkey),
)?
}
false => {
aggsig::sign_from_key_id(&secp, keychain, &msg, value, &key_id, None, Some(&pubkey))?
}
};
let kernel = TxKernel {
features: KernelFeatures::Coinbase,
excess,
excess_sig: sig,
};
Ok((output, kernel))
}
| {
let value = reward(fees);
// TODO: proper support for different switch commitment schemes
let switch = SwitchCommitmentType::Regular;
let commit = keychain.commit(value, key_id, switch)?;
trace!("Block reward - Pedersen Commit is: {:?}", commit,);
let proof = proof::create(keychain, builder, value, key_id, switch, commit, None)?;
let output = Output::new(OutputFeatures::Coinbase, commit, proof);
let secp = static_secp_instance();
let secp = secp.lock();
let over_commit = secp.commit_value(reward(fees))?;
let out_commit = output.commitment();
let excess = secp.commit_sum(vec![out_commit], vec![over_commit])?;
let pubkey = excess.to_pubkey(&secp)?;
let features = KernelFeatures::Coinbase; | identifier_body |
reward.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Builds the blinded output and related signature proof for the block
//! reward.
use crate::consensus::reward;
use crate::core::{KernelFeatures, Output, OutputFeatures, TxKernel};
use crate::libtx::error::Error;
use crate::libtx::{
aggsig,
proof::{self, ProofBuild},
};
use keychain::{Identifier, Keychain, SwitchCommitmentType};
use util::{secp, static_secp_instance};
/// output a reward output
pub fn output<K, B>(
keychain: &K,
builder: &B,
key_id: &Identifier,
fees: u64,
test_mode: bool,
) -> Result<(Output, TxKernel), Error>
where
K: Keychain,
B: ProofBuild,
{
let value = reward(fees);
// TODO: proper support for different switch commitment schemes
let switch = SwitchCommitmentType::Regular;
let commit = keychain.commit(value, key_id, switch)?;
trace!("Block reward - Pedersen Commit is: {:?}", commit,);
let proof = proof::create(keychain, builder, value, key_id, switch, commit, None)?;
let output = Output::new(OutputFeatures::Coinbase, commit, proof);
let secp = static_secp_instance();
let secp = secp.lock();
let over_commit = secp.commit_value(reward(fees))?;
let out_commit = output.commitment();
let excess = secp.commit_sum(vec![out_commit], vec![over_commit])?;
let pubkey = excess.to_pubkey(&secp)?;
let features = KernelFeatures::Coinbase;
let msg = features.kernel_sig_msg()?;
let sig = match test_mode {
true => |
false => {
aggsig::sign_from_key_id(&secp, keychain, &msg, value, &key_id, None, Some(&pubkey))?
}
};
let kernel = TxKernel {
features: KernelFeatures::Coinbase,
excess,
excess_sig: sig,
};
Ok((output, kernel))
}
| {
let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?;
aggsig::sign_from_key_id(
&secp,
keychain,
&msg,
value,
&key_id,
Some(&test_nonce),
Some(&pubkey),
)?
} | conditional_block |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
}
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len() == index {
return
}
for record in ds.view_records(view) {
println!("{}: {}", index, record.0.some_record_meta());
}
view.add_index(index);
test2(ds, view, index + 1)
}
fn | () {
println!("Hello, API!");
let ds = data::get_data();
println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.target_count());
for record in ds.records() {
println!("{:?}", record);
}
for record in ds.view_records(&api::DataSetView::new(vec![0])) {
println!("{:?}", record);
}
test(&ds);
test2(&ds, &mut api::DataSetView::empty(), 0);
}
| main | identifier_name |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
}
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len() == index |
for record in ds.view_records(view) {
println!("{}: {}", index, record.0.some_record_meta());
}
view.add_index(index);
test2(ds, view, index + 1)
}
fn main() {
println!("Hello, API!");
let ds = data::get_data();
println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.target_count());
for record in ds.records() {
println!("{:?}", record);
}
for record in ds.view_records(&api::DataSetView::new(vec![0])) {
println!("{:?}", record);
}
test(&ds);
test2(&ds, &mut api::DataSetView::empty(), 0);
}
| {
return
} | conditional_block |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) |
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len() == index {
return
}
for record in ds.view_records(view) {
println!("{}: {}", index, record.0.some_record_meta());
}
view.add_index(index);
test2(ds, view, index + 1)
}
fn main() {
println!("Hello, API!");
let ds = data::get_data();
println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.target_count());
for record in ds.records() {
println!("{:?}", record);
}
for record in ds.view_records(&api::DataSetView::new(vec![0])) {
println!("{:?}", record);
}
test(&ds);
test2(&ds, &mut api::DataSetView::empty(), 0);
}
| {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
} | identifier_body |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
}
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len() == index {
return
}
for record in ds.view_records(view) {
println!("{}: {}", index, record.0.some_record_meta());
}
view.add_index(index);
test2(ds, view, index + 1)
}
fn main() {
println!("Hello, API!");
let ds = data::get_data();
println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.target_count());
for record in ds.records() {
println!("{:?}", record);
}
for record in ds.view_records(&api::DataSetView::new(vec![0])) {
println!("{:?}", record);
}
test(&ds); | test2(&ds, &mut api::DataSetView::empty(), 0);
} | random_line_split | |
mod.rs | //! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position
//! alongside information about each of the moves.
pub mod root_moves_list;
use std::cmp::Ordering as CmpOrder;
use pleco::core::score::*;
use pleco::BitMove; |
/// Keeps track of information of a move for the position to be searched.
#[derive(Copy, Clone,Eq)]
pub struct RootMove {
pub score: i32,
pub prev_score: i32,
pub bit_move: BitMove,
pub depth_reached: i16,
}
impl RootMove {
/// Creates a new `RootMove`.
#[inline]
pub fn new(bit_move: BitMove) -> Self {
RootMove {
bit_move,
score: NEG_INFINITE as i32,
prev_score: NEG_INFINITE as i32,
depth_reached: 0,
}
}
/// Places the current score into the previous_score field, and then updates
/// the score and depth.
#[inline]
pub fn rollback_insert(&mut self, score: i32, depth: i16) {
self.prev_score = self.score;
self.score = score;
self.depth_reached = depth;
}
/// Inserts a score and depth.
#[inline]
pub fn insert(&mut self, score: i32, depth: i16) {
self.score = score;
self.depth_reached = depth;
}
/// Places the current score in the previous score.
#[inline]
pub fn rollback(&mut self) {
self.prev_score = self.score;
}
}
// Moves with higher score for a higher depth are less
impl Ord for RootMove {
#[inline]
fn cmp(&self, other: &RootMove) -> CmpOrder {
let value_diff = self.score - other.score;
if value_diff == 0 {
let prev_value_diff = self.prev_score - other.prev_score;
if prev_value_diff == 0 {
return CmpOrder::Equal;
} else if prev_value_diff > 0 {
return CmpOrder::Less;
}
} else if value_diff > 0 {
return CmpOrder::Less;
}
CmpOrder::Greater
}
}
impl PartialOrd for RootMove {
fn partial_cmp(&self, other: &RootMove) -> Option<CmpOrder> {
Some(self.cmp(other))
}
}
impl PartialEq for RootMove {
fn eq(&self, other: &RootMove) -> bool {
self.score == other.score && self.prev_score == other.prev_score
}
} |
// 250 as this fits into 64 byte cache lines easily.
const MAX_MOVES: usize = 250; | random_line_split |
mod.rs | //! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position
//! alongside information about each of the moves.
pub mod root_moves_list;
use std::cmp::Ordering as CmpOrder;
use pleco::core::score::*;
use pleco::BitMove;
// 250 as this fits into 64 byte cache lines easily.
const MAX_MOVES: usize = 250;
/// Keeps track of information of a move for the position to be searched.
#[derive(Copy, Clone,Eq)]
pub struct RootMove {
pub score: i32,
pub prev_score: i32,
pub bit_move: BitMove,
pub depth_reached: i16,
}
impl RootMove {
/// Creates a new `RootMove`.
#[inline]
pub fn | (bit_move: BitMove) -> Self {
RootMove {
bit_move,
score: NEG_INFINITE as i32,
prev_score: NEG_INFINITE as i32,
depth_reached: 0,
}
}
/// Places the current score into the previous_score field, and then updates
/// the score and depth.
#[inline]
pub fn rollback_insert(&mut self, score: i32, depth: i16) {
self.prev_score = self.score;
self.score = score;
self.depth_reached = depth;
}
/// Inserts a score and depth.
#[inline]
pub fn insert(&mut self, score: i32, depth: i16) {
self.score = score;
self.depth_reached = depth;
}
/// Places the current score in the previous score.
#[inline]
pub fn rollback(&mut self) {
self.prev_score = self.score;
}
}
// Moves with higher score for a higher depth are less
impl Ord for RootMove {
#[inline]
fn cmp(&self, other: &RootMove) -> CmpOrder {
let value_diff = self.score - other.score;
if value_diff == 0 {
let prev_value_diff = self.prev_score - other.prev_score;
if prev_value_diff == 0 {
return CmpOrder::Equal;
} else if prev_value_diff > 0 {
return CmpOrder::Less;
}
} else if value_diff > 0 {
return CmpOrder::Less;
}
CmpOrder::Greater
}
}
impl PartialOrd for RootMove {
fn partial_cmp(&self, other: &RootMove) -> Option<CmpOrder> {
Some(self.cmp(other))
}
}
impl PartialEq for RootMove {
fn eq(&self, other: &RootMove) -> bool {
self.score == other.score && self.prev_score == other.prev_score
}
} | new | identifier_name |
mod.rs | //! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position
//! alongside information about each of the moves.
pub mod root_moves_list;
use std::cmp::Ordering as CmpOrder;
use pleco::core::score::*;
use pleco::BitMove;
// 250 as this fits into 64 byte cache lines easily.
const MAX_MOVES: usize = 250;
/// Keeps track of information of a move for the position to be searched.
#[derive(Copy, Clone,Eq)]
pub struct RootMove {
pub score: i32,
pub prev_score: i32,
pub bit_move: BitMove,
pub depth_reached: i16,
}
impl RootMove {
/// Creates a new `RootMove`.
#[inline]
pub fn new(bit_move: BitMove) -> Self {
RootMove {
bit_move,
score: NEG_INFINITE as i32,
prev_score: NEG_INFINITE as i32,
depth_reached: 0,
}
}
/// Places the current score into the previous_score field, and then updates
/// the score and depth.
#[inline]
pub fn rollback_insert(&mut self, score: i32, depth: i16) {
self.prev_score = self.score;
self.score = score;
self.depth_reached = depth;
}
/// Inserts a score and depth.
#[inline]
pub fn insert(&mut self, score: i32, depth: i16) {
self.score = score;
self.depth_reached = depth;
}
/// Places the current score in the previous score.
#[inline]
pub fn rollback(&mut self) {
self.prev_score = self.score;
}
}
// Moves with higher score for a higher depth are less
impl Ord for RootMove {
#[inline]
fn cmp(&self, other: &RootMove) -> CmpOrder {
let value_diff = self.score - other.score;
if value_diff == 0 {
let prev_value_diff = self.prev_score - other.prev_score;
if prev_value_diff == 0 {
return CmpOrder::Equal;
} else if prev_value_diff > 0 {
return CmpOrder::Less;
}
} else if value_diff > 0 |
CmpOrder::Greater
}
}
impl PartialOrd for RootMove {
fn partial_cmp(&self, other: &RootMove) -> Option<CmpOrder> {
Some(self.cmp(other))
}
}
impl PartialEq for RootMove {
fn eq(&self, other: &RootMove) -> bool {
self.score == other.score && self.prev_score == other.prev_score
}
} | {
return CmpOrder::Less;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.