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 |
---|---|---|---|---|
tags.rs
|
use super::util;
use anyhow::{anyhow, Result};
use std::io::{self, Write};
use std::path::Path;
use std::time::Instant;
use std::{fs, str};
use tree_sitter_loader::Loader;
use tree_sitter_tags::TagsContext;
pub fn generate_tags(
loader: &Loader,
scope: Option<&str>,
paths: &[String],
quiet: bool,
time: bool,
) -> Result<()>
|
None => {
eprintln!("No language found for path {:?}", path);
continue;
}
},
};
if let Some(tags_config) = language_config.tags_config(language)? {
let indent;
if paths.len() > 1 {
if!quiet {
writeln!(&mut stdout, "{}", path.to_string_lossy())?;
}
indent = "\t"
} else {
indent = "";
};
let source = fs::read(path)?;
let t0 = Instant::now();
for tag in context
.generate_tags(tags_config, &source, Some(&cancellation_flag))?
.0
{
let tag = tag?;
if!quiet {
write!(
&mut stdout,
"{}{:<10}\t | {:<8}\t{} {} - {} `{}`",
indent,
str::from_utf8(&source[tag.name_range]).unwrap_or(""),
&tags_config.syntax_type_name(tag.syntax_type_id),
if tag.is_definition { "def" } else { "ref" },
tag.span.start,
tag.span.end,
str::from_utf8(&source[tag.line_range]).unwrap_or(""),
)?;
if let Some(docs) = tag.docs {
if docs.len() > 120 {
write!(&mut stdout, "\t{:?}...", docs.get(0..120).unwrap_or(""))?;
} else {
write!(&mut stdout, "\t{:?}", &docs)?;
}
}
writeln!(&mut stdout, "")?;
}
}
if time {
writeln!(
&mut stdout,
"{}time: {}ms",
indent,
t0.elapsed().as_millis(),
)?;
}
} else {
eprintln!("No tags config found for path {:?}", path);
}
}
Ok(())
}
|
{
let mut lang = None;
if let Some(scope) = scope {
lang = loader.language_configuration_for_scope(scope)?;
if lang.is_none() {
return Err(anyhow!("Unknown scope '{}'", scope));
}
}
let mut context = TagsContext::new();
let cancellation_flag = util::cancel_on_stdin();
let stdout = io::stdout();
let mut stdout = stdout.lock();
for path in paths {
let path = Path::new(&path);
let (language, language_config) = match lang {
Some(v) => v,
None => match loader.language_configuration_for_file_name(path)? {
Some(v) => v,
|
identifier_body
|
print_completion_loop.rs
|
// // use async_std::prelude::*;
// use async_std::fs;
// use std::sync::Arc;
// use eyre::{
// eyre,
// Result,
// // Context as _,
// };
// // use bytes::BufMut;
// use futures::stream::{StreamExt};
// use crate::models::VersionedModel;
// use crate::print_queue::tasks::{
// Task,
// // TaskStatus,
// TaskContent,
// Part,
// Package,
// };
// use crate::machine::models::{
// Machine,
// MachineStatus,
// // Printing,
// };
// pub async fn run_print_completion_loop(
// ctx: Arc<crate::Context>,
// ) -> Result<()> {
// let mut task_changes = Task::watch_all_changes(&ctx.db)?;
// loop {
// use crate::models::versioned_model::Change;
// let change = task_changes.next().await
// .ok_or_else(|| eyre!("print loop task stream unexpectedly ended"))??;
// let was_pending = change.previous
// .as_ref()
// .map(|t| t.status.is_pending())
// .unwrap_or(true);
// match change {
// // Handle settled tasks
// Change { next: Some(task),.. } if was_pending && task.status.is_settled() => {
// if task.is_print() && task.status.was_successful() {
// let config = ctx.machine_config.load();
// let automatic_printing = config.core_plugin()?.model.automatic_printing;
// handle_print_completion(
// &ctx,
// automatic_printing,
// &task,
// ).await?;
// }
// // Delete the settled task
// Task::remove(&ctx.db, task.id)?;
// ctx.db.flush_async().await?;
// }
// Change { previous: Some(task), next: None,.. } => {
// // clean up files on task deletion
// if let TaskContent::FilePath(file_path) = task.content {
|
// }
// _ => {}
// }
// }
// }
// async fn handle_print_completion(
// ctx: &Arc<crate::Context>,
// automatic_printing: bool,
// task: &Task,
// ) -> Result<()> {
// let print = task.print.as_ref().ok_or_else(||
// eyre!("Missing print for task: {}", task.id)
// )?;
// // Parts printed update
// Part::get_and_update(&ctx.db, print.part_id, |mut part| {
// part.printed += 1;
// part
// })?;
// // Parts + Package deletion
// let package = Package::find(&ctx.db, |package| {
// package.id == print.package_id
// })?;
// let parts = Part::filter(&ctx.db, |part| {
// part.package_id == print.package_id
// })?;
// if package.started_final_print(&parts) {
// Package::remove(&ctx.db, package.id)?;
// for part in parts {
// Part::remove(&ctx.db, part.id)?;
// }
// }
// Ok(())
// }
|
// fs::remove_file(file_path).await?;
// }
|
random_line_split
|
issue-2631-b.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
|
// 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(managed_boxes)];
// ignore-fast
// aux-build:issue-2631-a.rs
extern crate collections;
extern crate req;
use req::request;
use std::cell::RefCell;
use collections::HashMap;
pub fn main() {
let v = vec!(@~"hi");
let mut m: req::header_map = HashMap::new();
m.insert(~"METHOD", @RefCell::new(v));
request::<int>(&m);
}
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
random_line_split
|
issue-2631-b.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
// ignore-fast
// aux-build:issue-2631-a.rs
extern crate collections;
extern crate req;
use req::request;
use std::cell::RefCell;
use collections::HashMap;
pub fn
|
() {
let v = vec!(@~"hi");
let mut m: req::header_map = HashMap::new();
m.insert(~"METHOD", @RefCell::new(v));
request::<int>(&m);
}
|
main
|
identifier_name
|
issue-2631-b.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
// ignore-fast
// aux-build:issue-2631-a.rs
extern crate collections;
extern crate req;
use req::request;
use std::cell::RefCell;
use collections::HashMap;
pub fn main()
|
{
let v = vec!(@~"hi");
let mut m: req::header_map = HashMap::new();
m.insert(~"METHOD", @RefCell::new(v));
request::<int>(&m);
}
|
identifier_body
|
|
sgash.rs
|
/* kernel::sgash.rs */
#[allow(unused_imports)];
use core::*;
use core::str::*;
use core::option::{Some, Option, None};
use core::iter::Iterator;
use kernel::*;
use kernel::vec::Vec;
use super::super::platform::*;
use kernel::memory::Allocator;
use kernel::memory::BuddyAlloc;
use kernel::memory::Bitv;
use kernel::memory::BitvStorage;
use kernel::memory::Alloc;
use kernel::memory;
use kernel::fs;
use kernel::fs::FileNode;
use kernel::fs::DirNode;
pub static mut buffer: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 0
};
pub static mut s: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut numberString: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut count: uint = 0;
pub static mut root : DirNode = DirNode {
name : cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
},
dchildren : '\0' as *mut Vec<*mut DirNode>,
fchildren : '\0' as *mut Vec<*mut FileNode>,
parent : '\0' as *mut DirNode,
};
pub static mut pwd : *mut DirNode = '\0' as *mut DirNode;
pub fn putchar(key: char) {
unsafe {
/*
* We need to include a blank asm call to prevent rustc
* from optimizing this part out
*/
asm!("");
io::write_char(key, io::UART0);
}
}
pub fn putstr(msg: &str) {
for c in slice::iter(as_bytes(msg)) {
putchar(*c as char);
}
}
pub unsafe fn drawstr(msg: &str) {
let old_fg = super::super::io::FG_COLOR;
let mut x: u32 = 0x6699AAFF;
for c in slice::iter(as_bytes(msg)) {
x = (x << 8) + (x >> 24);
super::super::io::set_fg(x);
drawchar(*c as char);
}
super::super::io::set_fg(old_fg);
}
unsafe fn drawchar(x: char)
{
io::restore();
if x == '\n' {
io::CURSOR_Y += io::CURSOR_HEIGHT;
io::CURSOR_X = 0u32;
}
else {
io::draw_char(x);
io::CURSOR_X += io::CURSOR_WIDTH;
}
io::backup();
io::draw_cursor();
}
unsafe fn backspace()
{
io::restore();
if (io::CURSOR_X >= io::CURSOR_WIDTH) {
io::CURSOR_X -= io::CURSOR_WIDTH;
io::draw_char(' ');
}
io::backup();
io::draw_cursor();
}
pub unsafe fn parsekey(x: char) {
let x = x as u8;
// Set this to false to learn the keycodes of various keys!
// Key codes are printed backwards because life is hard
match x {
13 => {
parse();
putstr(&"\nsgash> ");
drawstr(&"\nsgash> ");
buffer.reset();
}
127 => {
putchar('');
putchar(' ');
putchar('');
backspace();
buffer.delete_char();
}
_ => {
if io::CURSOR_X < io::SCREEN_WIDTH-io::CURSOR_WIDTH && buffer.add_char(x) {
putchar(x as char);
drawchar(x as char);
}
}
}
}
unsafe fn parse(){
// cd, rm, mkdir, pwd
match buffer.getarg(' ', 0) {
Some(a) => {
if(a.equals(&"echo")) {
match buffer.getarg(' ', 1) {
Some(z) => {
drawchar('\n');
drawcstr(z);
}
None => {}
}
}
if(a.equals(&"ls")) {
putstr(&"\nfile list");
drawstr(&"\nfile list");
}
if(a.equals(&"cat")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
(*pwd).read_file(b);
}
None => {}
};
}
if(a.equals(&"cd")) {
putstr(&"\nchange directory");
drawstr(&"\nhange directory");
}
if(a.equals(&"rm")) {
putstr(&"\nremove");
drawstr(&"\nremove");
}
if(a.equals(&"mkdir")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
putcstr(b);
drawcstr(b);
}
None => {}
};
}
if(a.equals(&"pwd")) {
// putcstr((*pwd).name);
// drawcstr((*pwd).name);
putstr(&"\nYou are here");
drawstr(&"\nYou are here");
}
if(a.equals(&"wr")) {
putstr(&"\nwrite file");
drawstr(&"\nwrite file");
}
if(a.equals(&"highlight")) {
match buffer.getarg(' ', 1){
Some(b) =>{
if(b.equals("on")){
io::set_bg(0x33ffff);
}
if(b.equals("off")){
io::set_bg(0x660000);
}
}
None => {}
};
}
if(a.equals(&"clear")){
io::restart();
}
}
None => { }
};
buffer.reset();
}
fn screen() {
putstr(&"\n ");
putstr(&"\n ");
putstr(&"\n 7=..~$=..:7 ");
putstr(&"\n +$: =$$$+$$$?$$$+,7? ");
putstr(&"\n $$$$$$$$$$$$$$$$$$Z$$ ");
putstr(&"\n 7$$$$$$$$$$$$..Z$$$$$Z$$$$$$ ");
putstr(&"\n ~..7$$Z$$$$$7+7$+.?Z7=7$$Z$$Z$$$..: ");
putstr(&"\n ~$$$$$$$$7: :ZZZ, :7ZZZZ$$$$= ");
putstr(&"\n Z$$$$$? .+ZZZZ$$ ");
putstr(&"\n +$ZZ$$$Z7 7ZZZ$Z$$I. ");
putstr(&"\n $$$$ZZZZZZZZZZZZZZZZZZZZZZZZI, ,ZZZ$$Z ");
putstr(&"\n :+$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZ= $ZZ$$+~, ");
putstr(&"\n ?$Z$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZZI 7ZZZ$ZZI ");
putstr(&"\n =Z$$+7Z$$7ZZZZZZZZ$$$$$$$ZZZZZZZZZZ ~Z$?$ZZ? ");
putstr(&"\n :$Z$Z...$Z $ZZZZZZZ~ ~ZZZZZZZZ,.ZZ...Z$Z$~ ");
putstr(&"\n 7ZZZZZI$ZZ $ZZZZZZZ~ =ZZZZZZZ7..ZZ$?$ZZZZ$ ");
putstr(&"\n ZZZZ$: $ZZZZZZZZZZZZZZZZZZZZZZ= ~$ZZZ$: ");
putstr(&"\n 7Z$ZZ$, $ZZZZZZZZZZZZZZZZZZZZ7 ZZZ$Z$ ");
putstr(&"\n =ZZZZZZ, $ZZZZZZZZZZZZZZZZZZZZZZ, ZZZ$ZZ+ ");
putstr(&"\n ,ZZZZ, $ZZZZZZZ: =ZZZZZZZZZ ZZZZZ$: ");
putstr(&"\n =$ZZZZ+ ZZZZZZZZ~ ZZZZZZZZ~ =ZZZZZZZI ");
putstr(&"\n $ZZ$ZZZ$$Z$$ZZZZZZZZZ$$$$ IZZZZZZZZZ$ZZZZZZZZZ$ ");
putstr(&"\n :ZZZZZZZZZZZZZZZZZZZZZZ ~ZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n ,Z$$ZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n =$ZZZZZZZZZZZZZZZZZZZZZZ $ZZZZZZZZZZZZZZZ$+ ");
putstr(&"\n IZZZZZ:. .,ZZZZZ$ ");
putstr(&"\n ~$ZZZZZZZZZZZ ZZZZ$ZZZZZZZ+ ");
putstr(&"\n Z$ZZZ.,Z~ =Z:.,ZZZ$Z ");
putstr(&"\n ,ZZZZZ..~Z$. .7Z:..ZZZZZ: ");
putstr(&"\n ~7+:$ZZZZZZZZI=:. .,=IZZZZZZZ$Z:=7= ");
putstr(&"\n $$ZZZZZZZZZZZZZZZZZZZZZZ$ZZZZ ");
putstr(&"\n ==..$ZZZ$ZZZZZZZZZZZ$ZZZZ.~+ ");
putstr(&"\n I$?.?ZZZ$ZZZ$ZZZI =$7 ");
putstr(&"\n $7..I$7..I$, ");
putstr(&"\n");
putstr(&"\n _ _ _ _ ");
putstr(&"\n| | (_) | | | | ");
putstr(&"\n| | ____ ___ ____ _____| |_____ ____ ____ _____| | ");
putstr(&"\n| |/ ___) _ \\| _ \\ | _ _) ___ |/ ___) _ \\| ___ | | ");
putstr(&"\n| | | | |_| | | | | | | \\ \\| ____| | | | | | ____| | ");
putstr(&"\n|_|_| \\____/|_| |_| |_| \\_\\_____)_| |_| |_|_____)__)\n\n");
}
pub unsafe fn init() {
buffer = cstr::new(256);
screen();
putstr(&"\nsgash> ");
root = fs::DirNode::new(from_str("Root"), '\0' as *mut DirNode);
pwd = &mut root as *mut DirNode;
(*pwd).name = from_str("Root");
buffer.reset();
}
pub unsafe fn putcstr(s: cstr) {
let mut p = s.p as uint;
while *(p as *char)!= '\0'
{
putchar(*(p as *char));
p += 1;
}
}
pub unsafe fn drawcstr(string : cstr) -> bool{
let s = string.p as uint;
let e = string.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
drawchar(theChar as char);
i +=1;
}
else {
return true;
}
}
false
}
pub unsafe fn echo() -> bool{
drawstr(&"\n");
putstr(&"\n");
let s = buffer.p as uint;
let e = buffer.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
putchar(theChar as char);
drawchar(theChar as char);
i +=1;
}
else {
drawstr(&"\n");
putstr(&"\n");
return true;
}
}
false
}
pub unsafe fn from_str(s: &str) -> cstr {
let mut this = cstr::new(256);
for c in slice::iter(as_bytes(s)) {
this.add_char(*c);
};
this
}
pub struct cstr {
p: *mut u8,
p_cstr_i: uint,
max: uint
}
impl cstr {
pub unsafe fn new(size: uint) -> cstr {
let (x,y) = heap.alloc(size);
let temp = ((x as uint) + 256 * count) as *mut u8;
count = count + 1;
let this = cstr {
p: temp,
p_cstr_i: 0,
max: y
};
*(((this.p as uint)+this.p_cstr_i) as *mut char) = '\0';
this
}
fn len(&self) -> uint {
self.p_cstr_i
}
pub unsafe fn add_char(&mut self, x: u8) -> bool{
if (self.p_cstr_i == self.max)
|
*(((self.p as uint)+self.p_cstr_i) as *mut u8) = x;
self.p_cstr_i += 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn delete_char(&mut self) -> bool {
if (self.p_cstr_i == 0) { return false; }
self.p_cstr_i -= 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn reset(&mut self) {
self.p_cstr_i = 0;
*(self.p as *mut char) = '\0';
}
unsafe fn charAt(&self, n: u8) -> char {
((*self.p) + n) as char
}
unsafe fn equals(&self, other: &str) -> bool {
// save val of self.p, which is u8, as a unit
let mut selfp: uint = self.p as uint;
// iterate through the str "other"
for c in slice::iter(as_bytes(other)){
// return false if any character does not match
if( *c!= *(selfp as *u8) ) {
return false;
}
selfp += 1;
};
true
}
pub unsafe fn equals_cstr(&self, other: cstr) -> bool {
let mut x: uint = 0;
let mut selfp: uint = self.p as uint;
let mut otherp: uint = other.p as uint;
while x < self.len() {
if (*(selfp as *char)!= *(otherp as *char)) {
return false;
}
selfp += 1;
otherp += 1;
x += 1;
}
true
}
unsafe fn getarg(&self, delim: char, mut k: uint) -> Option<cstr> {
let mut ind: uint = 0;
let mut found = k == 0;
let mut selfp: uint = self.p as uint;
s.reset();
loop {
if (*(selfp as *char) == '\0') {
// End of string
//return a copy of s (write copy method)
// erased from next call
if (found) { return Some(s); }
else { return None; }
};
if (*(selfp as *u8) == delim as u8) {
if (found) { return Some(s); }
k -= 1;
};
if (found) {
s.add_char(*(selfp as *u8));
};
found = k == 0;
selfp += 1;
ind += 1;
if (ind == self.max) {
putstr(&"\nSomething broke!");
return None;
}
}
}
}
|
{
putstr("not able to add");
return false;
}
|
conditional_block
|
sgash.rs
|
/* kernel::sgash.rs */
#[allow(unused_imports)];
use core::*;
use core::str::*;
use core::option::{Some, Option, None};
use core::iter::Iterator;
use kernel::*;
use kernel::vec::Vec;
use super::super::platform::*;
use kernel::memory::Allocator;
use kernel::memory::BuddyAlloc;
use kernel::memory::Bitv;
use kernel::memory::BitvStorage;
use kernel::memory::Alloc;
use kernel::memory;
use kernel::fs;
use kernel::fs::FileNode;
use kernel::fs::DirNode;
pub static mut buffer: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 0
};
pub static mut s: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut numberString: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut count: uint = 0;
pub static mut root : DirNode = DirNode {
name : cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
},
dchildren : '\0' as *mut Vec<*mut DirNode>,
fchildren : '\0' as *mut Vec<*mut FileNode>,
parent : '\0' as *mut DirNode,
};
pub static mut pwd : *mut DirNode = '\0' as *mut DirNode;
pub fn putchar(key: char) {
unsafe {
/*
* We need to include a blank asm call to prevent rustc
* from optimizing this part out
*/
asm!("");
io::write_char(key, io::UART0);
}
}
pub fn putstr(msg: &str) {
for c in slice::iter(as_bytes(msg)) {
putchar(*c as char);
}
}
pub unsafe fn drawstr(msg: &str) {
let old_fg = super::super::io::FG_COLOR;
let mut x: u32 = 0x6699AAFF;
for c in slice::iter(as_bytes(msg)) {
x = (x << 8) + (x >> 24);
super::super::io::set_fg(x);
drawchar(*c as char);
}
super::super::io::set_fg(old_fg);
}
unsafe fn drawchar(x: char)
{
io::restore();
if x == '\n' {
io::CURSOR_Y += io::CURSOR_HEIGHT;
io::CURSOR_X = 0u32;
}
else {
io::draw_char(x);
io::CURSOR_X += io::CURSOR_WIDTH;
}
io::backup();
io::draw_cursor();
}
unsafe fn backspace()
{
io::restore();
if (io::CURSOR_X >= io::CURSOR_WIDTH) {
io::CURSOR_X -= io::CURSOR_WIDTH;
io::draw_char(' ');
}
io::backup();
io::draw_cursor();
}
pub unsafe fn parsekey(x: char)
|
_ => {
if io::CURSOR_X < io::SCREEN_WIDTH-io::CURSOR_WIDTH && buffer.add_char(x) {
putchar(x as char);
drawchar(x as char);
}
}
}
}
unsafe fn parse(){
// cd, rm, mkdir, pwd
match buffer.getarg(' ', 0) {
Some(a) => {
if(a.equals(&"echo")) {
match buffer.getarg(' ', 1) {
Some(z) => {
drawchar('\n');
drawcstr(z);
}
None => {}
}
}
if(a.equals(&"ls")) {
putstr(&"\nfile list");
drawstr(&"\nfile list");
}
if(a.equals(&"cat")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
(*pwd).read_file(b);
}
None => {}
};
}
if(a.equals(&"cd")) {
putstr(&"\nchange directory");
drawstr(&"\nhange directory");
}
if(a.equals(&"rm")) {
putstr(&"\nremove");
drawstr(&"\nremove");
}
if(a.equals(&"mkdir")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
putcstr(b);
drawcstr(b);
}
None => {}
};
}
if(a.equals(&"pwd")) {
// putcstr((*pwd).name);
// drawcstr((*pwd).name);
putstr(&"\nYou are here");
drawstr(&"\nYou are here");
}
if(a.equals(&"wr")) {
putstr(&"\nwrite file");
drawstr(&"\nwrite file");
}
if(a.equals(&"highlight")) {
match buffer.getarg(' ', 1){
Some(b) =>{
if(b.equals("on")){
io::set_bg(0x33ffff);
}
if(b.equals("off")){
io::set_bg(0x660000);
}
}
None => {}
};
}
if(a.equals(&"clear")){
io::restart();
}
}
None => { }
};
buffer.reset();
}
fn screen() {
putstr(&"\n ");
putstr(&"\n ");
putstr(&"\n 7=..~$=..:7 ");
putstr(&"\n +$: =$$$+$$$?$$$+,7? ");
putstr(&"\n $$$$$$$$$$$$$$$$$$Z$$ ");
putstr(&"\n 7$$$$$$$$$$$$..Z$$$$$Z$$$$$$ ");
putstr(&"\n ~..7$$Z$$$$$7+7$+.?Z7=7$$Z$$Z$$$..: ");
putstr(&"\n ~$$$$$$$$7: :ZZZ, :7ZZZZ$$$$= ");
putstr(&"\n Z$$$$$? .+ZZZZ$$ ");
putstr(&"\n +$ZZ$$$Z7 7ZZZ$Z$$I. ");
putstr(&"\n $$$$ZZZZZZZZZZZZZZZZZZZZZZZZI, ,ZZZ$$Z ");
putstr(&"\n :+$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZ= $ZZ$$+~, ");
putstr(&"\n ?$Z$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZZI 7ZZZ$ZZI ");
putstr(&"\n =Z$$+7Z$$7ZZZZZZZZ$$$$$$$ZZZZZZZZZZ ~Z$?$ZZ? ");
putstr(&"\n :$Z$Z...$Z $ZZZZZZZ~ ~ZZZZZZZZ,.ZZ...Z$Z$~ ");
putstr(&"\n 7ZZZZZI$ZZ $ZZZZZZZ~ =ZZZZZZZ7..ZZ$?$ZZZZ$ ");
putstr(&"\n ZZZZ$: $ZZZZZZZZZZZZZZZZZZZZZZ= ~$ZZZ$: ");
putstr(&"\n 7Z$ZZ$, $ZZZZZZZZZZZZZZZZZZZZ7 ZZZ$Z$ ");
putstr(&"\n =ZZZZZZ, $ZZZZZZZZZZZZZZZZZZZZZZ, ZZZ$ZZ+ ");
putstr(&"\n ,ZZZZ, $ZZZZZZZ: =ZZZZZZZZZ ZZZZZ$: ");
putstr(&"\n =$ZZZZ+ ZZZZZZZZ~ ZZZZZZZZ~ =ZZZZZZZI ");
putstr(&"\n $ZZ$ZZZ$$Z$$ZZZZZZZZZ$$$$ IZZZZZZZZZ$ZZZZZZZZZ$ ");
putstr(&"\n :ZZZZZZZZZZZZZZZZZZZZZZ ~ZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n ,Z$$ZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n =$ZZZZZZZZZZZZZZZZZZZZZZ $ZZZZZZZZZZZZZZZ$+ ");
putstr(&"\n IZZZZZ:. .,ZZZZZ$ ");
putstr(&"\n ~$ZZZZZZZZZZZ ZZZZ$ZZZZZZZ+ ");
putstr(&"\n Z$ZZZ.,Z~ =Z:.,ZZZ$Z ");
putstr(&"\n ,ZZZZZ..~Z$. .7Z:..ZZZZZ: ");
putstr(&"\n ~7+:$ZZZZZZZZI=:. .,=IZZZZZZZ$Z:=7= ");
putstr(&"\n $$ZZZZZZZZZZZZZZZZZZZZZZ$ZZZZ ");
putstr(&"\n ==..$ZZZ$ZZZZZZZZZZZ$ZZZZ.~+ ");
putstr(&"\n I$?.?ZZZ$ZZZ$ZZZI =$7 ");
putstr(&"\n $7..I$7..I$, ");
putstr(&"\n");
putstr(&"\n _ _ _ _ ");
putstr(&"\n| | (_) | | | | ");
putstr(&"\n| | ____ ___ ____ _____| |_____ ____ ____ _____| | ");
putstr(&"\n| |/ ___) _ \\| _ \\ | _ _) ___ |/ ___) _ \\| ___ | | ");
putstr(&"\n| | | | |_| | | | | | | \\ \\| ____| | | | | | ____| | ");
putstr(&"\n|_|_| \\____/|_| |_| |_| \\_\\_____)_| |_| |_|_____)__)\n\n");
}
pub unsafe fn init() {
buffer = cstr::new(256);
screen();
putstr(&"\nsgash> ");
root = fs::DirNode::new(from_str("Root"), '\0' as *mut DirNode);
pwd = &mut root as *mut DirNode;
(*pwd).name = from_str("Root");
buffer.reset();
}
pub unsafe fn putcstr(s: cstr) {
let mut p = s.p as uint;
while *(p as *char)!= '\0'
{
putchar(*(p as *char));
p += 1;
}
}
pub unsafe fn drawcstr(string : cstr) -> bool{
let s = string.p as uint;
let e = string.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
drawchar(theChar as char);
i +=1;
}
else {
return true;
}
}
false
}
pub unsafe fn echo() -> bool{
drawstr(&"\n");
putstr(&"\n");
let s = buffer.p as uint;
let e = buffer.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
putchar(theChar as char);
drawchar(theChar as char);
i +=1;
}
else {
drawstr(&"\n");
putstr(&"\n");
return true;
}
}
false
}
pub unsafe fn from_str(s: &str) -> cstr {
let mut this = cstr::new(256);
for c in slice::iter(as_bytes(s)) {
this.add_char(*c);
};
this
}
pub struct cstr {
p: *mut u8,
p_cstr_i: uint,
max: uint
}
impl cstr {
pub unsafe fn new(size: uint) -> cstr {
let (x,y) = heap.alloc(size);
let temp = ((x as uint) + 256 * count) as *mut u8;
count = count + 1;
let this = cstr {
p: temp,
p_cstr_i: 0,
max: y
};
*(((this.p as uint)+this.p_cstr_i) as *mut char) = '\0';
this
}
fn len(&self) -> uint {
self.p_cstr_i
}
pub unsafe fn add_char(&mut self, x: u8) -> bool{
if (self.p_cstr_i == self.max) {
putstr("not able to add");
return false;
}
*(((self.p as uint)+self.p_cstr_i) as *mut u8) = x;
self.p_cstr_i += 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn delete_char(&mut self) -> bool {
if (self.p_cstr_i == 0) { return false; }
self.p_cstr_i -= 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn reset(&mut self) {
self.p_cstr_i = 0;
*(self.p as *mut char) = '\0';
}
unsafe fn charAt(&self, n: u8) -> char {
((*self.p) + n) as char
}
unsafe fn equals(&self, other: &str) -> bool {
// save val of self.p, which is u8, as a unit
let mut selfp: uint = self.p as uint;
// iterate through the str "other"
for c in slice::iter(as_bytes(other)){
// return false if any character does not match
if( *c!= *(selfp as *u8) ) {
return false;
}
selfp += 1;
};
true
}
pub unsafe fn equals_cstr(&self, other: cstr) -> bool {
let mut x: uint = 0;
let mut selfp: uint = self.p as uint;
let mut otherp: uint = other.p as uint;
while x < self.len() {
if (*(selfp as *char)!= *(otherp as *char)) {
return false;
}
selfp += 1;
otherp += 1;
x += 1;
}
true
}
unsafe fn getarg(&self, delim: char, mut k: uint) -> Option<cstr> {
let mut ind: uint = 0;
let mut found = k == 0;
let mut selfp: uint = self.p as uint;
s.reset();
loop {
if (*(selfp as *char) == '\0') {
// End of string
//return a copy of s (write copy method)
// erased from next call
if (found) { return Some(s); }
else { return None; }
};
if (*(selfp as *u8) == delim as u8) {
if (found) { return Some(s); }
k -= 1;
};
if (found) {
s.add_char(*(selfp as *u8));
};
found = k == 0;
selfp += 1;
ind += 1;
if (ind == self.max) {
putstr(&"\nSomething broke!");
return None;
}
}
}
}
|
{
let x = x as u8;
// Set this to false to learn the keycodes of various keys!
// Key codes are printed backwards because life is hard
match x {
13 => {
parse();
putstr(&"\nsgash> ");
drawstr(&"\nsgash> ");
buffer.reset();
}
127 => {
putchar('');
putchar(' ');
putchar('');
backspace();
buffer.delete_char();
}
|
identifier_body
|
sgash.rs
|
/* kernel::sgash.rs */
#[allow(unused_imports)];
use core::*;
use core::str::*;
use core::option::{Some, Option, None};
use core::iter::Iterator;
use kernel::*;
use kernel::vec::Vec;
use super::super::platform::*;
use kernel::memory::Allocator;
use kernel::memory::BuddyAlloc;
use kernel::memory::Bitv;
use kernel::memory::BitvStorage;
use kernel::memory::Alloc;
use kernel::memory;
use kernel::fs;
use kernel::fs::FileNode;
use kernel::fs::DirNode;
pub static mut buffer: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 0
};
pub static mut s: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut numberString: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut count: uint = 0;
pub static mut root : DirNode = DirNode {
name : cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
},
dchildren : '\0' as *mut Vec<*mut DirNode>,
fchildren : '\0' as *mut Vec<*mut FileNode>,
parent : '\0' as *mut DirNode,
};
pub static mut pwd : *mut DirNode = '\0' as *mut DirNode;
pub fn putchar(key: char) {
unsafe {
/*
* We need to include a blank asm call to prevent rustc
* from optimizing this part out
*/
asm!("");
io::write_char(key, io::UART0);
}
}
pub fn putstr(msg: &str) {
for c in slice::iter(as_bytes(msg)) {
putchar(*c as char);
}
}
pub unsafe fn drawstr(msg: &str) {
let old_fg = super::super::io::FG_COLOR;
let mut x: u32 = 0x6699AAFF;
for c in slice::iter(as_bytes(msg)) {
x = (x << 8) + (x >> 24);
super::super::io::set_fg(x);
drawchar(*c as char);
}
super::super::io::set_fg(old_fg);
}
unsafe fn drawchar(x: char)
{
io::restore();
if x == '\n' {
io::CURSOR_Y += io::CURSOR_HEIGHT;
io::CURSOR_X = 0u32;
}
else {
io::draw_char(x);
io::CURSOR_X += io::CURSOR_WIDTH;
}
io::backup();
io::draw_cursor();
}
unsafe fn backspace()
{
io::restore();
if (io::CURSOR_X >= io::CURSOR_WIDTH) {
io::CURSOR_X -= io::CURSOR_WIDTH;
io::draw_char(' ');
}
io::backup();
io::draw_cursor();
}
pub unsafe fn parsekey(x: char) {
let x = x as u8;
// Set this to false to learn the keycodes of various keys!
// Key codes are printed backwards because life is hard
match x {
13 => {
parse();
putstr(&"\nsgash> ");
drawstr(&"\nsgash> ");
buffer.reset();
}
127 => {
putchar('');
putchar(' ');
putchar('');
backspace();
buffer.delete_char();
}
_ => {
if io::CURSOR_X < io::SCREEN_WIDTH-io::CURSOR_WIDTH && buffer.add_char(x) {
putchar(x as char);
drawchar(x as char);
}
}
}
}
unsafe fn parse(){
// cd, rm, mkdir, pwd
match buffer.getarg(' ', 0) {
Some(a) => {
if(a.equals(&"echo")) {
match buffer.getarg(' ', 1) {
Some(z) => {
drawchar('\n');
drawcstr(z);
}
None => {}
}
}
if(a.equals(&"ls")) {
putstr(&"\nfile list");
drawstr(&"\nfile list");
}
if(a.equals(&"cat")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
(*pwd).read_file(b);
}
None => {}
};
}
if(a.equals(&"cd")) {
putstr(&"\nchange directory");
drawstr(&"\nhange directory");
}
if(a.equals(&"rm")) {
putstr(&"\nremove");
drawstr(&"\nremove");
}
if(a.equals(&"mkdir")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
putcstr(b);
drawcstr(b);
}
None => {}
};
}
if(a.equals(&"pwd")) {
// putcstr((*pwd).name);
// drawcstr((*pwd).name);
putstr(&"\nYou are here");
drawstr(&"\nYou are here");
}
if(a.equals(&"wr")) {
putstr(&"\nwrite file");
drawstr(&"\nwrite file");
}
if(a.equals(&"highlight")) {
match buffer.getarg(' ', 1){
Some(b) =>{
if(b.equals("on")){
io::set_bg(0x33ffff);
}
if(b.equals("off")){
io::set_bg(0x660000);
}
}
None => {}
};
}
if(a.equals(&"clear")){
io::restart();
}
}
None => { }
};
buffer.reset();
}
fn screen() {
putstr(&"\n ");
putstr(&"\n ");
putstr(&"\n 7=..~$=..:7 ");
putstr(&"\n +$: =$$$+$$$?$$$+,7? ");
putstr(&"\n $$$$$$$$$$$$$$$$$$Z$$ ");
putstr(&"\n 7$$$$$$$$$$$$..Z$$$$$Z$$$$$$ ");
putstr(&"\n ~..7$$Z$$$$$7+7$+.?Z7=7$$Z$$Z$$$..: ");
putstr(&"\n ~$$$$$$$$7: :ZZZ, :7ZZZZ$$$$= ");
putstr(&"\n Z$$$$$? .+ZZZZ$$ ");
putstr(&"\n +$ZZ$$$Z7 7ZZZ$Z$$I. ");
putstr(&"\n $$$$ZZZZZZZZZZZZZZZZZZZZZZZZI, ,ZZZ$$Z ");
putstr(&"\n :+$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZ= $ZZ$$+~, ");
putstr(&"\n ?$Z$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZZI 7ZZZ$ZZI ");
putstr(&"\n =Z$$+7Z$$7ZZZZZZZZ$$$$$$$ZZZZZZZZZZ ~Z$?$ZZ? ");
putstr(&"\n :$Z$Z...$Z $ZZZZZZZ~ ~ZZZZZZZZ,.ZZ...Z$Z$~ ");
putstr(&"\n 7ZZZZZI$ZZ $ZZZZZZZ~ =ZZZZZZZ7..ZZ$?$ZZZZ$ ");
putstr(&"\n ZZZZ$: $ZZZZZZZZZZZZZZZZZZZZZZ= ~$ZZZ$: ");
putstr(&"\n 7Z$ZZ$, $ZZZZZZZZZZZZZZZZZZZZ7 ZZZ$Z$ ");
putstr(&"\n =ZZZZZZ, $ZZZZZZZZZZZZZZZZZZZZZZ, ZZZ$ZZ+ ");
putstr(&"\n ,ZZZZ, $ZZZZZZZ: =ZZZZZZZZZ ZZZZZ$: ");
putstr(&"\n =$ZZZZ+ ZZZZZZZZ~ ZZZZZZZZ~ =ZZZZZZZI ");
putstr(&"\n $ZZ$ZZZ$$Z$$ZZZZZZZZZ$$$$ IZZZZZZZZZ$ZZZZZZZZZ$ ");
putstr(&"\n :ZZZZZZZZZZZZZZZZZZZZZZ ~ZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n ,Z$$ZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n =$ZZZZZZZZZZZZZZZZZZZZZZ $ZZZZZZZZZZZZZZZ$+ ");
putstr(&"\n IZZZZZ:. .,ZZZZZ$ ");
putstr(&"\n ~$ZZZZZZZZZZZ ZZZZ$ZZZZZZZ+ ");
putstr(&"\n Z$ZZZ.,Z~ =Z:.,ZZZ$Z ");
putstr(&"\n ,ZZZZZ..~Z$. .7Z:..ZZZZZ: ");
putstr(&"\n ~7+:$ZZZZZZZZI=:. .,=IZZZZZZZ$Z:=7= ");
putstr(&"\n $$ZZZZZZZZZZZZZZZZZZZZZZ$ZZZZ ");
putstr(&"\n ==..$ZZZ$ZZZZZZZZZZZ$ZZZZ.~+ ");
putstr(&"\n I$?.?ZZZ$ZZZ$ZZZI =$7 ");
putstr(&"\n $7..I$7..I$, ");
putstr(&"\n");
putstr(&"\n _ _ _ _ ");
putstr(&"\n| | (_) | | | | ");
putstr(&"\n| | ____ ___ ____ _____| |_____ ____ ____ _____| | ");
putstr(&"\n| |/ ___) _ \\| _ \\ | _ _) ___ |/ ___) _ \\| ___ | | ");
putstr(&"\n| | | | |_| | | | | | | \\ \\| ____| | | | | | ____| | ");
putstr(&"\n|_|_| \\____/|_| |_| |_| \\_\\_____)_| |_| |_|_____)__)\n\n");
}
pub unsafe fn init() {
buffer = cstr::new(256);
screen();
putstr(&"\nsgash> ");
root = fs::DirNode::new(from_str("Root"), '\0' as *mut DirNode);
pwd = &mut root as *mut DirNode;
(*pwd).name = from_str("Root");
buffer.reset();
}
pub unsafe fn putcstr(s: cstr) {
let mut p = s.p as uint;
while *(p as *char)!= '\0'
{
putchar(*(p as *char));
p += 1;
}
}
pub unsafe fn drawcstr(string : cstr) -> bool{
let s = string.p as uint;
let e = string.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
drawchar(theChar as char);
i +=1;
}
else {
return true;
}
}
false
}
pub unsafe fn echo() -> bool{
drawstr(&"\n");
putstr(&"\n");
let s = buffer.p as uint;
let e = buffer.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
putchar(theChar as char);
drawchar(theChar as char);
i +=1;
}
else {
drawstr(&"\n");
putstr(&"\n");
return true;
}
}
false
}
pub unsafe fn from_str(s: &str) -> cstr {
let mut this = cstr::new(256);
for c in slice::iter(as_bytes(s)) {
this.add_char(*c);
};
this
}
pub struct cstr {
p: *mut u8,
p_cstr_i: uint,
max: uint
}
impl cstr {
pub unsafe fn new(size: uint) -> cstr {
let (x,y) = heap.alloc(size);
let temp = ((x as uint) + 256 * count) as *mut u8;
count = count + 1;
let this = cstr {
p: temp,
p_cstr_i: 0,
max: y
};
*(((this.p as uint)+this.p_cstr_i) as *mut char) = '\0';
this
}
fn len(&self) -> uint {
self.p_cstr_i
}
pub unsafe fn add_char(&mut self, x: u8) -> bool{
if (self.p_cstr_i == self.max) {
putstr("not able to add");
return false;
}
*(((self.p as uint)+self.p_cstr_i) as *mut u8) = x;
self.p_cstr_i += 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn delete_char(&mut self) -> bool {
if (self.p_cstr_i == 0) { return false; }
self.p_cstr_i -= 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn reset(&mut self) {
self.p_cstr_i = 0;
*(self.p as *mut char) = '\0';
}
unsafe fn charAt(&self, n: u8) -> char {
((*self.p) + n) as char
}
unsafe fn equals(&self, other: &str) -> bool {
// save val of self.p, which is u8, as a unit
let mut selfp: uint = self.p as uint;
// iterate through the str "other"
for c in slice::iter(as_bytes(other)){
// return false if any character does not match
if( *c!= *(selfp as *u8) ) {
return false;
}
selfp += 1;
};
true
}
pub unsafe fn equals_cstr(&self, other: cstr) -> bool {
let mut x: uint = 0;
let mut selfp: uint = self.p as uint;
let mut otherp: uint = other.p as uint;
while x < self.len() {
if (*(selfp as *char)!= *(otherp as *char)) {
return false;
}
selfp += 1;
otherp += 1;
x += 1;
}
true
}
unsafe fn
|
(&self, delim: char, mut k: uint) -> Option<cstr> {
let mut ind: uint = 0;
let mut found = k == 0;
let mut selfp: uint = self.p as uint;
s.reset();
loop {
if (*(selfp as *char) == '\0') {
// End of string
//return a copy of s (write copy method)
// erased from next call
if (found) { return Some(s); }
else { return None; }
};
if (*(selfp as *u8) == delim as u8) {
if (found) { return Some(s); }
k -= 1;
};
if (found) {
s.add_char(*(selfp as *u8));
};
found = k == 0;
selfp += 1;
ind += 1;
if (ind == self.max) {
putstr(&"\nSomething broke!");
return None;
}
}
}
}
|
getarg
|
identifier_name
|
sgash.rs
|
/* kernel::sgash.rs */
#[allow(unused_imports)];
use core::*;
use core::str::*;
use core::option::{Some, Option, None};
use core::iter::Iterator;
use kernel::*;
use kernel::vec::Vec;
use super::super::platform::*;
use kernel::memory::Allocator;
use kernel::memory::BuddyAlloc;
use kernel::memory::Bitv;
use kernel::memory::BitvStorage;
use kernel::memory::Alloc;
use kernel::memory;
use kernel::fs;
use kernel::fs::FileNode;
use kernel::fs::DirNode;
pub static mut buffer: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 0
};
pub static mut s: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut numberString: cstr = cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
};
pub static mut count: uint = 0;
pub static mut root : DirNode = DirNode {
name : cstr {
p: 0 as *mut u8,
p_cstr_i: 0,
max: 256
},
dchildren : '\0' as *mut Vec<*mut DirNode>,
fchildren : '\0' as *mut Vec<*mut FileNode>,
parent : '\0' as *mut DirNode,
};
pub static mut pwd : *mut DirNode = '\0' as *mut DirNode;
pub fn putchar(key: char) {
unsafe {
/*
* We need to include a blank asm call to prevent rustc
* from optimizing this part out
*/
asm!("");
io::write_char(key, io::UART0);
}
}
pub fn putstr(msg: &str) {
for c in slice::iter(as_bytes(msg)) {
putchar(*c as char);
}
}
pub unsafe fn drawstr(msg: &str) {
let old_fg = super::super::io::FG_COLOR;
let mut x: u32 = 0x6699AAFF;
for c in slice::iter(as_bytes(msg)) {
x = (x << 8) + (x >> 24);
super::super::io::set_fg(x);
drawchar(*c as char);
}
super::super::io::set_fg(old_fg);
}
unsafe fn drawchar(x: char)
{
io::restore();
if x == '\n' {
io::CURSOR_Y += io::CURSOR_HEIGHT;
io::CURSOR_X = 0u32;
}
else {
io::draw_char(x);
io::CURSOR_X += io::CURSOR_WIDTH;
}
io::backup();
io::draw_cursor();
}
unsafe fn backspace()
{
io::restore();
if (io::CURSOR_X >= io::CURSOR_WIDTH) {
io::CURSOR_X -= io::CURSOR_WIDTH;
io::draw_char(' ');
}
io::backup();
io::draw_cursor();
}
pub unsafe fn parsekey(x: char) {
let x = x as u8;
// Set this to false to learn the keycodes of various keys!
// Key codes are printed backwards because life is hard
match x {
13 => {
parse();
putstr(&"\nsgash> ");
drawstr(&"\nsgash> ");
buffer.reset();
}
127 => {
|
putchar('');
backspace();
buffer.delete_char();
}
_ => {
if io::CURSOR_X < io::SCREEN_WIDTH-io::CURSOR_WIDTH && buffer.add_char(x) {
putchar(x as char);
drawchar(x as char);
}
}
}
}
unsafe fn parse(){
// cd, rm, mkdir, pwd
match buffer.getarg(' ', 0) {
Some(a) => {
if(a.equals(&"echo")) {
match buffer.getarg(' ', 1) {
Some(z) => {
drawchar('\n');
drawcstr(z);
}
None => {}
}
}
if(a.equals(&"ls")) {
putstr(&"\nfile list");
drawstr(&"\nfile list");
}
if(a.equals(&"cat")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
(*pwd).read_file(b);
}
None => {}
};
}
if(a.equals(&"cd")) {
putstr(&"\nchange directory");
drawstr(&"\nhange directory");
}
if(a.equals(&"rm")) {
putstr(&"\nremove");
drawstr(&"\nremove");
}
if(a.equals(&"mkdir")) {
putstr(&"\n");
drawstr(&"\n");
match buffer.getarg(' ', 1){
Some(b) =>{
putcstr(b);
drawcstr(b);
}
None => {}
};
}
if(a.equals(&"pwd")) {
// putcstr((*pwd).name);
// drawcstr((*pwd).name);
putstr(&"\nYou are here");
drawstr(&"\nYou are here");
}
if(a.equals(&"wr")) {
putstr(&"\nwrite file");
drawstr(&"\nwrite file");
}
if(a.equals(&"highlight")) {
match buffer.getarg(' ', 1){
Some(b) =>{
if(b.equals("on")){
io::set_bg(0x33ffff);
}
if(b.equals("off")){
io::set_bg(0x660000);
}
}
None => {}
};
}
if(a.equals(&"clear")){
io::restart();
}
}
None => { }
};
buffer.reset();
}
fn screen() {
putstr(&"\n ");
putstr(&"\n ");
putstr(&"\n 7=..~$=..:7 ");
putstr(&"\n +$: =$$$+$$$?$$$+,7? ");
putstr(&"\n $$$$$$$$$$$$$$$$$$Z$$ ");
putstr(&"\n 7$$$$$$$$$$$$..Z$$$$$Z$$$$$$ ");
putstr(&"\n ~..7$$Z$$$$$7+7$+.?Z7=7$$Z$$Z$$$..: ");
putstr(&"\n ~$$$$$$$$7: :ZZZ, :7ZZZZ$$$$= ");
putstr(&"\n Z$$$$$? .+ZZZZ$$ ");
putstr(&"\n +$ZZ$$$Z7 7ZZZ$Z$$I. ");
putstr(&"\n $$$$ZZZZZZZZZZZZZZZZZZZZZZZZI, ,ZZZ$$Z ");
putstr(&"\n :+$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZ= $ZZ$$+~, ");
putstr(&"\n ?$Z$$$$ZZZZZZZZZZZZZZZZZZZZZZZZZZZZI 7ZZZ$ZZI ");
putstr(&"\n =Z$$+7Z$$7ZZZZZZZZ$$$$$$$ZZZZZZZZZZ ~Z$?$ZZ? ");
putstr(&"\n :$Z$Z...$Z $ZZZZZZZ~ ~ZZZZZZZZ,.ZZ...Z$Z$~ ");
putstr(&"\n 7ZZZZZI$ZZ $ZZZZZZZ~ =ZZZZZZZ7..ZZ$?$ZZZZ$ ");
putstr(&"\n ZZZZ$: $ZZZZZZZZZZZZZZZZZZZZZZ= ~$ZZZ$: ");
putstr(&"\n 7Z$ZZ$, $ZZZZZZZZZZZZZZZZZZZZ7 ZZZ$Z$ ");
putstr(&"\n =ZZZZZZ, $ZZZZZZZZZZZZZZZZZZZZZZ, ZZZ$ZZ+ ");
putstr(&"\n ,ZZZZ, $ZZZZZZZ: =ZZZZZZZZZ ZZZZZ$: ");
putstr(&"\n =$ZZZZ+ ZZZZZZZZ~ ZZZZZZZZ~ =ZZZZZZZI ");
putstr(&"\n $ZZ$ZZZ$$Z$$ZZZZZZZZZ$$$$ IZZZZZZZZZ$ZZZZZZZZZ$ ");
putstr(&"\n :ZZZZZZZZZZZZZZZZZZZZZZ ~ZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n ,Z$$ZZZZZZZZZZZZZZZZZZZZ ZZZZZZZZZZZZZZZZZZ~ ");
putstr(&"\n =$ZZZZZZZZZZZZZZZZZZZZZZ $ZZZZZZZZZZZZZZZ$+ ");
putstr(&"\n IZZZZZ:. .,ZZZZZ$ ");
putstr(&"\n ~$ZZZZZZZZZZZ ZZZZ$ZZZZZZZ+ ");
putstr(&"\n Z$ZZZ.,Z~ =Z:.,ZZZ$Z ");
putstr(&"\n ,ZZZZZ..~Z$. .7Z:..ZZZZZ: ");
putstr(&"\n ~7+:$ZZZZZZZZI=:. .,=IZZZZZZZ$Z:=7= ");
putstr(&"\n $$ZZZZZZZZZZZZZZZZZZZZZZ$ZZZZ ");
putstr(&"\n ==..$ZZZ$ZZZZZZZZZZZ$ZZZZ.~+ ");
putstr(&"\n I$?.?ZZZ$ZZZ$ZZZI =$7 ");
putstr(&"\n $7..I$7..I$, ");
putstr(&"\n");
putstr(&"\n _ _ _ _ ");
putstr(&"\n| | (_) | | | | ");
putstr(&"\n| | ____ ___ ____ _____| |_____ ____ ____ _____| | ");
putstr(&"\n| |/ ___) _ \\| _ \\ | _ _) ___ |/ ___) _ \\| ___ | | ");
putstr(&"\n| | | | |_| | | | | | | \\ \\| ____| | | | | | ____| | ");
putstr(&"\n|_|_| \\____/|_| |_| |_| \\_\\_____)_| |_| |_|_____)__)\n\n");
}
pub unsafe fn init() {
buffer = cstr::new(256);
screen();
putstr(&"\nsgash> ");
root = fs::DirNode::new(from_str("Root"), '\0' as *mut DirNode);
pwd = &mut root as *mut DirNode;
(*pwd).name = from_str("Root");
buffer.reset();
}
pub unsafe fn putcstr(s: cstr) {
let mut p = s.p as uint;
while *(p as *char)!= '\0'
{
putchar(*(p as *char));
p += 1;
}
}
pub unsafe fn drawcstr(string : cstr) -> bool{
let s = string.p as uint;
let e = string.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
drawchar(theChar as char);
i +=1;
}
else {
return true;
}
}
false
}
pub unsafe fn echo() -> bool{
drawstr(&"\n");
putstr(&"\n");
let s = buffer.p as uint;
let e = buffer.max;
let mut i = 0;
while i < e {
let theChar : u8 = *((s+i) as *mut u8);
if(theChar as char!= '\0') {
putchar(theChar as char);
drawchar(theChar as char);
i +=1;
}
else {
drawstr(&"\n");
putstr(&"\n");
return true;
}
}
false
}
pub unsafe fn from_str(s: &str) -> cstr {
let mut this = cstr::new(256);
for c in slice::iter(as_bytes(s)) {
this.add_char(*c);
};
this
}
pub struct cstr {
p: *mut u8,
p_cstr_i: uint,
max: uint
}
impl cstr {
pub unsafe fn new(size: uint) -> cstr {
let (x,y) = heap.alloc(size);
let temp = ((x as uint) + 256 * count) as *mut u8;
count = count + 1;
let this = cstr {
p: temp,
p_cstr_i: 0,
max: y
};
*(((this.p as uint)+this.p_cstr_i) as *mut char) = '\0';
this
}
fn len(&self) -> uint {
self.p_cstr_i
}
pub unsafe fn add_char(&mut self, x: u8) -> bool{
if (self.p_cstr_i == self.max) {
putstr("not able to add");
return false;
}
*(((self.p as uint)+self.p_cstr_i) as *mut u8) = x;
self.p_cstr_i += 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn delete_char(&mut self) -> bool {
if (self.p_cstr_i == 0) { return false; }
self.p_cstr_i -= 1;
*(((self.p as uint)+self.p_cstr_i) as *mut char) = '\0';
true
}
unsafe fn reset(&mut self) {
self.p_cstr_i = 0;
*(self.p as *mut char) = '\0';
}
unsafe fn charAt(&self, n: u8) -> char {
((*self.p) + n) as char
}
unsafe fn equals(&self, other: &str) -> bool {
// save val of self.p, which is u8, as a unit
let mut selfp: uint = self.p as uint;
// iterate through the str "other"
for c in slice::iter(as_bytes(other)){
// return false if any character does not match
if( *c!= *(selfp as *u8) ) {
return false;
}
selfp += 1;
};
true
}
pub unsafe fn equals_cstr(&self, other: cstr) -> bool {
let mut x: uint = 0;
let mut selfp: uint = self.p as uint;
let mut otherp: uint = other.p as uint;
while x < self.len() {
if (*(selfp as *char)!= *(otherp as *char)) {
return false;
}
selfp += 1;
otherp += 1;
x += 1;
}
true
}
unsafe fn getarg(&self, delim: char, mut k: uint) -> Option<cstr> {
let mut ind: uint = 0;
let mut found = k == 0;
let mut selfp: uint = self.p as uint;
s.reset();
loop {
if (*(selfp as *char) == '\0') {
// End of string
//return a copy of s (write copy method)
// erased from next call
if (found) { return Some(s); }
else { return None; }
};
if (*(selfp as *u8) == delim as u8) {
if (found) { return Some(s); }
k -= 1;
};
if (found) {
s.add_char(*(selfp as *u8));
};
found = k == 0;
selfp += 1;
ind += 1;
if (ind == self.max) {
putstr(&"\nSomething broke!");
return None;
}
}
}
}
|
putchar('');
putchar(' ');
|
random_line_split
|
matrices.rs
|
use libc::{c_double};
use cairo::ffi;
#[repr(C)]
pub struct Matrix{
xx: c_double,
yx: c_double,
xy: c_double,
yy: c_double,
x0: c_double,
y0: c_double,
}
impl Matrix{
pub fn null() -> Matrix{
Matrix{
xx: 0.0,
yx: 0.0,
xy: 0.0,
yy: 0.0,
x0: 0.0,
y0: 0.0
}
}
pub fn new(xx: f64, yx: f64, xy: f64, yy: f64, x0: f64, y0: f64) -> Matrix{
let mut matrix = Matrix::null();
matrix.init(xx, yx, xy, yy, x0, y0);
matrix
}
pub fn multiply(left: &Matrix, right: &Matrix) -> Matrix{
let mut matrix = Matrix::null();
unsafe{
ffi::cairo_matrix_multiply(&mut matrix, left, right);
}
matrix
}
pub fn identity() -> Matrix{
let mut matrix = Matrix::null();
unsafe{
ffi::cairo_matrix_init_identity(&mut matrix);
}
matrix
}
pub fn init(&mut self, xx: f64, yx: f64, xy: f64, yy: f64, x0: f64, y0: f64){
unsafe{
ffi::cairo_matrix_init(self, xx, yx, xy, yy, x0, y0)
}
}
pub fn translate(&mut self, tx: f64, ty: f64){
unsafe{
ffi::cairo_matrix_translate(self, tx, ty)
}
}
pub fn scale(&mut self, sx: f64, sy: f64){
unsafe{
ffi::cairo_matrix_scale(self, sx, sy)
}
}
pub fn rotate(&mut self, angle: f64){
unsafe{
ffi::cairo_matrix_rotate(self, angle)
}
}
pub fn
|
(&mut self){
let result = unsafe{
ffi::cairo_matrix_invert(self)
};
result.ensure_valid();
}
pub fn transform_distance(&self, _dx: f64, _dy: f64) -> (f64, f64){
let mut dx = _dx;
let mut dy = _dy;
unsafe{
ffi::cairo_matrix_transform_distance(self, &mut dx, &mut dy);
}
(dx, dy)
}
pub fn transform_point(&self, _x: f64, _y: f64) -> (f64, f64){
let mut x = _x;
let mut y = _y;
unsafe{
ffi::cairo_matrix_transform_point(self, &mut x, &mut y);
}
(x, y)
}
}
|
invert
|
identifier_name
|
matrices.rs
|
use libc::{c_double};
use cairo::ffi;
#[repr(C)]
pub struct Matrix{
xx: c_double,
yx: c_double,
xy: c_double,
yy: c_double,
x0: c_double,
y0: c_double,
}
impl Matrix{
pub fn null() -> Matrix{
Matrix{
xx: 0.0,
yx: 0.0,
xy: 0.0,
yy: 0.0,
x0: 0.0,
y0: 0.0
}
}
pub fn new(xx: f64, yx: f64, xy: f64, yy: f64, x0: f64, y0: f64) -> Matrix{
let mut matrix = Matrix::null();
matrix.init(xx, yx, xy, yy, x0, y0);
matrix
}
pub fn multiply(left: &Matrix, right: &Matrix) -> Matrix{
let mut matrix = Matrix::null();
unsafe{
ffi::cairo_matrix_multiply(&mut matrix, left, right);
}
matrix
}
pub fn identity() -> Matrix{
let mut matrix = Matrix::null();
unsafe{
ffi::cairo_matrix_init_identity(&mut matrix);
}
matrix
}
pub fn init(&mut self, xx: f64, yx: f64, xy: f64, yy: f64, x0: f64, y0: f64){
unsafe{
ffi::cairo_matrix_init(self, xx, yx, xy, yy, x0, y0)
}
}
pub fn translate(&mut self, tx: f64, ty: f64)
|
pub fn scale(&mut self, sx: f64, sy: f64){
unsafe{
ffi::cairo_matrix_scale(self, sx, sy)
}
}
pub fn rotate(&mut self, angle: f64){
unsafe{
ffi::cairo_matrix_rotate(self, angle)
}
}
pub fn invert(&mut self){
let result = unsafe{
ffi::cairo_matrix_invert(self)
};
result.ensure_valid();
}
pub fn transform_distance(&self, _dx: f64, _dy: f64) -> (f64, f64){
let mut dx = _dx;
let mut dy = _dy;
unsafe{
ffi::cairo_matrix_transform_distance(self, &mut dx, &mut dy);
}
(dx, dy)
}
pub fn transform_point(&self, _x: f64, _y: f64) -> (f64, f64){
let mut x = _x;
let mut y = _y;
unsafe{
ffi::cairo_matrix_transform_point(self, &mut x, &mut y);
}
(x, y)
}
}
|
{
unsafe{
ffi::cairo_matrix_translate(self, tx, ty)
}
}
|
identifier_body
|
coerce-issue-49593-box-never.rs
|
// revisions: nofallback fallback
//[fallback] check-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
#![allow(unreachable_code)]
use std::error::Error;
use std::mem;
|
/* *mut $0 is coerced to Box<dyn Error> here */ Box::<_ /*! */>::new(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn foo_raw_ptr(x:!) -> *mut dyn Error {
/* *mut $0 is coerced to *mut Error here */ raw_ptr_box::<_ /*! */>(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn no_coercion(d: *mut dyn Error) -> *mut dyn Error {
/* an unsize coercion won't compile here, and it is indeed not used
because there is nothing requiring the _ to be Sized */
d as *mut _
}
trait Xyz {}
struct S;
struct T;
impl Xyz for S {}
impl Xyz for T {}
fn foo_no_never() {
let mut x /* : Option<S> */ = None;
let mut first_iter = false;
loop {
if!first_iter {
let y: Box<dyn Xyz>
= /* Box<$0> is coerced to Box<Xyz> here */ Box::new(x.unwrap());
}
x = Some(S);
first_iter = true;
}
let mut y : Option<S> = None;
// assert types are equal
mem::swap(&mut x, &mut y);
}
fn main() {
}
|
fn raw_ptr_box<T>(t: T) -> *mut T {
panic!()
}
fn foo(x: !) -> Box<dyn Error> {
|
random_line_split
|
coerce-issue-49593-box-never.rs
|
// revisions: nofallback fallback
//[fallback] check-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
#![allow(unreachable_code)]
use std::error::Error;
use std::mem;
fn raw_ptr_box<T>(t: T) -> *mut T {
panic!()
}
fn foo(x:!) -> Box<dyn Error>
|
fn foo_raw_ptr(x:!) -> *mut dyn Error {
/* *mut $0 is coerced to *mut Error here */ raw_ptr_box::<_ /*! */>(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn no_coercion(d: *mut dyn Error) -> *mut dyn Error {
/* an unsize coercion won't compile here, and it is indeed not used
because there is nothing requiring the _ to be Sized */
d as *mut _
}
trait Xyz {}
struct S;
struct T;
impl Xyz for S {}
impl Xyz for T {}
fn foo_no_never() {
let mut x /* : Option<S> */ = None;
let mut first_iter = false;
loop {
if!first_iter {
let y: Box<dyn Xyz>
= /* Box<$0> is coerced to Box<Xyz> here */ Box::new(x.unwrap());
}
x = Some(S);
first_iter = true;
}
let mut y : Option<S> = None;
// assert types are equal
mem::swap(&mut x, &mut y);
}
fn main() {
}
|
{
/* *mut $0 is coerced to Box<dyn Error> here */ Box::<_ /* ! */>::new(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
|
identifier_body
|
coerce-issue-49593-box-never.rs
|
// revisions: nofallback fallback
//[fallback] check-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
#![allow(unreachable_code)]
use std::error::Error;
use std::mem;
fn raw_ptr_box<T>(t: T) -> *mut T {
panic!()
}
fn foo(x:!) -> Box<dyn Error> {
/* *mut $0 is coerced to Box<dyn Error> here */ Box::<_ /*! */>::new(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn foo_raw_ptr(x:!) -> *mut dyn Error {
/* *mut $0 is coerced to *mut Error here */ raw_ptr_box::<_ /*! */>(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn no_coercion(d: *mut dyn Error) -> *mut dyn Error {
/* an unsize coercion won't compile here, and it is indeed not used
because there is nothing requiring the _ to be Sized */
d as *mut _
}
trait Xyz {}
struct S;
struct T;
impl Xyz for S {}
impl Xyz for T {}
fn foo_no_never() {
let mut x /* : Option<S> */ = None;
let mut first_iter = false;
loop {
if!first_iter
|
x = Some(S);
first_iter = true;
}
let mut y : Option<S> = None;
// assert types are equal
mem::swap(&mut x, &mut y);
}
fn main() {
}
|
{
let y: Box<dyn Xyz>
= /* Box<$0> is coerced to Box<Xyz> here */ Box::new(x.unwrap());
}
|
conditional_block
|
coerce-issue-49593-box-never.rs
|
// revisions: nofallback fallback
//[fallback] check-pass
//[nofallback] check-fail
#![feature(never_type)]
#![cfg_attr(fallback, feature(never_type_fallback))]
#![allow(unreachable_code)]
use std::error::Error;
use std::mem;
fn raw_ptr_box<T>(t: T) -> *mut T {
panic!()
}
fn foo(x:!) -> Box<dyn Error> {
/* *mut $0 is coerced to Box<dyn Error> here */ Box::<_ /*! */>::new(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn foo_raw_ptr(x:!) -> *mut dyn Error {
/* *mut $0 is coerced to *mut Error here */ raw_ptr_box::<_ /*! */>(x)
//[nofallback]~^ ERROR trait bound `(): std::error::Error` is not satisfied
}
fn
|
(d: *mut dyn Error) -> *mut dyn Error {
/* an unsize coercion won't compile here, and it is indeed not used
because there is nothing requiring the _ to be Sized */
d as *mut _
}
trait Xyz {}
struct S;
struct T;
impl Xyz for S {}
impl Xyz for T {}
fn foo_no_never() {
let mut x /* : Option<S> */ = None;
let mut first_iter = false;
loop {
if!first_iter {
let y: Box<dyn Xyz>
= /* Box<$0> is coerced to Box<Xyz> here */ Box::new(x.unwrap());
}
x = Some(S);
first_iter = true;
}
let mut y : Option<S> = None;
// assert types are equal
mem::swap(&mut x, &mut y);
}
fn main() {
}
|
no_coercion
|
identifier_name
|
bookitem.rs
|
extern crate rustc_serialize;
use self::rustc_serialize::json::{Json, ToJson};
use std::path::PathBuf;
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub enum BookItem {
Chapter(String, Chapter), // String = section
Affix(Chapter),
Spacer,
}
#[derive(Debug, Clone)]
pub struct Chapter {
pub name: String,
pub path: PathBuf,
pub sub_items: Vec<BookItem>,
}
#[derive(Debug, Clone)]
pub struct BookItems<'a> {
pub items: &'a [BookItem],
pub current_index: usize,
pub stack: Vec<(&'a [BookItem], usize)>,
}
impl Chapter {
|
Chapter {
name: name,
path: path,
sub_items: vec![],
}
}
}
impl ToJson for Chapter {
fn to_json(&self) -> Json {
let mut m: BTreeMap<String, Json> = BTreeMap::new();
m.insert("name".to_owned(), self.name.to_json());
m.insert("path".to_owned(),self.path.to_str()
.expect("Json conversion failed for path").to_json()
);
m.to_json()
}
}
// Shamelessly copied from Rustbook
// (https://github.com/rust-lang/rust/blob/master/src/rustbook/book.rs)
impl<'a> Iterator for BookItems<'a> {
type Item = &'a BookItem;
fn next(&mut self) -> Option<&'a BookItem> {
loop {
if self.current_index >= self.items.len() {
match self.stack.pop() {
None => return None,
Some((parent_items, parent_idx)) => {
self.items = parent_items;
self.current_index = parent_idx + 1;
}
}
} else {
let cur = self.items.get(self.current_index).unwrap();
match *cur {
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {
self.stack.push((self.items, self.current_index));
self.items = &ch.sub_items[..];
self.current_index = 0;
},
BookItem::Spacer => {
self.current_index += 1;
}
}
return Some(cur)
}
}
}
}
|
pub fn new(name: String, path: PathBuf) -> Self {
|
random_line_split
|
bookitem.rs
|
extern crate rustc_serialize;
use self::rustc_serialize::json::{Json, ToJson};
use std::path::PathBuf;
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub enum BookItem {
Chapter(String, Chapter), // String = section
Affix(Chapter),
Spacer,
}
#[derive(Debug, Clone)]
pub struct Chapter {
pub name: String,
pub path: PathBuf,
pub sub_items: Vec<BookItem>,
}
#[derive(Debug, Clone)]
pub struct BookItems<'a> {
pub items: &'a [BookItem],
pub current_index: usize,
pub stack: Vec<(&'a [BookItem], usize)>,
}
impl Chapter {
pub fn new(name: String, path: PathBuf) -> Self {
Chapter {
name: name,
path: path,
sub_items: vec![],
}
}
}
impl ToJson for Chapter {
fn
|
(&self) -> Json {
let mut m: BTreeMap<String, Json> = BTreeMap::new();
m.insert("name".to_owned(), self.name.to_json());
m.insert("path".to_owned(),self.path.to_str()
.expect("Json conversion failed for path").to_json()
);
m.to_json()
}
}
// Shamelessly copied from Rustbook
// (https://github.com/rust-lang/rust/blob/master/src/rustbook/book.rs)
impl<'a> Iterator for BookItems<'a> {
type Item = &'a BookItem;
fn next(&mut self) -> Option<&'a BookItem> {
loop {
if self.current_index >= self.items.len() {
match self.stack.pop() {
None => return None,
Some((parent_items, parent_idx)) => {
self.items = parent_items;
self.current_index = parent_idx + 1;
}
}
} else {
let cur = self.items.get(self.current_index).unwrap();
match *cur {
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {
self.stack.push((self.items, self.current_index));
self.items = &ch.sub_items[..];
self.current_index = 0;
},
BookItem::Spacer => {
self.current_index += 1;
}
}
return Some(cur)
}
}
}
}
|
to_json
|
identifier_name
|
bookitem.rs
|
extern crate rustc_serialize;
use self::rustc_serialize::json::{Json, ToJson};
use std::path::PathBuf;
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub enum BookItem {
Chapter(String, Chapter), // String = section
Affix(Chapter),
Spacer,
}
#[derive(Debug, Clone)]
pub struct Chapter {
pub name: String,
pub path: PathBuf,
pub sub_items: Vec<BookItem>,
}
#[derive(Debug, Clone)]
pub struct BookItems<'a> {
pub items: &'a [BookItem],
pub current_index: usize,
pub stack: Vec<(&'a [BookItem], usize)>,
}
impl Chapter {
pub fn new(name: String, path: PathBuf) -> Self {
Chapter {
name: name,
path: path,
sub_items: vec![],
}
}
}
impl ToJson for Chapter {
fn to_json(&self) -> Json {
let mut m: BTreeMap<String, Json> = BTreeMap::new();
m.insert("name".to_owned(), self.name.to_json());
m.insert("path".to_owned(),self.path.to_str()
.expect("Json conversion failed for path").to_json()
);
m.to_json()
}
}
// Shamelessly copied from Rustbook
// (https://github.com/rust-lang/rust/blob/master/src/rustbook/book.rs)
impl<'a> Iterator for BookItems<'a> {
type Item = &'a BookItem;
fn next(&mut self) -> Option<&'a BookItem> {
loop {
if self.current_index >= self.items.len() {
match self.stack.pop() {
None => return None,
Some((parent_items, parent_idx)) => {
self.items = parent_items;
self.current_index = parent_idx + 1;
}
}
} else {
let cur = self.items.get(self.current_index).unwrap();
match *cur {
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {
self.stack.push((self.items, self.current_index));
self.items = &ch.sub_items[..];
self.current_index = 0;
},
BookItem::Spacer =>
|
}
return Some(cur)
}
}
}
}
|
{
self.current_index += 1;
}
|
conditional_block
|
object.rs
|
use ast::token;
use class::{LoxClass,LoxInstance};
use functions::Callable;
use std::cmp::Ordering;
use std::fmt;
use std::cmp;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub enum
|
{
Literal(token::Literal),
Func(Callable),
Class(Rc<LoxClass>),
Instance(LoxInstance),
}
impl Object {
pub fn is_truthy(&self) -> bool {
use ast::token::Literal::*;
match *self {
Object::Func(_) | Object::Class(_) | Object::Instance(_) => true,
Object::Literal(ref lit) => match *lit {
Nil => false,
Boolean(b) => b,
Number(n) => n!= 0.0,
String(ref s) =>!s.is_empty(),
},
}
}
}
#[cfg(feature = "debug-destructors")]
impl Drop for Object{
fn drop(&mut self) {
match *self {
Object::Literal(ref lit) =>
debug_drop!("Object::Literal {:?}", lit),
Object::Func(ref c) =>
debug_drop!("Object::Func {:?}", c),
Object::Class(ref c) =>
debug_drop!("Object::Class {:?} ({} refs remain)", c, Rc::strong_count(&c)-1),
Object::Instance(ref i) =>
debug_drop!("Object::Instance {:?}", i),
}
}
}
impl cmp::PartialEq for Object {
fn eq(&self, other: &Self) -> bool {
use object::Object::Literal as ObjLit;
match (self, other) {
(&ObjLit(ref lhs), &ObjLit(ref rhs)) => lhs.eq(rhs),
_ => false
}
}
}
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Object::Literal(ref lit) => fmt::Display::fmt(lit, f),
Object::Func(_) => write!(f, "<function>"),
Object::Class(ref cls) => fmt::Display::fmt(cls, f),
Object::Instance(ref inst) => fmt::Display::fmt(inst, f),
}
}
}
impl PartialOrd for Object {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
use object::Object::Literal as ObjLit;
match (self, other) {
(&ObjLit(ref l), &ObjLit(ref r)) => l.partial_cmp(r),
_ => None,
}
}
}
|
Object
|
identifier_name
|
object.rs
|
use ast::token;
use class::{LoxClass,LoxInstance};
use functions::Callable;
use std::cmp::Ordering;
use std::fmt;
use std::cmp;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub enum Object {
Literal(token::Literal),
Func(Callable),
Class(Rc<LoxClass>),
Instance(LoxInstance),
}
impl Object {
pub fn is_truthy(&self) -> bool {
use ast::token::Literal::*;
match *self {
Object::Func(_) | Object::Class(_) | Object::Instance(_) => true,
Object::Literal(ref lit) => match *lit {
Nil => false,
Boolean(b) => b,
Number(n) => n!= 0.0,
String(ref s) =>!s.is_empty(),
},
}
}
}
#[cfg(feature = "debug-destructors")]
impl Drop for Object{
fn drop(&mut self) {
match *self {
Object::Literal(ref lit) =>
|
Object::Func(ref c) =>
debug_drop!("Object::Func {:?}", c),
Object::Class(ref c) =>
debug_drop!("Object::Class {:?} ({} refs remain)", c, Rc::strong_count(&c)-1),
Object::Instance(ref i) =>
debug_drop!("Object::Instance {:?}", i),
}
}
}
impl cmp::PartialEq for Object {
fn eq(&self, other: &Self) -> bool {
use object::Object::Literal as ObjLit;
match (self, other) {
(&ObjLit(ref lhs), &ObjLit(ref rhs)) => lhs.eq(rhs),
_ => false
}
}
}
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Object::Literal(ref lit) => fmt::Display::fmt(lit, f),
Object::Func(_) => write!(f, "<function>"),
Object::Class(ref cls) => fmt::Display::fmt(cls, f),
Object::Instance(ref inst) => fmt::Display::fmt(inst, f),
}
}
}
impl PartialOrd for Object {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
use object::Object::Literal as ObjLit;
match (self, other) {
(&ObjLit(ref l), &ObjLit(ref r)) => l.partial_cmp(r),
_ => None,
}
}
}
|
debug_drop!("Object::Literal {:?}", lit),
|
random_line_split
|
object.rs
|
use ast::token;
use class::{LoxClass,LoxInstance};
use functions::Callable;
use std::cmp::Ordering;
use std::fmt;
use std::cmp;
use std::rc::Rc;
#[derive(Clone, Debug)]
pub enum Object {
Literal(token::Literal),
Func(Callable),
Class(Rc<LoxClass>),
Instance(LoxInstance),
}
impl Object {
pub fn is_truthy(&self) -> bool
|
}
#[cfg(feature = "debug-destructors")]
impl Drop for Object{
fn drop(&mut self) {
match *self {
Object::Literal(ref lit) =>
debug_drop!("Object::Literal {:?}", lit),
Object::Func(ref c) =>
debug_drop!("Object::Func {:?}", c),
Object::Class(ref c) =>
debug_drop!("Object::Class {:?} ({} refs remain)", c, Rc::strong_count(&c)-1),
Object::Instance(ref i) =>
debug_drop!("Object::Instance {:?}", i),
}
}
}
impl cmp::PartialEq for Object {
fn eq(&self, other: &Self) -> bool {
use object::Object::Literal as ObjLit;
match (self, other) {
(&ObjLit(ref lhs), &ObjLit(ref rhs)) => lhs.eq(rhs),
_ => false
}
}
}
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Object::Literal(ref lit) => fmt::Display::fmt(lit, f),
Object::Func(_) => write!(f, "<function>"),
Object::Class(ref cls) => fmt::Display::fmt(cls, f),
Object::Instance(ref inst) => fmt::Display::fmt(inst, f),
}
}
}
impl PartialOrd for Object {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
use object::Object::Literal as ObjLit;
match (self, other) {
(&ObjLit(ref l), &ObjLit(ref r)) => l.partial_cmp(r),
_ => None,
}
}
}
|
{
use ast::token::Literal::*;
match *self {
Object::Func(_) | Object::Class(_) | Object::Instance(_) => true,
Object::Literal(ref lit) => match *lit {
Nil => false,
Boolean(b) => b,
Number(n) => n != 0.0,
String(ref s) => !s.is_empty(),
},
}
}
|
identifier_body
|
prompt.rs
|
use super::super::{Capture, Function, Shell};
use parser::shell_expand::expand_string;
use std::{io::Read, process};
use sys;
pub(crate) fn prompt(shell: &mut Shell) -> String {
if shell.flow_control.level == 0 {
match prompt_fn(shell) {
Some(prompt) => prompt,
None => expand_string(&shell.get_var_or_empty("PROMPT"), shell, false).join(" "),
}
} else {
" ".repeat(shell.flow_control.level as usize)
}
}
pub(crate) fn prompt_fn(shell: &mut Shell) -> Option<String>
|
}
// Ensure that the parent retains ownership of the terminal before exiting.
let _ = sys::tcsetpgrp(sys::STDIN_FILENO, process::id());
output
}
|
{
let function = shell.functions.get("PROMPT")? as *const Function;
let mut output = None;
match shell.fork(Capture::StdoutThenIgnoreStderr, |child| unsafe {
let _ = function.read().execute(child, &["ion"]);
}) {
Ok(result) => {
let mut string = String::with_capacity(1024);
match result.stdout.unwrap().read_to_string(&mut string) {
Ok(_) => output = Some(string),
Err(why) => {
eprintln!("ion: error reading stdout of child: {}", why);
}
}
}
Err(why) => {
eprintln!("ion: fork error: {}", why);
}
|
identifier_body
|
prompt.rs
|
use super::super::{Capture, Function, Shell};
use parser::shell_expand::expand_string;
use std::{io::Read, process};
use sys;
pub(crate) fn prompt(shell: &mut Shell) -> String {
if shell.flow_control.level == 0 {
match prompt_fn(shell) {
Some(prompt) => prompt,
None => expand_string(&shell.get_var_or_empty("PROMPT"), shell, false).join(" "),
}
} else {
" ".repeat(shell.flow_control.level as usize)
}
}
pub(crate) fn prompt_fn(shell: &mut Shell) -> Option<String> {
let function = shell.functions.get("PROMPT")? as *const Function;
let mut output = None;
match shell.fork(Capture::StdoutThenIgnoreStderr, |child| unsafe {
let _ = function.read().execute(child, &["ion"]);
}) {
Ok(result) => {
let mut string = String::with_capacity(1024);
match result.stdout.unwrap().read_to_string(&mut string) {
Ok(_) => output = Some(string),
Err(why) => {
eprintln!("ion: error reading stdout of child: {}", why);
}
}
}
Err(why) => {
eprintln!("ion: fork error: {}", why);
}
}
// Ensure that the parent retains ownership of the terminal before exiting.
let _ = sys::tcsetpgrp(sys::STDIN_FILENO, process::id());
output
|
}
|
random_line_split
|
|
prompt.rs
|
use super::super::{Capture, Function, Shell};
use parser::shell_expand::expand_string;
use std::{io::Read, process};
use sys;
pub(crate) fn
|
(shell: &mut Shell) -> String {
if shell.flow_control.level == 0 {
match prompt_fn(shell) {
Some(prompt) => prompt,
None => expand_string(&shell.get_var_or_empty("PROMPT"), shell, false).join(" "),
}
} else {
" ".repeat(shell.flow_control.level as usize)
}
}
pub(crate) fn prompt_fn(shell: &mut Shell) -> Option<String> {
let function = shell.functions.get("PROMPT")? as *const Function;
let mut output = None;
match shell.fork(Capture::StdoutThenIgnoreStderr, |child| unsafe {
let _ = function.read().execute(child, &["ion"]);
}) {
Ok(result) => {
let mut string = String::with_capacity(1024);
match result.stdout.unwrap().read_to_string(&mut string) {
Ok(_) => output = Some(string),
Err(why) => {
eprintln!("ion: error reading stdout of child: {}", why);
}
}
}
Err(why) => {
eprintln!("ion: fork error: {}", why);
}
}
// Ensure that the parent retains ownership of the terminal before exiting.
let _ = sys::tcsetpgrp(sys::STDIN_FILENO, process::id());
output
}
|
prompt
|
identifier_name
|
prompt.rs
|
use super::super::{Capture, Function, Shell};
use parser::shell_expand::expand_string;
use std::{io::Read, process};
use sys;
pub(crate) fn prompt(shell: &mut Shell) -> String {
if shell.flow_control.level == 0 {
match prompt_fn(shell) {
Some(prompt) => prompt,
None => expand_string(&shell.get_var_or_empty("PROMPT"), shell, false).join(" "),
}
} else
|
}
pub(crate) fn prompt_fn(shell: &mut Shell) -> Option<String> {
let function = shell.functions.get("PROMPT")? as *const Function;
let mut output = None;
match shell.fork(Capture::StdoutThenIgnoreStderr, |child| unsafe {
let _ = function.read().execute(child, &["ion"]);
}) {
Ok(result) => {
let mut string = String::with_capacity(1024);
match result.stdout.unwrap().read_to_string(&mut string) {
Ok(_) => output = Some(string),
Err(why) => {
eprintln!("ion: error reading stdout of child: {}", why);
}
}
}
Err(why) => {
eprintln!("ion: fork error: {}", why);
}
}
// Ensure that the parent retains ownership of the terminal before exiting.
let _ = sys::tcsetpgrp(sys::STDIN_FILENO, process::id());
output
}
|
{
" ".repeat(shell.flow_control.level as usize)
}
|
conditional_block
|
mod.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
|
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
mod accept_connection;
mod connect;
mod connection;
pub use self::accept_connection::{AcceptConnection, accept_connection};
pub use self::connect::{Connect, connect};
pub use self::connection::Connection;
|
random_line_split
|
|
id_type.rs
|
// Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
|
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// IdType
///
/// #Examples
/// ```
/// use ::safe_client::id::{IdType, RevocationIdType, MaidTypeTags};
/// // Creating new IdType
/// let maid = IdType::new(&RevocationIdType::new::<MaidTypeTags>());
///
/// ```
#[derive(Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable)]
pub struct IdType {
type_tag : u64,
public_keys: (::sodiumoxide::crypto::sign::PublicKey, ::sodiumoxide::crypto::box_::PublicKey),
secret_keys: (::sodiumoxide::crypto::sign::SecretKey, ::sodiumoxide::crypto::box_::SecretKey),
}
impl IdType {
/// Invoked to create an instance of IdType
pub fn new(revocation_id: &::id::RevocationIdType) -> IdType {
let asym_keys = ::sodiumoxide::crypto::box_::gen_keypair();
let signing_keys = ::sodiumoxide::crypto::sign::gen_keypair();
IdType {
type_tag : revocation_id.type_tags().1,
public_keys: (signing_keys.0, asym_keys.0),
secret_keys: (signing_keys.1, asym_keys.1),
}
}
/// Returns name
pub fn name(&self) -> ::routing::NameType {
let combined_iter = (&self.public_keys.0).0.into_iter().chain((&self.public_keys.1).0.into_iter());
let mut combined = Vec::new();
for iter in combined_iter {
combined.push(*iter);
}
for i in self.type_tag.to_string().into_bytes().into_iter() {
combined.push(i);
}
::routing::NameType(::sodiumoxide::crypto::hash::sha512::hash(&combined).0)
}
/// Returns the PublicKeys
pub fn public_keys(&self) -> &(::sodiumoxide::crypto::sign::PublicKey, ::sodiumoxide::crypto::box_::PublicKey) {
&self.public_keys
}
/// Returns the PublicKeys
pub fn secret_keys(&self) -> &(::sodiumoxide::crypto::sign::SecretKey, ::sodiumoxide::crypto::box_::SecretKey) {
&self.secret_keys
}
/// Signs the data with the SecretKey and returns the Signed data
pub fn sign(&self, data : &[u8]) -> Vec<u8> {
return ::sodiumoxide::crypto::sign::sign(&data, &self.secret_keys.0)
}
/// Encrypts and authenticates data. It returns a ciphertext and the Nonce.
pub fn seal(&self, data : &[u8], to : &::sodiumoxide::crypto::box_::PublicKey) -> (Vec<u8>, ::sodiumoxide::crypto::box_::Nonce) {
let nonce = ::sodiumoxide::crypto::box_::gen_nonce();
let sealed = ::sodiumoxide::crypto::box_::seal(data, &nonce, &to, &self.secret_keys.1);
return (sealed, nonce);
}
/// Verifies and decrypts the data
pub fn open(&self,
data : &[u8],
nonce : &::sodiumoxide::crypto::box_::Nonce,
from : &::sodiumoxide::crypto::box_::PublicKey) -> Result<Vec<u8>, ::errors::ClientError> {
::sodiumoxide::crypto::box_::open(&data, &nonce, &from, &self.secret_keys.1).map_err(|_| ::errors::ClientError::AsymmetricDecipherFailure)
}
}
#[cfg(test)]
mod test {
extern crate rand;
use self::rand::Rng;
use ::id::Random;
impl Random for ::id::IdType {
fn generate_random() -> ::id::IdType {
::id::IdType::new(&::id::RevocationIdType::new::<::id::MaidTypeTags>())
}
}
#[test]
fn serialisation_maid() {
let obj_before = ::id::IdType::generate_random();
let mut e = ::cbor::Encoder::from_memory();
e.encode(&[&obj_before]).unwrap();
let mut d = ::cbor::Decoder::from_bytes(e.as_bytes());
let obj_after: ::id::IdType = d.decode().next().unwrap().unwrap();
let &(::sodiumoxide::crypto::sign::PublicKey(pub_sign_arr_before), ::sodiumoxide::crypto::box_::PublicKey(pub_asym_arr_before)) = obj_before.public_keys();
let &(::sodiumoxide::crypto::sign::PublicKey(pub_sign_arr_after), ::sodiumoxide::crypto::box_::PublicKey(pub_asym_arr_after)) = obj_after.public_keys();
let &(::sodiumoxide::crypto::sign::SecretKey(sec_sign_arr_before), ::sodiumoxide::crypto::box_::SecretKey(sec_asym_arr_before)) = &obj_before.secret_keys;
let &(::sodiumoxide::crypto::sign::SecretKey(sec_sign_arr_after), ::sodiumoxide::crypto::box_::SecretKey(sec_asym_arr_after)) = &obj_after.secret_keys;
assert_eq!(pub_sign_arr_before, pub_sign_arr_after);
assert_eq!(pub_asym_arr_before, pub_asym_arr_after);
assert!(::utility::slice_equal(&sec_sign_arr_before, &sec_sign_arr_after));
assert_eq!(sec_asym_arr_before, sec_asym_arr_after);
}
#[test]
fn generation() {
let maid1 = ::id::IdType::generate_random();
let maid2 = ::id::IdType::generate_random();
let maid2_clone = maid2.clone();
assert_eq!(maid2, maid2_clone);
assert!(!(maid2!= maid2_clone));
assert!(maid1!= maid2);
let random_bytes = rand::thread_rng().gen_iter::<u8>().take(100).collect::<Vec<u8>>();
{
let sign1 = maid1.sign(&random_bytes);
let sign2 = maid2.sign(&random_bytes);
assert!(sign1!= sign2);
assert!(::sodiumoxide::crypto::sign::verify(&sign1, &maid1.public_keys().0).is_ok());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid1.public_keys().0).is_err());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid2.public_keys().0).is_ok());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid1.public_keys().0).is_err());
}
{
let maid3 = ::id::IdType::generate_random();
let encrypt1 = maid1.seal(&random_bytes, &maid3.public_keys().1);
let encrypt2 = maid2.seal(&random_bytes, &maid3.public_keys().1);
assert!(encrypt1.0!= encrypt2.0);
assert!(maid3.open(&encrypt1.0, &encrypt1.1, &maid1.public_keys().1).is_ok());
assert!(maid3.open(&encrypt1.0, &encrypt1.1, &maid2.public_keys().1).is_err());
assert!(maid3.open(&encrypt2.0, &encrypt2.1, &maid2.public_keys().1).is_ok());
assert!(maid3.open(&encrypt2.0, &encrypt2.1, &maid1.public_keys().1).is_err());
}
}
}
|
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
|
random_line_split
|
id_type.rs
|
// Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// IdType
///
/// #Examples
/// ```
/// use ::safe_client::id::{IdType, RevocationIdType, MaidTypeTags};
/// // Creating new IdType
/// let maid = IdType::new(&RevocationIdType::new::<MaidTypeTags>());
///
/// ```
#[derive(Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable)]
pub struct IdType {
type_tag : u64,
public_keys: (::sodiumoxide::crypto::sign::PublicKey, ::sodiumoxide::crypto::box_::PublicKey),
secret_keys: (::sodiumoxide::crypto::sign::SecretKey, ::sodiumoxide::crypto::box_::SecretKey),
}
impl IdType {
/// Invoked to create an instance of IdType
pub fn new(revocation_id: &::id::RevocationIdType) -> IdType {
let asym_keys = ::sodiumoxide::crypto::box_::gen_keypair();
let signing_keys = ::sodiumoxide::crypto::sign::gen_keypair();
IdType {
type_tag : revocation_id.type_tags().1,
public_keys: (signing_keys.0, asym_keys.0),
secret_keys: (signing_keys.1, asym_keys.1),
}
}
/// Returns name
pub fn name(&self) -> ::routing::NameType {
let combined_iter = (&self.public_keys.0).0.into_iter().chain((&self.public_keys.1).0.into_iter());
let mut combined = Vec::new();
for iter in combined_iter {
combined.push(*iter);
}
for i in self.type_tag.to_string().into_bytes().into_iter() {
combined.push(i);
}
::routing::NameType(::sodiumoxide::crypto::hash::sha512::hash(&combined).0)
}
/// Returns the PublicKeys
pub fn public_keys(&self) -> &(::sodiumoxide::crypto::sign::PublicKey, ::sodiumoxide::crypto::box_::PublicKey) {
&self.public_keys
}
/// Returns the PublicKeys
pub fn secret_keys(&self) -> &(::sodiumoxide::crypto::sign::SecretKey, ::sodiumoxide::crypto::box_::SecretKey) {
&self.secret_keys
}
/// Signs the data with the SecretKey and returns the Signed data
pub fn sign(&self, data : &[u8]) -> Vec<u8>
|
/// Encrypts and authenticates data. It returns a ciphertext and the Nonce.
pub fn seal(&self, data : &[u8], to : &::sodiumoxide::crypto::box_::PublicKey) -> (Vec<u8>, ::sodiumoxide::crypto::box_::Nonce) {
let nonce = ::sodiumoxide::crypto::box_::gen_nonce();
let sealed = ::sodiumoxide::crypto::box_::seal(data, &nonce, &to, &self.secret_keys.1);
return (sealed, nonce);
}
/// Verifies and decrypts the data
pub fn open(&self,
data : &[u8],
nonce : &::sodiumoxide::crypto::box_::Nonce,
from : &::sodiumoxide::crypto::box_::PublicKey) -> Result<Vec<u8>, ::errors::ClientError> {
::sodiumoxide::crypto::box_::open(&data, &nonce, &from, &self.secret_keys.1).map_err(|_| ::errors::ClientError::AsymmetricDecipherFailure)
}
}
#[cfg(test)]
mod test {
extern crate rand;
use self::rand::Rng;
use ::id::Random;
impl Random for ::id::IdType {
fn generate_random() -> ::id::IdType {
::id::IdType::new(&::id::RevocationIdType::new::<::id::MaidTypeTags>())
}
}
#[test]
fn serialisation_maid() {
let obj_before = ::id::IdType::generate_random();
let mut e = ::cbor::Encoder::from_memory();
e.encode(&[&obj_before]).unwrap();
let mut d = ::cbor::Decoder::from_bytes(e.as_bytes());
let obj_after: ::id::IdType = d.decode().next().unwrap().unwrap();
let &(::sodiumoxide::crypto::sign::PublicKey(pub_sign_arr_before), ::sodiumoxide::crypto::box_::PublicKey(pub_asym_arr_before)) = obj_before.public_keys();
let &(::sodiumoxide::crypto::sign::PublicKey(pub_sign_arr_after), ::sodiumoxide::crypto::box_::PublicKey(pub_asym_arr_after)) = obj_after.public_keys();
let &(::sodiumoxide::crypto::sign::SecretKey(sec_sign_arr_before), ::sodiumoxide::crypto::box_::SecretKey(sec_asym_arr_before)) = &obj_before.secret_keys;
let &(::sodiumoxide::crypto::sign::SecretKey(sec_sign_arr_after), ::sodiumoxide::crypto::box_::SecretKey(sec_asym_arr_after)) = &obj_after.secret_keys;
assert_eq!(pub_sign_arr_before, pub_sign_arr_after);
assert_eq!(pub_asym_arr_before, pub_asym_arr_after);
assert!(::utility::slice_equal(&sec_sign_arr_before, &sec_sign_arr_after));
assert_eq!(sec_asym_arr_before, sec_asym_arr_after);
}
#[test]
fn generation() {
let maid1 = ::id::IdType::generate_random();
let maid2 = ::id::IdType::generate_random();
let maid2_clone = maid2.clone();
assert_eq!(maid2, maid2_clone);
assert!(!(maid2!= maid2_clone));
assert!(maid1!= maid2);
let random_bytes = rand::thread_rng().gen_iter::<u8>().take(100).collect::<Vec<u8>>();
{
let sign1 = maid1.sign(&random_bytes);
let sign2 = maid2.sign(&random_bytes);
assert!(sign1!= sign2);
assert!(::sodiumoxide::crypto::sign::verify(&sign1, &maid1.public_keys().0).is_ok());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid1.public_keys().0).is_err());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid2.public_keys().0).is_ok());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid1.public_keys().0).is_err());
}
{
let maid3 = ::id::IdType::generate_random();
let encrypt1 = maid1.seal(&random_bytes, &maid3.public_keys().1);
let encrypt2 = maid2.seal(&random_bytes, &maid3.public_keys().1);
assert!(encrypt1.0!= encrypt2.0);
assert!(maid3.open(&encrypt1.0, &encrypt1.1, &maid1.public_keys().1).is_ok());
assert!(maid3.open(&encrypt1.0, &encrypt1.1, &maid2.public_keys().1).is_err());
assert!(maid3.open(&encrypt2.0, &encrypt2.1, &maid2.public_keys().1).is_ok());
assert!(maid3.open(&encrypt2.0, &encrypt2.1, &maid1.public_keys().1).is_err());
}
}
}
|
{
return ::sodiumoxide::crypto::sign::sign(&data, &self.secret_keys.0)
}
|
identifier_body
|
id_type.rs
|
// Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// IdType
///
/// #Examples
/// ```
/// use ::safe_client::id::{IdType, RevocationIdType, MaidTypeTags};
/// // Creating new IdType
/// let maid = IdType::new(&RevocationIdType::new::<MaidTypeTags>());
///
/// ```
#[derive(Clone, Debug, Eq, PartialEq, RustcEncodable, RustcDecodable)]
pub struct
|
{
type_tag : u64,
public_keys: (::sodiumoxide::crypto::sign::PublicKey, ::sodiumoxide::crypto::box_::PublicKey),
secret_keys: (::sodiumoxide::crypto::sign::SecretKey, ::sodiumoxide::crypto::box_::SecretKey),
}
impl IdType {
/// Invoked to create an instance of IdType
pub fn new(revocation_id: &::id::RevocationIdType) -> IdType {
let asym_keys = ::sodiumoxide::crypto::box_::gen_keypair();
let signing_keys = ::sodiumoxide::crypto::sign::gen_keypair();
IdType {
type_tag : revocation_id.type_tags().1,
public_keys: (signing_keys.0, asym_keys.0),
secret_keys: (signing_keys.1, asym_keys.1),
}
}
/// Returns name
pub fn name(&self) -> ::routing::NameType {
let combined_iter = (&self.public_keys.0).0.into_iter().chain((&self.public_keys.1).0.into_iter());
let mut combined = Vec::new();
for iter in combined_iter {
combined.push(*iter);
}
for i in self.type_tag.to_string().into_bytes().into_iter() {
combined.push(i);
}
::routing::NameType(::sodiumoxide::crypto::hash::sha512::hash(&combined).0)
}
/// Returns the PublicKeys
pub fn public_keys(&self) -> &(::sodiumoxide::crypto::sign::PublicKey, ::sodiumoxide::crypto::box_::PublicKey) {
&self.public_keys
}
/// Returns the PublicKeys
pub fn secret_keys(&self) -> &(::sodiumoxide::crypto::sign::SecretKey, ::sodiumoxide::crypto::box_::SecretKey) {
&self.secret_keys
}
/// Signs the data with the SecretKey and returns the Signed data
pub fn sign(&self, data : &[u8]) -> Vec<u8> {
return ::sodiumoxide::crypto::sign::sign(&data, &self.secret_keys.0)
}
/// Encrypts and authenticates data. It returns a ciphertext and the Nonce.
pub fn seal(&self, data : &[u8], to : &::sodiumoxide::crypto::box_::PublicKey) -> (Vec<u8>, ::sodiumoxide::crypto::box_::Nonce) {
let nonce = ::sodiumoxide::crypto::box_::gen_nonce();
let sealed = ::sodiumoxide::crypto::box_::seal(data, &nonce, &to, &self.secret_keys.1);
return (sealed, nonce);
}
/// Verifies and decrypts the data
pub fn open(&self,
data : &[u8],
nonce : &::sodiumoxide::crypto::box_::Nonce,
from : &::sodiumoxide::crypto::box_::PublicKey) -> Result<Vec<u8>, ::errors::ClientError> {
::sodiumoxide::crypto::box_::open(&data, &nonce, &from, &self.secret_keys.1).map_err(|_| ::errors::ClientError::AsymmetricDecipherFailure)
}
}
#[cfg(test)]
mod test {
extern crate rand;
use self::rand::Rng;
use ::id::Random;
impl Random for ::id::IdType {
fn generate_random() -> ::id::IdType {
::id::IdType::new(&::id::RevocationIdType::new::<::id::MaidTypeTags>())
}
}
#[test]
fn serialisation_maid() {
let obj_before = ::id::IdType::generate_random();
let mut e = ::cbor::Encoder::from_memory();
e.encode(&[&obj_before]).unwrap();
let mut d = ::cbor::Decoder::from_bytes(e.as_bytes());
let obj_after: ::id::IdType = d.decode().next().unwrap().unwrap();
let &(::sodiumoxide::crypto::sign::PublicKey(pub_sign_arr_before), ::sodiumoxide::crypto::box_::PublicKey(pub_asym_arr_before)) = obj_before.public_keys();
let &(::sodiumoxide::crypto::sign::PublicKey(pub_sign_arr_after), ::sodiumoxide::crypto::box_::PublicKey(pub_asym_arr_after)) = obj_after.public_keys();
let &(::sodiumoxide::crypto::sign::SecretKey(sec_sign_arr_before), ::sodiumoxide::crypto::box_::SecretKey(sec_asym_arr_before)) = &obj_before.secret_keys;
let &(::sodiumoxide::crypto::sign::SecretKey(sec_sign_arr_after), ::sodiumoxide::crypto::box_::SecretKey(sec_asym_arr_after)) = &obj_after.secret_keys;
assert_eq!(pub_sign_arr_before, pub_sign_arr_after);
assert_eq!(pub_asym_arr_before, pub_asym_arr_after);
assert!(::utility::slice_equal(&sec_sign_arr_before, &sec_sign_arr_after));
assert_eq!(sec_asym_arr_before, sec_asym_arr_after);
}
#[test]
fn generation() {
let maid1 = ::id::IdType::generate_random();
let maid2 = ::id::IdType::generate_random();
let maid2_clone = maid2.clone();
assert_eq!(maid2, maid2_clone);
assert!(!(maid2!= maid2_clone));
assert!(maid1!= maid2);
let random_bytes = rand::thread_rng().gen_iter::<u8>().take(100).collect::<Vec<u8>>();
{
let sign1 = maid1.sign(&random_bytes);
let sign2 = maid2.sign(&random_bytes);
assert!(sign1!= sign2);
assert!(::sodiumoxide::crypto::sign::verify(&sign1, &maid1.public_keys().0).is_ok());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid1.public_keys().0).is_err());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid2.public_keys().0).is_ok());
assert!(::sodiumoxide::crypto::sign::verify(&sign2, &maid1.public_keys().0).is_err());
}
{
let maid3 = ::id::IdType::generate_random();
let encrypt1 = maid1.seal(&random_bytes, &maid3.public_keys().1);
let encrypt2 = maid2.seal(&random_bytes, &maid3.public_keys().1);
assert!(encrypt1.0!= encrypt2.0);
assert!(maid3.open(&encrypt1.0, &encrypt1.1, &maid1.public_keys().1).is_ok());
assert!(maid3.open(&encrypt1.0, &encrypt1.1, &maid2.public_keys().1).is_err());
assert!(maid3.open(&encrypt2.0, &encrypt2.1, &maid2.public_keys().1).is_ok());
assert!(maid3.open(&encrypt2.0, &encrypt2.1, &maid1.public_keys().1).is_err());
}
}
}
|
IdType
|
identifier_name
|
trait-inheritance-static.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait MyNum {
fn from_int(int) -> Self;
}
pub trait NumExt: MyNum { }
struct S { v: int }
impl MyNum for S {
fn from_int(i: int) -> S {
S {
v: i
}
}
}
impl NumExt for S { }
fn
|
<T:NumExt>() -> T { MyNum::from_int(1) }
pub fn main() {
let v: S = greater_than_one();
assert!(v.v == 1);
}
|
greater_than_one
|
identifier_name
|
trait-inheritance-static.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait MyNum {
fn from_int(int) -> Self;
}
pub trait NumExt: MyNum { }
struct S { v: int }
impl MyNum for S {
fn from_int(i: int) -> S {
S {
v: i
}
}
}
impl NumExt for S { }
fn greater_than_one<T:NumExt>() -> T { MyNum::from_int(1) }
pub fn main() {
let v: S = greater_than_one();
assert!(v.v == 1);
}
|
random_line_split
|
|
trait-inheritance-static.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait MyNum {
fn from_int(int) -> Self;
}
pub trait NumExt: MyNum { }
struct S { v: int }
impl MyNum for S {
fn from_int(i: int) -> S {
S {
v: i
}
}
}
impl NumExt for S { }
fn greater_than_one<T:NumExt>() -> T
|
pub fn main() {
let v: S = greater_than_one();
assert!(v.v == 1);
}
|
{ MyNum::from_int(1) }
|
identifier_body
|
outline.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Specified values for outline properties
use crate::parser::{Parse, ParserContext};
use crate::values::specified::BorderStyle;
use cssparser::Parser;
use selectors::parser::SelectorParseErrorKind;
use style_traits::ParseError;
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Ord,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
/// <https://drafts.csswg.org/css-ui/#propdef-outline-style>
pub enum OutlineStyle {
/// auto
Auto,
/// <border-style>
BorderStyle(BorderStyle),
}
impl OutlineStyle {
#[inline]
/// Get default value as None
pub fn none() -> OutlineStyle {
OutlineStyle::BorderStyle(BorderStyle::None)
}
#[inline]
/// Get value for None or Hidden
pub fn none_or_hidden(&self) -> bool {
match *self {
OutlineStyle::Auto => false,
OutlineStyle::BorderStyle(ref style) => style.none_or_hidden(),
}
}
}
impl Parse for OutlineStyle {
fn
|
<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<OutlineStyle, ParseError<'i>> {
if let Ok(border_style) = input.try_parse(BorderStyle::parse) {
if let BorderStyle::Hidden = border_style {
return Err(input
.new_custom_error(SelectorParseErrorKind::UnexpectedIdent("hidden".into())));
}
return Ok(OutlineStyle::BorderStyle(border_style));
}
input.expect_ident_matching("auto")?;
Ok(OutlineStyle::Auto)
}
}
|
parse
|
identifier_name
|
outline.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Specified values for outline properties
use crate::parser::{Parse, ParserContext};
use crate::values::specified::BorderStyle;
use cssparser::Parser;
use selectors::parser::SelectorParseErrorKind;
use style_traits::ParseError;
#[derive(
Clone,
Copy,
Debug,
Eq,
MallocSizeOf,
Ord,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToComputedValue,
ToCss,
ToResolvedValue,
ToShmem,
)]
#[repr(C, u8)]
/// <https://drafts.csswg.org/css-ui/#propdef-outline-style>
pub enum OutlineStyle {
/// auto
Auto,
/// <border-style>
BorderStyle(BorderStyle),
}
impl OutlineStyle {
#[inline]
/// Get default value as None
pub fn none() -> OutlineStyle {
OutlineStyle::BorderStyle(BorderStyle::None)
}
#[inline]
/// Get value for None or Hidden
pub fn none_or_hidden(&self) -> bool {
match *self {
OutlineStyle::Auto => false,
OutlineStyle::BorderStyle(ref style) => style.none_or_hidden(),
}
}
}
impl Parse for OutlineStyle {
fn parse<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<OutlineStyle, ParseError<'i>> {
if let Ok(border_style) = input.try_parse(BorderStyle::parse) {
if let BorderStyle::Hidden = border_style {
return Err(input
.new_custom_error(SelectorParseErrorKind::UnexpectedIdent("hidden".into())));
}
return Ok(OutlineStyle::BorderStyle(border_style));
}
input.expect_ident_matching("auto")?;
Ok(OutlineStyle::Auto)
|
}
}
|
random_line_split
|
|
restrictions.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.
//! Computes the restrictions that result from a borrow.
pub use self::RestrictionResult::*;
use borrowck::*;
use rustc::middle::expr_use_visitor as euv;
use rustc::middle::mem_categorization as mc;
use rustc::middle::ty;
use syntax::codemap::Span;
use borrowck::ToInteriorKind;
use std::rc::Rc;
#[derive(Debug)]
pub enum RestrictionResult<'tcx> {
Safe,
SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>)
}
pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
span: Span,
cause: euv::LoanCause,
cmt: mc::cmt<'tcx>,
loan_region: ty::Region)
-> RestrictionResult<'tcx> {
let ctxt = RestrictionsContext {
bccx: bccx,
span: span,
cause: cause,
loan_region: loan_region,
};
ctxt.restrict(cmt)
}
///////////////////////////////////////////////////////////////////////////
// Private
struct RestrictionsContext<'a, 'tcx: 'a> {
bccx: &'a BorrowckCtxt<'a, 'tcx>,
span: Span,
loan_region: ty::Region,
cause: euv::LoanCause,
}
impl<'a, 'tcx> RestrictionsContext<'a, 'tcx> {
fn restrict(&self,
cmt: mc::cmt<'tcx>) -> RestrictionResult<'tcx> {
debug!("restrict(cmt={:?})", cmt);
let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
match cmt.cat.clone() {
mc::cat_rvalue(..) => {
// Effectively, rvalues are stored into a
// non-aliasable temporary on the stack. Since they
// are inherently non-aliasable, they can only be
// accessed later through the borrow itself and hence
// must inherently comply with its terms.
Safe
}
mc::cat_local(local_id) => {
// R-Variable, locally declared
let lp = new_lp(LpVar(local_id));
SafeIf(lp.clone(), vec![lp])
}
mc::cat_upvar(mc::Upvar { id,.. }) => {
// R-Variable, captured into closure
let lp = new_lp(LpUpvar(id));
SafeIf(lp.clone(), vec![lp])
}
mc::cat_downcast(cmt_base, _) => {
// When we borrow the interior of an enum, we have to
// ensure the enum itself is not mutated, because that
// could cause the type of the memory to change.
self.restrict(cmt_base)
}
mc::cat_interior(cmt_base, i) => {
// R-Field
//
// Overwriting the base would not change the type of
// the memory, so no additional restrictions are
// needed.
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpInterior(i.cleaned()))
}
mc::cat_static_item(..) => {
Safe
}
mc::cat_deref(cmt_base, _, pk) => {
match pk {
mc::Unique =>
|
mc::Implicit(bk, lt) | mc::BorrowedPtr(bk, lt) => {
// R-Deref-[Mut-]Borrowed
if!self.bccx.is_subregion_of(self.loan_region, lt) {
self.bccx.report(
BckError {
span: self.span,
cause: self.cause,
cmt: cmt_base,
code: err_borrowed_pointer_too_short(
self.loan_region, lt)});
return Safe;
}
match bk {
ty::ImmBorrow => Safe,
ty::MutBorrow | ty::UniqueImmBorrow => {
// R-Deref-Mut-Borrowed
//
// The referent can be aliased after the
// references lifetime ends (by a newly-unfrozen
// borrow).
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpDeref(pk))
}
}
}
// Borrowck is not relevant for raw pointers
mc::UnsafePtr(..) => Safe
}
}
}
}
fn extend(&self,
result: RestrictionResult<'tcx>,
cmt: &mc::cmt<'tcx>,
elem: LoanPathElem) -> RestrictionResult<'tcx> {
match result {
Safe => Safe,
SafeIf(base_lp, mut base_vec) => {
let v = LpExtend(base_lp, cmt.mutbl, elem);
let lp = Rc::new(LoanPath::new(v, cmt.ty));
base_vec.push(lp.clone());
SafeIf(lp, base_vec)
}
}
}
}
|
{
// R-Deref-Send-Pointer
//
// When we borrow the interior of a box, we
// cannot permit the base to be mutated, because that
// would cause the unique pointer to be freed.
//
// Eventually we should make these non-special and
// just rely on Deref<T> implementation.
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpDeref(pk))
}
|
conditional_block
|
restrictions.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.
//! Computes the restrictions that result from a borrow.
pub use self::RestrictionResult::*;
use borrowck::*;
use rustc::middle::expr_use_visitor as euv;
use rustc::middle::mem_categorization as mc;
use rustc::middle::ty;
use syntax::codemap::Span;
use borrowck::ToInteriorKind;
use std::rc::Rc;
#[derive(Debug)]
pub enum RestrictionResult<'tcx> {
Safe,
SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>)
}
pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
span: Span,
cause: euv::LoanCause,
cmt: mc::cmt<'tcx>,
loan_region: ty::Region)
-> RestrictionResult<'tcx> {
let ctxt = RestrictionsContext {
bccx: bccx,
span: span,
cause: cause,
loan_region: loan_region,
};
ctxt.restrict(cmt)
}
///////////////////////////////////////////////////////////////////////////
// Private
struct RestrictionsContext<'a, 'tcx: 'a> {
bccx: &'a BorrowckCtxt<'a, 'tcx>,
span: Span,
loan_region: ty::Region,
cause: euv::LoanCause,
}
impl<'a, 'tcx> RestrictionsContext<'a, 'tcx> {
fn restrict(&self,
cmt: mc::cmt<'tcx>) -> RestrictionResult<'tcx> {
debug!("restrict(cmt={:?})", cmt);
let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
match cmt.cat.clone() {
mc::cat_rvalue(..) => {
// Effectively, rvalues are stored into a
// non-aliasable temporary on the stack. Since they
// are inherently non-aliasable, they can only be
// accessed later through the borrow itself and hence
// must inherently comply with its terms.
|
Safe
}
mc::cat_local(local_id) => {
// R-Variable, locally declared
let lp = new_lp(LpVar(local_id));
SafeIf(lp.clone(), vec![lp])
}
mc::cat_upvar(mc::Upvar { id,.. }) => {
// R-Variable, captured into closure
let lp = new_lp(LpUpvar(id));
SafeIf(lp.clone(), vec![lp])
}
mc::cat_downcast(cmt_base, _) => {
// When we borrow the interior of an enum, we have to
// ensure the enum itself is not mutated, because that
// could cause the type of the memory to change.
self.restrict(cmt_base)
}
mc::cat_interior(cmt_base, i) => {
// R-Field
//
// Overwriting the base would not change the type of
// the memory, so no additional restrictions are
// needed.
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpInterior(i.cleaned()))
}
mc::cat_static_item(..) => {
Safe
}
mc::cat_deref(cmt_base, _, pk) => {
match pk {
mc::Unique => {
// R-Deref-Send-Pointer
//
// When we borrow the interior of a box, we
// cannot permit the base to be mutated, because that
// would cause the unique pointer to be freed.
//
// Eventually we should make these non-special and
// just rely on Deref<T> implementation.
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpDeref(pk))
}
mc::Implicit(bk, lt) | mc::BorrowedPtr(bk, lt) => {
// R-Deref-[Mut-]Borrowed
if!self.bccx.is_subregion_of(self.loan_region, lt) {
self.bccx.report(
BckError {
span: self.span,
cause: self.cause,
cmt: cmt_base,
code: err_borrowed_pointer_too_short(
self.loan_region, lt)});
return Safe;
}
match bk {
ty::ImmBorrow => Safe,
ty::MutBorrow | ty::UniqueImmBorrow => {
// R-Deref-Mut-Borrowed
//
// The referent can be aliased after the
// references lifetime ends (by a newly-unfrozen
// borrow).
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpDeref(pk))
}
}
}
// Borrowck is not relevant for raw pointers
mc::UnsafePtr(..) => Safe
}
}
}
}
fn extend(&self,
result: RestrictionResult<'tcx>,
cmt: &mc::cmt<'tcx>,
elem: LoanPathElem) -> RestrictionResult<'tcx> {
match result {
Safe => Safe,
SafeIf(base_lp, mut base_vec) => {
let v = LpExtend(base_lp, cmt.mutbl, elem);
let lp = Rc::new(LoanPath::new(v, cmt.ty));
base_vec.push(lp.clone());
SafeIf(lp, base_vec)
}
}
}
}
|
random_line_split
|
|
restrictions.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.
//! Computes the restrictions that result from a borrow.
pub use self::RestrictionResult::*;
use borrowck::*;
use rustc::middle::expr_use_visitor as euv;
use rustc::middle::mem_categorization as mc;
use rustc::middle::ty;
use syntax::codemap::Span;
use borrowck::ToInteriorKind;
use std::rc::Rc;
#[derive(Debug)]
pub enum RestrictionResult<'tcx> {
Safe,
SafeIf(Rc<LoanPath<'tcx>>, Vec<Rc<LoanPath<'tcx>>>)
}
pub fn compute_restrictions<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>,
span: Span,
cause: euv::LoanCause,
cmt: mc::cmt<'tcx>,
loan_region: ty::Region)
-> RestrictionResult<'tcx> {
let ctxt = RestrictionsContext {
bccx: bccx,
span: span,
cause: cause,
loan_region: loan_region,
};
ctxt.restrict(cmt)
}
///////////////////////////////////////////////////////////////////////////
// Private
struct RestrictionsContext<'a, 'tcx: 'a> {
bccx: &'a BorrowckCtxt<'a, 'tcx>,
span: Span,
loan_region: ty::Region,
cause: euv::LoanCause,
}
impl<'a, 'tcx> RestrictionsContext<'a, 'tcx> {
fn
|
(&self,
cmt: mc::cmt<'tcx>) -> RestrictionResult<'tcx> {
debug!("restrict(cmt={:?})", cmt);
let new_lp = |v: LoanPathKind<'tcx>| Rc::new(LoanPath::new(v, cmt.ty));
match cmt.cat.clone() {
mc::cat_rvalue(..) => {
// Effectively, rvalues are stored into a
// non-aliasable temporary on the stack. Since they
// are inherently non-aliasable, they can only be
// accessed later through the borrow itself and hence
// must inherently comply with its terms.
Safe
}
mc::cat_local(local_id) => {
// R-Variable, locally declared
let lp = new_lp(LpVar(local_id));
SafeIf(lp.clone(), vec![lp])
}
mc::cat_upvar(mc::Upvar { id,.. }) => {
// R-Variable, captured into closure
let lp = new_lp(LpUpvar(id));
SafeIf(lp.clone(), vec![lp])
}
mc::cat_downcast(cmt_base, _) => {
// When we borrow the interior of an enum, we have to
// ensure the enum itself is not mutated, because that
// could cause the type of the memory to change.
self.restrict(cmt_base)
}
mc::cat_interior(cmt_base, i) => {
// R-Field
//
// Overwriting the base would not change the type of
// the memory, so no additional restrictions are
// needed.
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpInterior(i.cleaned()))
}
mc::cat_static_item(..) => {
Safe
}
mc::cat_deref(cmt_base, _, pk) => {
match pk {
mc::Unique => {
// R-Deref-Send-Pointer
//
// When we borrow the interior of a box, we
// cannot permit the base to be mutated, because that
// would cause the unique pointer to be freed.
//
// Eventually we should make these non-special and
// just rely on Deref<T> implementation.
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpDeref(pk))
}
mc::Implicit(bk, lt) | mc::BorrowedPtr(bk, lt) => {
// R-Deref-[Mut-]Borrowed
if!self.bccx.is_subregion_of(self.loan_region, lt) {
self.bccx.report(
BckError {
span: self.span,
cause: self.cause,
cmt: cmt_base,
code: err_borrowed_pointer_too_short(
self.loan_region, lt)});
return Safe;
}
match bk {
ty::ImmBorrow => Safe,
ty::MutBorrow | ty::UniqueImmBorrow => {
// R-Deref-Mut-Borrowed
//
// The referent can be aliased after the
// references lifetime ends (by a newly-unfrozen
// borrow).
let result = self.restrict(cmt_base);
self.extend(result, &cmt, LpDeref(pk))
}
}
}
// Borrowck is not relevant for raw pointers
mc::UnsafePtr(..) => Safe
}
}
}
}
fn extend(&self,
result: RestrictionResult<'tcx>,
cmt: &mc::cmt<'tcx>,
elem: LoanPathElem) -> RestrictionResult<'tcx> {
match result {
Safe => Safe,
SafeIf(base_lp, mut base_vec) => {
let v = LpExtend(base_lp, cmt.mutbl, elem);
let lp = Rc::new(LoanPath::new(v, cmt.ty));
base_vec.push(lp.clone());
SafeIf(lp, base_vec)
}
}
}
}
|
restrict
|
identifier_name
|
expr-match-generic-unique2.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true {
true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool
|
test_generic::<Box<isize>, _>(box 1, compare_box);
}
pub fn main() { test_vec(); }
|
{ return v1 == v2; }
|
identifier_body
|
expr-match-generic-unique2.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(box_syntax)]
fn test_generic<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true {
true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
|
pub fn main() { test_vec(); }
|
test_generic::<Box<isize>, _>(box 1, compare_box);
}
|
random_line_split
|
expr-match-generic-unique2.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![feature(box_syntax)]
fn
|
<T: Clone, F>(expected: T, eq: F) where F: FnOnce(T, T) -> bool {
let actual: T = match true {
true => expected.clone(),
_ => panic!("wat")
};
assert!(eq(expected, actual));
}
fn test_vec() {
fn compare_box(v1: Box<isize>, v2: Box<isize>) -> bool { return v1 == v2; }
test_generic::<Box<isize>, _>(box 1, compare_box);
}
pub fn main() { test_vec(); }
|
test_generic
|
identifier_name
|
main.rs
|
use std::convert::Infallible;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use hyper::service;
use hyper::{Body, Method, Request, Response, Server, StatusCode};
#[tokio::main]
async fn main() {
let listen_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080);
Server::bind(&listen_addr)
.serve(service::make_service_fn(|_conn| async {
Ok::<_, Infallible>(service::service_fn(|req| async {
Ok::<_, Infallible>(handle(req).await)
}))
}))
.await
.unwrap();
}
const ROLE_JSON: &str = r#"{
"Code" : "Success",
"LastUpdated" : "2015-08-04T00:09:23Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "Access_key_id_value",
"SecretAccessKey" : "Secret_access_key_value",
"Token" : "AAAAA",
"Expiration" : "2015-08-04T06:32:37Z"
}"#;
async fn handle(req: Request<Body>) -> Response<Body> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/latest/meta-data/iam/security-credentials/") =>
|
(&Method::GET, "/latest/meta-data/iam/security-credentials/testrole") => {
Response::new(Body::from(ROLE_JSON))
}
_ => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("unsupported"))
.unwrap(),
}
}
|
{
Response::new(Body::from("testrole"))
}
|
conditional_block
|
main.rs
|
use std::convert::Infallible;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use hyper::service;
use hyper::{Body, Method, Request, Response, Server, StatusCode};
#[tokio::main]
async fn main() {
let listen_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080);
Server::bind(&listen_addr)
.serve(service::make_service_fn(|_conn| async {
Ok::<_, Infallible>(service::service_fn(|req| async {
Ok::<_, Infallible>(handle(req).await)
}))
}))
.await
.unwrap();
}
|
"Type" : "AWS-HMAC",
"AccessKeyId" : "Access_key_id_value",
"SecretAccessKey" : "Secret_access_key_value",
"Token" : "AAAAA",
"Expiration" : "2015-08-04T06:32:37Z"
}"#;
async fn handle(req: Request<Body>) -> Response<Body> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/latest/meta-data/iam/security-credentials/") => {
Response::new(Body::from("testrole"))
}
(&Method::GET, "/latest/meta-data/iam/security-credentials/testrole") => {
Response::new(Body::from(ROLE_JSON))
}
_ => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("unsupported"))
.unwrap(),
}
}
|
const ROLE_JSON: &str = r#"{
"Code" : "Success",
"LastUpdated" : "2015-08-04T00:09:23Z",
|
random_line_split
|
main.rs
|
use std::convert::Infallible;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use hyper::service;
use hyper::{Body, Method, Request, Response, Server, StatusCode};
#[tokio::main]
async fn main() {
let listen_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080);
Server::bind(&listen_addr)
.serve(service::make_service_fn(|_conn| async {
Ok::<_, Infallible>(service::service_fn(|req| async {
Ok::<_, Infallible>(handle(req).await)
}))
}))
.await
.unwrap();
}
const ROLE_JSON: &str = r#"{
"Code" : "Success",
"LastUpdated" : "2015-08-04T00:09:23Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "Access_key_id_value",
"SecretAccessKey" : "Secret_access_key_value",
"Token" : "AAAAA",
"Expiration" : "2015-08-04T06:32:37Z"
}"#;
async fn handle(req: Request<Body>) -> Response<Body>
|
{
match (req.method(), req.uri().path()) {
(&Method::GET, "/latest/meta-data/iam/security-credentials/") => {
Response::new(Body::from("testrole"))
}
(&Method::GET, "/latest/meta-data/iam/security-credentials/testrole") => {
Response::new(Body::from(ROLE_JSON))
}
_ => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("unsupported"))
.unwrap(),
}
}
|
identifier_body
|
|
main.rs
|
use std::convert::Infallible;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use hyper::service;
use hyper::{Body, Method, Request, Response, Server, StatusCode};
#[tokio::main]
async fn main() {
let listen_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8080);
Server::bind(&listen_addr)
.serve(service::make_service_fn(|_conn| async {
Ok::<_, Infallible>(service::service_fn(|req| async {
Ok::<_, Infallible>(handle(req).await)
}))
}))
.await
.unwrap();
}
const ROLE_JSON: &str = r#"{
"Code" : "Success",
"LastUpdated" : "2015-08-04T00:09:23Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "Access_key_id_value",
"SecretAccessKey" : "Secret_access_key_value",
"Token" : "AAAAA",
"Expiration" : "2015-08-04T06:32:37Z"
}"#;
async fn
|
(req: Request<Body>) -> Response<Body> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/latest/meta-data/iam/security-credentials/") => {
Response::new(Body::from("testrole"))
}
(&Method::GET, "/latest/meta-data/iam/security-credentials/testrole") => {
Response::new(Body::from(ROLE_JSON))
}
_ => Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("unsupported"))
.unwrap(),
}
}
|
handle
|
identifier_name
|
traits.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.
//xfail-test
// Sketching traits.
// methods with no implementation are required; methods with an
// implementation are provided. No "req" keyword necessary.
trait Eq {
fn eq(a: self) -> bool;
fn neq(a: self) -> bool
|
}
// The `<` is pronounced `extends`. Also under consideration is `<:`.
// Just using `:` is frowned upon, because (paraphrasing dherman) `:`
// is supposed to separate things from different universes.
trait Ord < Eq {
fn lt(a: self) -> bool;
fn lte(a: self) -> bool {
self.lt(a) || self.eq(a)
}
fn gt(a: self) -> bool {
!self.lt(a) &&!self.eq(a)
}
fn gte(a: self) -> bool {
!self.lt(a)
}
}
// pronounced "impl of Ord for int" -- not sold on this yet
impl Ord for int {
fn lt(a: &int) -> bool {
self < (*a)
}
// is this the place to put this?
fn eq(a: &int) -> bool {
self == (*a)
}
}
|
{
!self.eq(a)
}
|
identifier_body
|
traits.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.
//xfail-test
|
// methods with no implementation are required; methods with an
// implementation are provided. No "req" keyword necessary.
trait Eq {
fn eq(a: self) -> bool;
fn neq(a: self) -> bool {
!self.eq(a)
}
}
// The `<` is pronounced `extends`. Also under consideration is `<:`.
// Just using `:` is frowned upon, because (paraphrasing dherman) `:`
// is supposed to separate things from different universes.
trait Ord < Eq {
fn lt(a: self) -> bool;
fn lte(a: self) -> bool {
self.lt(a) || self.eq(a)
}
fn gt(a: self) -> bool {
!self.lt(a) &&!self.eq(a)
}
fn gte(a: self) -> bool {
!self.lt(a)
}
}
// pronounced "impl of Ord for int" -- not sold on this yet
impl Ord for int {
fn lt(a: &int) -> bool {
self < (*a)
}
// is this the place to put this?
fn eq(a: &int) -> bool {
self == (*a)
}
}
|
// Sketching traits.
|
random_line_split
|
traits.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.
//xfail-test
// Sketching traits.
// methods with no implementation are required; methods with an
// implementation are provided. No "req" keyword necessary.
trait Eq {
fn eq(a: self) -> bool;
fn neq(a: self) -> bool {
!self.eq(a)
}
}
// The `<` is pronounced `extends`. Also under consideration is `<:`.
// Just using `:` is frowned upon, because (paraphrasing dherman) `:`
// is supposed to separate things from different universes.
trait Ord < Eq {
fn lt(a: self) -> bool;
fn lte(a: self) -> bool {
self.lt(a) || self.eq(a)
}
fn
|
(a: self) -> bool {
!self.lt(a) &&!self.eq(a)
}
fn gte(a: self) -> bool {
!self.lt(a)
}
}
// pronounced "impl of Ord for int" -- not sold on this yet
impl Ord for int {
fn lt(a: &int) -> bool {
self < (*a)
}
// is this the place to put this?
fn eq(a: &int) -> bool {
self == (*a)
}
}
|
gt
|
identifier_name
|
block-disambig.rs
|
// compile-flags: --crate-type=lib
// A bunch of tests for syntactic forms involving blocks that were
// previously ambiguous (e.g., 'if true { } *val;' gets parsed as a
// binop)
use std::cell::Cell;
fn test1() { let val = &0; { } *val; }
fn test2() -> isize { let val = &0; { } *val }
#[derive(Copy, Clone)]
struct S { eax: isize }
fn test3() {
let regs = &Cell::new(S {eax: 0});
match true { true => { } _ => { } }
regs.set(S {eax: 1});
}
fn test4() -> bool { let regs = &true; if true { } *regs || false }
fn test5() -> (isize, isize) { { } (0, 1) }
fn test6() -> bool { { } (true || false) && true }
fn test7() -> usize {
let regs = &0;
match true { true => { } _ => { } }
(*regs < 2) as usize
}
fn test8() -> isize {
let val = &0;
match true {
true => { }
_ => { }
}
if *val < 1 {
0
} else {
1
}
}
fn test9() {
let regs = &Cell::new(0);
match true { true => { } _ => { } } regs.set(regs.get() + 1);
}
fn test10() -> isize {
let regs = vec![0];
match true { true => { } _ => { } }
regs[0]
}
fn
|
() -> Vec<isize> { if true { } vec![1, 2] }
|
test11
|
identifier_name
|
block-disambig.rs
|
// compile-flags: --crate-type=lib
// A bunch of tests for syntactic forms involving blocks that were
// previously ambiguous (e.g., 'if true { } *val;' gets parsed as a
// binop)
use std::cell::Cell;
fn test1() { let val = &0; { } *val; }
fn test2() -> isize { let val = &0; { } *val }
#[derive(Copy, Clone)]
struct S { eax: isize }
fn test3() {
let regs = &Cell::new(S {eax: 0});
match true { true =>
|
_ => { } }
regs.set(S {eax: 1});
}
fn test4() -> bool { let regs = &true; if true { } *regs || false }
fn test5() -> (isize, isize) { { } (0, 1) }
fn test6() -> bool { { } (true || false) && true }
fn test7() -> usize {
let regs = &0;
match true { true => { } _ => { } }
(*regs < 2) as usize
}
fn test8() -> isize {
let val = &0;
match true {
true => { }
_ => { }
}
if *val < 1 {
0
} else {
1
}
}
fn test9() {
let regs = &Cell::new(0);
match true { true => { } _ => { } } regs.set(regs.get() + 1);
}
fn test10() -> isize {
let regs = vec![0];
match true { true => { } _ => { } }
regs[0]
}
fn test11() -> Vec<isize> { if true { } vec![1, 2] }
|
{ }
|
conditional_block
|
block-disambig.rs
|
// compile-flags: --crate-type=lib
// A bunch of tests for syntactic forms involving blocks that were
// previously ambiguous (e.g., 'if true { } *val;' gets parsed as a
// binop)
use std::cell::Cell;
fn test1() { let val = &0; { } *val; }
fn test2() -> isize { let val = &0; { } *val }
#[derive(Copy, Clone)]
struct S { eax: isize }
fn test3() {
let regs = &Cell::new(S {eax: 0});
match true { true => { } _ => { } }
regs.set(S {eax: 1});
}
|
fn test6() -> bool { { } (true || false) && true }
fn test7() -> usize {
let regs = &0;
match true { true => { } _ => { } }
(*regs < 2) as usize
}
fn test8() -> isize {
let val = &0;
match true {
true => { }
_ => { }
}
if *val < 1 {
0
} else {
1
}
}
fn test9() {
let regs = &Cell::new(0);
match true { true => { } _ => { } } regs.set(regs.get() + 1);
}
fn test10() -> isize {
let regs = vec![0];
match true { true => { } _ => { } }
regs[0]
}
fn test11() -> Vec<isize> { if true { } vec![1, 2] }
|
fn test4() -> bool { let regs = &true; if true { } *regs || false }
fn test5() -> (isize, isize) { { } (0, 1) }
|
random_line_split
|
block-disambig.rs
|
// compile-flags: --crate-type=lib
// A bunch of tests for syntactic forms involving blocks that were
// previously ambiguous (e.g., 'if true { } *val;' gets parsed as a
// binop)
use std::cell::Cell;
fn test1() { let val = &0; { } *val; }
fn test2() -> isize { let val = &0; { } *val }
#[derive(Copy, Clone)]
struct S { eax: isize }
fn test3() {
let regs = &Cell::new(S {eax: 0});
match true { true => { } _ => { } }
regs.set(S {eax: 1});
}
fn test4() -> bool { let regs = &true; if true { } *regs || false }
fn test5() -> (isize, isize) { { } (0, 1) }
fn test6() -> bool { { } (true || false) && true }
fn test7() -> usize
|
fn test8() -> isize {
let val = &0;
match true {
true => { }
_ => { }
}
if *val < 1 {
0
} else {
1
}
}
fn test9() {
let regs = &Cell::new(0);
match true { true => { } _ => { } } regs.set(regs.get() + 1);
}
fn test10() -> isize {
let regs = vec![0];
match true { true => { } _ => { } }
regs[0]
}
fn test11() -> Vec<isize> { if true { } vec![1, 2] }
|
{
let regs = &0;
match true { true => { } _ => { } }
(*regs < 2) as usize
}
|
identifier_body
|
lib.rs
|
// Copyright Cryptape Technologies LLC.
//
// 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,
|
// See the License for the specific language governing permissions and
// limitations under the License.
#[macro_use]
extern crate libproto;
#[macro_use]
extern crate cita_logger as logger;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate util;
#[cfg(test)]
extern crate cita_crypto;
extern crate cita_database as cita_db;
extern crate common_types as types;
pub mod filters;
pub mod libchain;
pub use crate::types::*;
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
random_line_split
|
mod.rs
|
/************************************************************************
* *
* Copyright 2014 Thomas Poinsot, Urban Hafner *
* Copyright 2015 Urban Hafner, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
#![cfg(test)]
use board::Black;
use board::IllegalMove;
use board::Pass;
use board::Play;
use board::Resign;
use board::White;
use game::Game;
use ruleset::KgsChinese;
mod ko;
#[test]
fn catch_su
|
let mut g = Game::new(3, 6.5, KgsChinese);
g = g.play(Play(Black, 2, 2)).unwrap();
g = g.play(Play(White, 1, 2)).unwrap();
g = g.play(Play(Black, 2, 1)).unwrap();
g = g.play(Play(White, 3, 2)).unwrap();
g = g.play(Play(Black, 2, 3)).unwrap();
g = g.play(Play(White, 3, 1)).unwrap();
g = g.play(Pass(Black)).unwrap();
g = g.play(Play(White, 1, 3)).unwrap();
g = g.play(Pass(Black)).unwrap();
let play = g.play(Play(White, 1, 1));
match play {
Err(e) => assert_eq!(e, IllegalMove::SuicidePlay),
Ok(_) => panic!("Expected Err!")
}
}
#[test]
fn it_should_handle_resign() {
let g = Game::new(9, 6.5, KgsChinese);
let res = g.play(Resign(Black));
assert!(res.is_ok());
}
|
icide_moves_in_chinese() {
|
identifier_name
|
mod.rs
|
/************************************************************************
* *
* Copyright 2014 Thomas Poinsot, Urban Hafner *
* Copyright 2015 Urban Hafner, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
#![cfg(test)]
use board::Black;
use board::IllegalMove;
use board::Pass;
use board::Play;
use board::Resign;
use board::White;
use game::Game;
use ruleset::KgsChinese;
mod ko;
#[test]
fn catch_suicide_moves_in_chinese() {
let mut g = Game::new(3, 6.5, KgsChinese);
g = g.play(Play(Black, 2, 2)).unwrap();
g = g.play(Play(White, 1, 2)).unwrap();
g = g.play(Play(Black, 2, 1)).unwrap();
g = g.play(Play(White, 3, 2)).unwrap();
g = g.play(Play(Black, 2, 3)).unwrap();
g = g.play(Play(White, 3, 1)).unwrap();
g = g.play(Pass(Black)).unwrap();
g = g.play(Play(White, 1, 3)).unwrap();
g = g.play(Pass(Black)).unwrap();
let play = g.play(Play(White, 1, 1));
match play {
Err(e) => assert_eq!(e, IllegalMove::SuicidePlay),
Ok(_) => panic!("Expected Err!")
}
}
#[test]
fn it_should_handle_resign() {
le
|
t g = Game::new(9, 6.5, KgsChinese);
let res = g.play(Resign(Black));
assert!(res.is_ok());
}
|
identifier_body
|
|
mod.rs
|
/************************************************************************
* *
* Copyright 2014 Thomas Poinsot, Urban Hafner *
* Copyright 2015 Urban Hafner, Igor Polyakov *
* *
* This file is part of Iomrascálaí. *
* *
* Iomrascálaí is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* Iomrascálaí is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with Iomrascálaí. If not, see <http://www.gnu.org/licenses/>. *
* *
************************************************************************/
#![cfg(test)]
use board::Black;
use board::IllegalMove;
use board::Pass;
use board::Play;
use board::Resign;
use board::White;
use game::Game;
use ruleset::KgsChinese;
mod ko;
#[test]
fn catch_suicide_moves_in_chinese() {
let mut g = Game::new(3, 6.5, KgsChinese);
g = g.play(Play(Black, 2, 2)).unwrap();
g = g.play(Play(White, 1, 2)).unwrap();
g = g.play(Play(Black, 2, 1)).unwrap();
g = g.play(Play(White, 3, 2)).unwrap();
g = g.play(Play(Black, 2, 3)).unwrap();
g = g.play(Play(White, 3, 1)).unwrap();
g = g.play(Pass(Black)).unwrap();
g = g.play(Play(White, 1, 3)).unwrap();
g = g.play(Pass(Black)).unwrap();
|
Err(e) => assert_eq!(e, IllegalMove::SuicidePlay),
Ok(_) => panic!("Expected Err!")
}
}
#[test]
fn it_should_handle_resign() {
let g = Game::new(9, 6.5, KgsChinese);
let res = g.play(Resign(Black));
assert!(res.is_ok());
}
|
let play = g.play(Play(White, 1, 1));
match play {
|
random_line_split
|
mod.rs
|
pub type c_long = i32;
pub type c_ulong = u32;
pub type nlink_t = u32;
pub type blksize_t = ::c_long;
pub type __u64 = ::c_ulonglong;
pub type regoff_t = ::c_int;
s! {
pub struct pthread_attr_t {
__size: [u32; 9]
}
pub struct sigset_t {
__val: [::c_ulong; 32],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg_iov: *mut ::iovec,
pub msg_iovlen: ::c_int,
pub msg_control: *mut ::c_void,
pub msg_controllen: ::socklen_t,
pub msg_flags: ::c_int,
}
pub struct cmsghdr {
pub cmsg_len: ::socklen_t,
pub cmsg_level: ::c_int,
pub cmsg_type: ::c_int,
}
pub struct sem_t {
__val: [::c_int; 4],
}
}
pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32;
pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24;
pub const TIOCINQ: ::c_int = ::FIONREAD;
extern "C" {
|
cfg_if! {
if #[cfg(any(target_arch = "x86"))] {
mod x86;
pub use self::x86::*;
} else if #[cfg(any(target_arch = "mips"))] {
mod mips;
pub use self::mips::*;
} else if #[cfg(any(target_arch = "arm"))] {
mod arm;
pub use self::arm::*;
} else if #[cfg(any(target_arch = "powerpc"))] {
mod powerpc;
pub use self::powerpc::*;
} else if #[cfg(any(target_arch = "hexagon"))] {
mod hexagon;
pub use self::hexagon::*;
} else {
// Unknown target_arch
}
}
|
pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int;
}
|
random_line_split
|
lib.rs
|
extern crate rand;
use rand::{Rng, SeedableRng, XorShiftRng};
use std::cmp;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
pub struct Corpus {
seed: [u32; 4],
max_context: usize,
words: Vec<String>,
table: HashMap<Vec<String>, BTreeMap<String, f64>>,
}
pub struct Chain<'a> {
rng: XorShiftRng,
history: VecDeque<String>,
corpus: &'a Corpus,
}
impl Corpus {
pub fn new(path: &Path, max_context: usize) -> io::Result<Corpus> {
let mut f = try!(File::open(path));
let mut buffer = String::new();
try!(f.read_to_string(&mut buffer));
let words: Vec<String> = buffer.split_whitespace()
.map(|s| s.to_lowercase())
.collect();
let mut builder = HashMap::new();
let mut history = VecDeque::new();
history.push_back(words[0].clone());
for word in &words[1..] {
let hist_len = history.len();
for skip in 0..cmp::min(hist_len, max_context) {
let key: Vec<String> = history.iter()
.skip(skip)
.cloned()
.collect();
let word_list = builder.entry(key).or_insert(vec![]);
word_list.push(word.clone());
}
history.push_back(word.clone());
if history.len() > max_context {
history.pop_front();
}
}
let mut table = HashMap::new();
for (history, words) in builder.drain() {
let mut word_count = HashMap::new();
let total_words = words.len() as u32;
for word in words {
let count = word_count.entry(word).or_insert(0u32);
*count += 1;
}
let mut word_probs = BTreeMap::new();
for (word, count) in word_count.drain() {
word_probs.insert(word, f64::from(count) / f64::from(total_words));
}
table.insert(history.into_iter().collect(), word_probs);
}
let mut rng = rand::thread_rng();
let seed = [rng.gen(), rng.gen(), rng.gen(), rng.gen()];
Ok(Corpus {
seed: seed,
max_context: max_context,
words: words,
table: table,
})
}
pub fn seed(&mut self, seed: [u32; 4]) {
self.seed = seed;
}
pub fn get_seed(&self) -> [u32; 4]
|
pub fn words(&self, start: &[&str]) -> Chain {
Chain {
rng: SeedableRng::from_seed(self.seed),
history: start.iter()
.map(|&s| s.to_lowercase())
.collect(),
corpus: self,
}
}
}
impl<'a> Iterator for Chain<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
while self.history.len() > self.corpus.max_context {
self.history.pop_front();
}
let hist_len = self.history.len();
if hist_len > 0 {
for skip in 0..hist_len {
let key: Vec<String> = self.history.iter()
.skip(skip)
.cloned()
.collect();
match self.corpus.table.get(&key) {
Some(word_probs) => {
let r = self.rng.gen::<f64>();
let mut acc = 0.0;
for (word, prob) in word_probs {
acc += *prob;
if acc > r {
self.history.push_back(word.clone());
return Some(word)
}
}
unreachable!("failed to pick a word")
}
None => {}
}
}
}
let word = self.rng.choose(&self.corpus.words)
.expect("corpus words shouldn't be empty");
self.history.push_back(word.clone());
Some(word)
}
}
|
{
self.seed
}
|
identifier_body
|
lib.rs
|
extern crate rand;
use rand::{Rng, SeedableRng, XorShiftRng};
use std::cmp;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
pub struct Corpus {
seed: [u32; 4],
max_context: usize,
words: Vec<String>,
table: HashMap<Vec<String>, BTreeMap<String, f64>>,
}
pub struct Chain<'a> {
rng: XorShiftRng,
history: VecDeque<String>,
corpus: &'a Corpus,
}
impl Corpus {
pub fn new(path: &Path, max_context: usize) -> io::Result<Corpus> {
let mut f = try!(File::open(path));
let mut buffer = String::new();
try!(f.read_to_string(&mut buffer));
let words: Vec<String> = buffer.split_whitespace()
.map(|s| s.to_lowercase())
.collect();
let mut builder = HashMap::new();
let mut history = VecDeque::new();
history.push_back(words[0].clone());
for word in &words[1..] {
let hist_len = history.len();
for skip in 0..cmp::min(hist_len, max_context) {
let key: Vec<String> = history.iter()
.skip(skip)
.cloned()
.collect();
let word_list = builder.entry(key).or_insert(vec![]);
word_list.push(word.clone());
}
history.push_back(word.clone());
if history.len() > max_context {
history.pop_front();
}
}
let mut table = HashMap::new();
for (history, words) in builder.drain() {
let mut word_count = HashMap::new();
let total_words = words.len() as u32;
for word in words {
let count = word_count.entry(word).or_insert(0u32);
*count += 1;
}
let mut word_probs = BTreeMap::new();
for (word, count) in word_count.drain() {
word_probs.insert(word, f64::from(count) / f64::from(total_words));
}
table.insert(history.into_iter().collect(), word_probs);
}
let mut rng = rand::thread_rng();
let seed = [rng.gen(), rng.gen(), rng.gen(), rng.gen()];
Ok(Corpus {
seed: seed,
max_context: max_context,
words: words,
table: table,
})
}
pub fn seed(&mut self, seed: [u32; 4]) {
self.seed = seed;
}
pub fn get_seed(&self) -> [u32; 4] {
self.seed
}
pub fn
|
(&self, start: &[&str]) -> Chain {
Chain {
rng: SeedableRng::from_seed(self.seed),
history: start.iter()
.map(|&s| s.to_lowercase())
.collect(),
corpus: self,
}
}
}
impl<'a> Iterator for Chain<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
while self.history.len() > self.corpus.max_context {
self.history.pop_front();
}
let hist_len = self.history.len();
if hist_len > 0 {
for skip in 0..hist_len {
let key: Vec<String> = self.history.iter()
.skip(skip)
.cloned()
.collect();
match self.corpus.table.get(&key) {
Some(word_probs) => {
let r = self.rng.gen::<f64>();
let mut acc = 0.0;
for (word, prob) in word_probs {
acc += *prob;
if acc > r {
self.history.push_back(word.clone());
return Some(word)
}
}
unreachable!("failed to pick a word")
}
None => {}
}
}
}
let word = self.rng.choose(&self.corpus.words)
.expect("corpus words shouldn't be empty");
self.history.push_back(word.clone());
Some(word)
}
}
|
words
|
identifier_name
|
lib.rs
|
extern crate rand;
use rand::{Rng, SeedableRng, XorShiftRng};
use std::cmp;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
pub struct Corpus {
seed: [u32; 4],
max_context: usize,
words: Vec<String>,
table: HashMap<Vec<String>, BTreeMap<String, f64>>,
}
pub struct Chain<'a> {
rng: XorShiftRng,
history: VecDeque<String>,
corpus: &'a Corpus,
}
impl Corpus {
pub fn new(path: &Path, max_context: usize) -> io::Result<Corpus> {
let mut f = try!(File::open(path));
let mut buffer = String::new();
try!(f.read_to_string(&mut buffer));
let words: Vec<String> = buffer.split_whitespace()
.map(|s| s.to_lowercase())
.collect();
let mut builder = HashMap::new();
let mut history = VecDeque::new();
history.push_back(words[0].clone());
for word in &words[1..] {
let hist_len = history.len();
for skip in 0..cmp::min(hist_len, max_context) {
let key: Vec<String> = history.iter()
.skip(skip)
.cloned()
.collect();
let word_list = builder.entry(key).or_insert(vec![]);
word_list.push(word.clone());
}
history.push_back(word.clone());
if history.len() > max_context {
history.pop_front();
}
}
let mut table = HashMap::new();
for (history, words) in builder.drain() {
let mut word_count = HashMap::new();
let total_words = words.len() as u32;
for word in words {
let count = word_count.entry(word).or_insert(0u32);
*count += 1;
}
let mut word_probs = BTreeMap::new();
for (word, count) in word_count.drain() {
word_probs.insert(word, f64::from(count) / f64::from(total_words));
}
table.insert(history.into_iter().collect(), word_probs);
}
let mut rng = rand::thread_rng();
let seed = [rng.gen(), rng.gen(), rng.gen(), rng.gen()];
Ok(Corpus {
seed: seed,
max_context: max_context,
words: words,
table: table,
})
}
pub fn seed(&mut self, seed: [u32; 4]) {
self.seed = seed;
}
pub fn get_seed(&self) -> [u32; 4] {
self.seed
}
pub fn words(&self, start: &[&str]) -> Chain {
Chain {
rng: SeedableRng::from_seed(self.seed),
history: start.iter()
.map(|&s| s.to_lowercase())
.collect(),
corpus: self,
}
}
}
impl<'a> Iterator for Chain<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
while self.history.len() > self.corpus.max_context {
self.history.pop_front();
}
let hist_len = self.history.len();
if hist_len > 0 {
for skip in 0..hist_len {
let key: Vec<String> = self.history.iter()
.skip(skip)
.cloned()
.collect();
match self.corpus.table.get(&key) {
Some(word_probs) =>
|
None => {}
}
}
}
let word = self.rng.choose(&self.corpus.words)
.expect("corpus words shouldn't be empty");
self.history.push_back(word.clone());
Some(word)
}
}
|
{
let r = self.rng.gen::<f64>();
let mut acc = 0.0;
for (word, prob) in word_probs {
acc += *prob;
if acc > r {
self.history.push_back(word.clone());
return Some(word)
}
}
unreachable!("failed to pick a word")
}
|
conditional_block
|
lib.rs
|
extern crate rand;
use rand::{Rng, SeedableRng, XorShiftRng};
use std::cmp;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
pub struct Corpus {
seed: [u32; 4],
max_context: usize,
|
pub struct Chain<'a> {
rng: XorShiftRng,
history: VecDeque<String>,
corpus: &'a Corpus,
}
impl Corpus {
pub fn new(path: &Path, max_context: usize) -> io::Result<Corpus> {
let mut f = try!(File::open(path));
let mut buffer = String::new();
try!(f.read_to_string(&mut buffer));
let words: Vec<String> = buffer.split_whitespace()
.map(|s| s.to_lowercase())
.collect();
let mut builder = HashMap::new();
let mut history = VecDeque::new();
history.push_back(words[0].clone());
for word in &words[1..] {
let hist_len = history.len();
for skip in 0..cmp::min(hist_len, max_context) {
let key: Vec<String> = history.iter()
.skip(skip)
.cloned()
.collect();
let word_list = builder.entry(key).or_insert(vec![]);
word_list.push(word.clone());
}
history.push_back(word.clone());
if history.len() > max_context {
history.pop_front();
}
}
let mut table = HashMap::new();
for (history, words) in builder.drain() {
let mut word_count = HashMap::new();
let total_words = words.len() as u32;
for word in words {
let count = word_count.entry(word).or_insert(0u32);
*count += 1;
}
let mut word_probs = BTreeMap::new();
for (word, count) in word_count.drain() {
word_probs.insert(word, f64::from(count) / f64::from(total_words));
}
table.insert(history.into_iter().collect(), word_probs);
}
let mut rng = rand::thread_rng();
let seed = [rng.gen(), rng.gen(), rng.gen(), rng.gen()];
Ok(Corpus {
seed: seed,
max_context: max_context,
words: words,
table: table,
})
}
pub fn seed(&mut self, seed: [u32; 4]) {
self.seed = seed;
}
pub fn get_seed(&self) -> [u32; 4] {
self.seed
}
pub fn words(&self, start: &[&str]) -> Chain {
Chain {
rng: SeedableRng::from_seed(self.seed),
history: start.iter()
.map(|&s| s.to_lowercase())
.collect(),
corpus: self,
}
}
}
impl<'a> Iterator for Chain<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
while self.history.len() > self.corpus.max_context {
self.history.pop_front();
}
let hist_len = self.history.len();
if hist_len > 0 {
for skip in 0..hist_len {
let key: Vec<String> = self.history.iter()
.skip(skip)
.cloned()
.collect();
match self.corpus.table.get(&key) {
Some(word_probs) => {
let r = self.rng.gen::<f64>();
let mut acc = 0.0;
for (word, prob) in word_probs {
acc += *prob;
if acc > r {
self.history.push_back(word.clone());
return Some(word)
}
}
unreachable!("failed to pick a word")
}
None => {}
}
}
}
let word = self.rng.choose(&self.corpus.words)
.expect("corpus words shouldn't be empty");
self.history.push_back(word.clone());
Some(word)
}
}
|
words: Vec<String>,
table: HashMap<Vec<String>, BTreeMap<String, f64>>,
}
|
random_line_split
|
sound.rs
|
//! Manages the gameboy sound controller
//! This is mostly incomplete, at the moment all this does is manage the sound registers.
pub struct SoundController {
/// Channel 1 Sweep register
pub nr10: u8,
/// Channel 1 Sound length/Wave pattern duty
pub nr11: u8,
/// Channel 1 Volume Envelope (R/W)
pub nr12: u8,
/// Channel 1 Frequency lo
pub nr13: u8,
/// Channel 1 Frequency hi
pub nr14: u8,
/// Channel 2 Sound length/Wave pattern duty
pub nr21: u8,
/// Channel 2 Volume Envelope (R/W)
pub nr22: u8,
/// Channel 2 Frequency lo
pub nr23: u8,
/// Channel 2 Frequency hi
pub nr24: u8,
pub nr30: u8,
pub nr31: u8,
pub nr32: u8,
pub nr33: u8,
pub nr34: u8,
pub wave_pattern_ram: [u8; 32],
pub nr41: u8,
pub nr42: u8,
pub nr43: u8,
pub nr44: u8,
pub nr50: u8,
pub nr51: u8,
pub nr52: u8,
}
impl SoundController {
pub fn
|
() -> SoundController {
SoundController {
nr10: 0,
nr11: 0,
nr12: 0,
nr13: 0,
nr14: 0,
nr21: 0,
nr22: 0,
nr23: 0,
nr24: 0,
nr30: 0,
nr31: 0,
nr32: 0,
nr33: 0,
nr34: 0,
wave_pattern_ram: [0; 32],
nr41: 0,
nr42: 0,
nr43: 0,
nr44: 0,
nr50: 0,
nr51: 0,
nr52: 0,
}
}
}
|
new
|
identifier_name
|
sound.rs
|
//! Manages the gameboy sound controller
//! This is mostly incomplete, at the moment all this does is manage the sound registers.
|
/// Channel 1 Volume Envelope (R/W)
pub nr12: u8,
/// Channel 1 Frequency lo
pub nr13: u8,
/// Channel 1 Frequency hi
pub nr14: u8,
/// Channel 2 Sound length/Wave pattern duty
pub nr21: u8,
/// Channel 2 Volume Envelope (R/W)
pub nr22: u8,
/// Channel 2 Frequency lo
pub nr23: u8,
/// Channel 2 Frequency hi
pub nr24: u8,
pub nr30: u8,
pub nr31: u8,
pub nr32: u8,
pub nr33: u8,
pub nr34: u8,
pub wave_pattern_ram: [u8; 32],
pub nr41: u8,
pub nr42: u8,
pub nr43: u8,
pub nr44: u8,
pub nr50: u8,
pub nr51: u8,
pub nr52: u8,
}
impl SoundController {
pub fn new() -> SoundController {
SoundController {
nr10: 0,
nr11: 0,
nr12: 0,
nr13: 0,
nr14: 0,
nr21: 0,
nr22: 0,
nr23: 0,
nr24: 0,
nr30: 0,
nr31: 0,
nr32: 0,
nr33: 0,
nr34: 0,
wave_pattern_ram: [0; 32],
nr41: 0,
nr42: 0,
nr43: 0,
nr44: 0,
nr50: 0,
nr51: 0,
nr52: 0,
}
}
}
|
pub struct SoundController {
/// Channel 1 Sweep register
pub nr10: u8,
/// Channel 1 Sound length/Wave pattern duty
pub nr11: u8,
|
random_line_split
|
fold.rs
|
#![crate_name = "fold"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, stdin, Write};
use std::path::Path;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
static NAME: &'static str = "fold";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
let (args, obs_width) = handle_obsolete(&args[..]);
let mut opts = getopts::Options::new();
opts.optflag("b", "bytes", "count using bytes rather than columns (meaning control characters such as newline are not treated specially)");
opts.optflag("s", "spaces", "break lines at word boundaries rather than a hard cut-off");
opts.optopt("w", "width", "set WIDTH as the maximum line width rather than 80", "WIDTH");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f)
};
if matches.opt_present("h")
|
else if matches.opt_present("V") {
println!("{} {}", NAME, VERSION);
} else {
let bytes = matches.opt_present("b");
let spaces = matches.opt_present("s");
let poss_width =
if matches.opt_present("w") {
matches.opt_str("w")
} else {
match obs_width {
Some(v) => Some(v.to_string()),
None => None,
}
};
let width = match poss_width {
Some(inp_width) => match inp_width.parse::<usize>() {
Ok(width) => width,
Err(e) => crash!(1, "illegal width value (\"{}\"): {}", inp_width, e)
},
None => 80
};
let files = if matches.free.is_empty() {
vec!("-".to_string())
} else {
matches.free
};
fold(files, bytes, spaces, width);
}
0
}
fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
for (i, arg) in args.iter().enumerate() {
let slice = &arg;
if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
let mut v = args.to_vec();
v.remove(i);
return (v, Some(slice[1..].to_string()));
}
}
(args.to_vec(), None)
}
#[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
for filename in filenames.iter() {
let filename: &str = &filename;
let mut stdin_buf;
let mut file_buf;
let buffer = BufReader::new(
if filename == "-" {
stdin_buf = stdin();
&mut stdin_buf as &mut Read
} else {
file_buf = safe_unwrap!(File::open(Path::new(filename)));
&mut file_buf as &mut Read
}
);
fold_file(buffer, bytes, spaces, width);
}
}
#[inline]
fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width: usize) {
let mut line = String::new();
while safe_unwrap!(file.read_line(&mut line)) > 0 {
if bytes {
let len = line.len();
let mut i = 0;
while i < len {
let width = if len - i >= width { width } else { len - i };
let slice = {
let slice = &line[i..i + width];
if spaces && i + width < len {
match slice.rfind(|ch: char| ch.is_whitespace()) {
Some(m) => &slice[..m + 1],
None => slice
}
} else {
slice
}
};
print!("{}", slice);
i += slice.len();
}
} else {
let mut len = line.chars().count();
let newline = line.ends_with("\n");
if newline {
if len == 1 {
println!("");
continue;
}
len -= 1;
line.truncate(len);
}
let mut output = String::new();
let mut count = 0;
for (i, ch) in line.chars().enumerate() {
if count >= width {
let (val, ncount) = {
let slice = &output[..];
let (out, val, ncount) =
if spaces && i + 1 < len {
match rfind_whitespace(slice) {
Some(m) => {
let routput = &slice[m + 1.. slice.chars().count()];
let ncount = routput.chars().fold(0usize, |out, ch: char| {
out + match ch {
'\t' => 8,
'\x08' => if out > 0 { -1 } else { 0 },
'\r' => return 0,
_ => 1
}
});
(&slice[0.. m + 1], routput, ncount)
},
None => (slice, "", 0)
}
} else {
(slice, "", 0)
};
println!("{}", out);
(val.to_string(), ncount)
};
output = val;
count = ncount;
}
match ch {
'\t' => {
count += 8;
if count > width {
println!("{}", output);
output.truncate(0);
count = 8;
}
}
'\x08' => {
if count > 0 {
count -= 1;
let len = output.len() - 1;
output.truncate(len);
}
continue;
}
'\r' => {
output.truncate(0);
count = 0;
continue;
}
_ => count += 1
};
output.push(ch);
}
if count > 0 {
if newline {
println!("{}", output);
} else {
print!("{}", output);
}
}
}
}
}
#[inline]
fn rfind_whitespace(slice: &str) -> Option<usize> {
for (i, ch) in slice.chars().rev().enumerate() {
if ch.is_whitespace() {
return Some(slice.chars().count() - (i + 1));
}
}
None
}
|
{
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]...", NAME);
println!("");
print!("{}", opts.usage("Writes each file (or standard input if no files are given) to standard output whilst breaking long lines"));
}
|
conditional_block
|
fold.rs
|
#![crate_name = "fold"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, stdin, Write};
use std::path::Path;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
static NAME: &'static str = "fold";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
let (args, obs_width) = handle_obsolete(&args[..]);
let mut opts = getopts::Options::new();
opts.optflag("b", "bytes", "count using bytes rather than columns (meaning control characters such as newline are not treated specially)");
opts.optflag("s", "spaces", "break lines at word boundaries rather than a hard cut-off");
opts.optopt("w", "width", "set WIDTH as the maximum line width rather than 80", "WIDTH");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f)
};
if matches.opt_present("h") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]...", NAME);
println!("");
print!("{}", opts.usage("Writes each file (or standard input if no files are given) to standard output whilst breaking long lines"));
} else if matches.opt_present("V") {
println!("{} {}", NAME, VERSION);
} else {
let bytes = matches.opt_present("b");
let spaces = matches.opt_present("s");
let poss_width =
if matches.opt_present("w") {
matches.opt_str("w")
} else {
match obs_width {
Some(v) => Some(v.to_string()),
None => None,
}
};
let width = match poss_width {
Some(inp_width) => match inp_width.parse::<usize>() {
Ok(width) => width,
Err(e) => crash!(1, "illegal width value (\"{}\"): {}", inp_width, e)
},
None => 80
};
let files = if matches.free.is_empty() {
vec!("-".to_string())
} else {
matches.free
};
fold(files, bytes, spaces, width);
}
0
}
fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
for (i, arg) in args.iter().enumerate() {
let slice = &arg;
if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
let mut v = args.to_vec();
v.remove(i);
return (v, Some(slice[1..].to_string()));
}
}
(args.to_vec(), None)
}
#[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
for filename in filenames.iter() {
let filename: &str = &filename;
let mut stdin_buf;
let mut file_buf;
let buffer = BufReader::new(
if filename == "-" {
stdin_buf = stdin();
&mut stdin_buf as &mut Read
} else {
file_buf = safe_unwrap!(File::open(Path::new(filename)));
&mut file_buf as &mut Read
}
);
fold_file(buffer, bytes, spaces, width);
}
}
#[inline]
fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width: usize) {
let mut line = String::new();
while safe_unwrap!(file.read_line(&mut line)) > 0 {
if bytes {
let len = line.len();
let mut i = 0;
while i < len {
let width = if len - i >= width { width } else { len - i };
let slice = {
let slice = &line[i..i + width];
if spaces && i + width < len {
match slice.rfind(|ch: char| ch.is_whitespace()) {
Some(m) => &slice[..m + 1],
None => slice
}
} else {
slice
}
};
print!("{}", slice);
i += slice.len();
}
} else {
let mut len = line.chars().count();
let newline = line.ends_with("\n");
if newline {
if len == 1 {
println!("");
continue;
}
len -= 1;
line.truncate(len);
}
let mut output = String::new();
let mut count = 0;
for (i, ch) in line.chars().enumerate() {
if count >= width {
let (val, ncount) = {
let slice = &output[..];
let (out, val, ncount) =
if spaces && i + 1 < len {
match rfind_whitespace(slice) {
Some(m) => {
let routput = &slice[m + 1.. slice.chars().count()];
let ncount = routput.chars().fold(0usize, |out, ch: char| {
out + match ch {
'\t' => 8,
'\x08' => if out > 0 { -1 } else { 0 },
'\r' => return 0,
_ => 1
}
});
(&slice[0.. m + 1], routput, ncount)
},
None => (slice, "", 0)
}
} else {
(slice, "", 0)
};
println!("{}", out);
(val.to_string(), ncount)
};
output = val;
count = ncount;
}
match ch {
'\t' => {
count += 8;
if count > width {
println!("{}", output);
output.truncate(0);
count = 8;
}
}
'\x08' => {
if count > 0 {
count -= 1;
let len = output.len() - 1;
output.truncate(len);
}
continue;
}
'\r' => {
output.truncate(0);
count = 0;
continue;
}
|
};
output.push(ch);
}
if count > 0 {
if newline {
println!("{}", output);
} else {
print!("{}", output);
}
}
}
}
}
#[inline]
fn rfind_whitespace(slice: &str) -> Option<usize> {
for (i, ch) in slice.chars().rev().enumerate() {
if ch.is_whitespace() {
return Some(slice.chars().count() - (i + 1));
}
}
None
}
|
_ => count += 1
|
random_line_split
|
fold.rs
|
#![crate_name = "fold"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, stdin, Write};
use std::path::Path;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
static NAME: &'static str = "fold";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
let (args, obs_width) = handle_obsolete(&args[..]);
let mut opts = getopts::Options::new();
opts.optflag("b", "bytes", "count using bytes rather than columns (meaning control characters such as newline are not treated specially)");
opts.optflag("s", "spaces", "break lines at word boundaries rather than a hard cut-off");
opts.optopt("w", "width", "set WIDTH as the maximum line width rather than 80", "WIDTH");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f)
};
if matches.opt_present("h") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]...", NAME);
println!("");
print!("{}", opts.usage("Writes each file (or standard input if no files are given) to standard output whilst breaking long lines"));
} else if matches.opt_present("V") {
println!("{} {}", NAME, VERSION);
} else {
let bytes = matches.opt_present("b");
let spaces = matches.opt_present("s");
let poss_width =
if matches.opt_present("w") {
matches.opt_str("w")
} else {
match obs_width {
Some(v) => Some(v.to_string()),
None => None,
}
};
let width = match poss_width {
Some(inp_width) => match inp_width.parse::<usize>() {
Ok(width) => width,
Err(e) => crash!(1, "illegal width value (\"{}\"): {}", inp_width, e)
},
None => 80
};
let files = if matches.free.is_empty() {
vec!("-".to_string())
} else {
matches.free
};
fold(files, bytes, spaces, width);
}
0
}
fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
for (i, arg) in args.iter().enumerate() {
let slice = &arg;
if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
let mut v = args.to_vec();
v.remove(i);
return (v, Some(slice[1..].to_string()));
}
}
(args.to_vec(), None)
}
#[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
for filename in filenames.iter() {
let filename: &str = &filename;
let mut stdin_buf;
let mut file_buf;
let buffer = BufReader::new(
if filename == "-" {
stdin_buf = stdin();
&mut stdin_buf as &mut Read
} else {
file_buf = safe_unwrap!(File::open(Path::new(filename)));
&mut file_buf as &mut Read
}
);
fold_file(buffer, bytes, spaces, width);
}
}
#[inline]
fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width: usize)
|
i += slice.len();
}
} else {
let mut len = line.chars().count();
let newline = line.ends_with("\n");
if newline {
if len == 1 {
println!("");
continue;
}
len -= 1;
line.truncate(len);
}
let mut output = String::new();
let mut count = 0;
for (i, ch) in line.chars().enumerate() {
if count >= width {
let (val, ncount) = {
let slice = &output[..];
let (out, val, ncount) =
if spaces && i + 1 < len {
match rfind_whitespace(slice) {
Some(m) => {
let routput = &slice[m + 1.. slice.chars().count()];
let ncount = routput.chars().fold(0usize, |out, ch: char| {
out + match ch {
'\t' => 8,
'\x08' => if out > 0 { -1 } else { 0 },
'\r' => return 0,
_ => 1
}
});
(&slice[0.. m + 1], routput, ncount)
},
None => (slice, "", 0)
}
} else {
(slice, "", 0)
};
println!("{}", out);
(val.to_string(), ncount)
};
output = val;
count = ncount;
}
match ch {
'\t' => {
count += 8;
if count > width {
println!("{}", output);
output.truncate(0);
count = 8;
}
}
'\x08' => {
if count > 0 {
count -= 1;
let len = output.len() - 1;
output.truncate(len);
}
continue;
}
'\r' => {
output.truncate(0);
count = 0;
continue;
}
_ => count += 1
};
output.push(ch);
}
if count > 0 {
if newline {
println!("{}", output);
} else {
print!("{}", output);
}
}
}
}
}
#[inline]
fn rfind_whitespace(slice: &str) -> Option<usize> {
for (i, ch) in slice.chars().rev().enumerate() {
if ch.is_whitespace() {
return Some(slice.chars().count() - (i + 1));
}
}
None
}
|
{
let mut line = String::new();
while safe_unwrap!(file.read_line(&mut line)) > 0 {
if bytes {
let len = line.len();
let mut i = 0;
while i < len {
let width = if len - i >= width { width } else { len - i };
let slice = {
let slice = &line[i..i + width];
if spaces && i + width < len {
match slice.rfind(|ch: char| ch.is_whitespace()) {
Some(m) => &slice[..m + 1],
None => slice
}
} else {
slice
}
};
print!("{}", slice);
|
identifier_body
|
fold.rs
|
#![crate_name = "fold"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::fs::File;
use std::io::{BufRead, BufReader, Read, stdin, Write};
use std::path::Path;
#[path = "../common/util.rs"]
#[macro_use]
mod util;
static NAME: &'static str = "fold";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
let (args, obs_width) = handle_obsolete(&args[..]);
let mut opts = getopts::Options::new();
opts.optflag("b", "bytes", "count using bytes rather than columns (meaning control characters such as newline are not treated specially)");
opts.optflag("s", "spaces", "break lines at word boundaries rather than a hard cut-off");
opts.optopt("w", "width", "set WIDTH as the maximum line width rather than 80", "WIDTH");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f)
};
if matches.opt_present("h") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTION]... [FILE]...", NAME);
println!("");
print!("{}", opts.usage("Writes each file (or standard input if no files are given) to standard output whilst breaking long lines"));
} else if matches.opt_present("V") {
println!("{} {}", NAME, VERSION);
} else {
let bytes = matches.opt_present("b");
let spaces = matches.opt_present("s");
let poss_width =
if matches.opt_present("w") {
matches.opt_str("w")
} else {
match obs_width {
Some(v) => Some(v.to_string()),
None => None,
}
};
let width = match poss_width {
Some(inp_width) => match inp_width.parse::<usize>() {
Ok(width) => width,
Err(e) => crash!(1, "illegal width value (\"{}\"): {}", inp_width, e)
},
None => 80
};
let files = if matches.free.is_empty() {
vec!("-".to_string())
} else {
matches.free
};
fold(files, bytes, spaces, width);
}
0
}
fn
|
(args: &[String]) -> (Vec<String>, Option<String>) {
for (i, arg) in args.iter().enumerate() {
let slice = &arg;
if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
let mut v = args.to_vec();
v.remove(i);
return (v, Some(slice[1..].to_string()));
}
}
(args.to_vec(), None)
}
#[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
for filename in filenames.iter() {
let filename: &str = &filename;
let mut stdin_buf;
let mut file_buf;
let buffer = BufReader::new(
if filename == "-" {
stdin_buf = stdin();
&mut stdin_buf as &mut Read
} else {
file_buf = safe_unwrap!(File::open(Path::new(filename)));
&mut file_buf as &mut Read
}
);
fold_file(buffer, bytes, spaces, width);
}
}
#[inline]
fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width: usize) {
let mut line = String::new();
while safe_unwrap!(file.read_line(&mut line)) > 0 {
if bytes {
let len = line.len();
let mut i = 0;
while i < len {
let width = if len - i >= width { width } else { len - i };
let slice = {
let slice = &line[i..i + width];
if spaces && i + width < len {
match slice.rfind(|ch: char| ch.is_whitespace()) {
Some(m) => &slice[..m + 1],
None => slice
}
} else {
slice
}
};
print!("{}", slice);
i += slice.len();
}
} else {
let mut len = line.chars().count();
let newline = line.ends_with("\n");
if newline {
if len == 1 {
println!("");
continue;
}
len -= 1;
line.truncate(len);
}
let mut output = String::new();
let mut count = 0;
for (i, ch) in line.chars().enumerate() {
if count >= width {
let (val, ncount) = {
let slice = &output[..];
let (out, val, ncount) =
if spaces && i + 1 < len {
match rfind_whitespace(slice) {
Some(m) => {
let routput = &slice[m + 1.. slice.chars().count()];
let ncount = routput.chars().fold(0usize, |out, ch: char| {
out + match ch {
'\t' => 8,
'\x08' => if out > 0 { -1 } else { 0 },
'\r' => return 0,
_ => 1
}
});
(&slice[0.. m + 1], routput, ncount)
},
None => (slice, "", 0)
}
} else {
(slice, "", 0)
};
println!("{}", out);
(val.to_string(), ncount)
};
output = val;
count = ncount;
}
match ch {
'\t' => {
count += 8;
if count > width {
println!("{}", output);
output.truncate(0);
count = 8;
}
}
'\x08' => {
if count > 0 {
count -= 1;
let len = output.len() - 1;
output.truncate(len);
}
continue;
}
'\r' => {
output.truncate(0);
count = 0;
continue;
}
_ => count += 1
};
output.push(ch);
}
if count > 0 {
if newline {
println!("{}", output);
} else {
print!("{}", output);
}
}
}
}
}
#[inline]
fn rfind_whitespace(slice: &str) -> Option<usize> {
for (i, ch) in slice.chars().rev().enumerate() {
if ch.is_whitespace() {
return Some(slice.chars().count() - (i + 1));
}
}
None
}
|
handle_obsolete
|
identifier_name
|
joiner.rs
|
use std::os;
use std::io::File;
fn
|
() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let current_dir = std::os::getcwd();
let share1fname = args[1].clone();
let share2fname = args[2].clone();
let path1 = Path::new(share1fname.clone());
let path2 = Path::new(share2fname.clone());
let path3 = Path::new(current_dir.as_str().unwrap() + "/message.out");
let share1_file = File::open(&path1);
let share2_file = File::open(&path2);
let message_file = File::create(&path3);
match (share1_file, share2_file) {
(Some(mut share1), Some(mut share2)) => {
let share1_msg: ~[u8] = share1.read_to_end();
let share2_msg: ~[u8] = share2.read_to_end();
match (message_file) {
Some(msg) => join(share1_msg, share2_msg, msg),
None => fail!("Error opening output file!"),
}
},
(_, _) => fail!("Error opening input files!"),
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn join(share1_bytes: &[u8], share2_bytes: &[u8], mut message: File) {
let message_bytes = xor(share1_bytes, share2_bytes);
message.write(message_bytes);
}
|
main
|
identifier_name
|
joiner.rs
|
use std::os;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let current_dir = std::os::getcwd();
let share1fname = args[1].clone();
let share2fname = args[2].clone();
let path1 = Path::new(share1fname.clone());
let path2 = Path::new(share2fname.clone());
let path3 = Path::new(current_dir.as_str().unwrap() + "/message.out");
let share1_file = File::open(&path1);
let share2_file = File::open(&path2);
let message_file = File::create(&path3);
match (share1_file, share2_file) {
(Some(mut share1), Some(mut share2)) => {
let share1_msg: ~[u8] = share1.read_to_end();
let share2_msg: ~[u8] = share2.read_to_end();
match (message_file) {
Some(msg) => join(share1_msg, share2_msg, msg),
None => fail!("Error opening output file!"),
}
},
(_, _) => fail!("Error opening input files!"),
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8]
|
fn join(share1_bytes: &[u8], share2_bytes: &[u8], mut message: File) {
let message_bytes = xor(share1_bytes, share2_bytes);
message.write(message_bytes);
}
|
{
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
|
identifier_body
|
joiner.rs
|
use std::os;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len()!= 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let current_dir = std::os::getcwd();
let share1fname = args[1].clone();
let share2fname = args[2].clone();
let path1 = Path::new(share1fname.clone());
let path2 = Path::new(share2fname.clone());
let path3 = Path::new(current_dir.as_str().unwrap() + "/message.out");
let share1_file = File::open(&path1);
let share2_file = File::open(&path2);
let message_file = File::create(&path3);
match (share1_file, share2_file) {
(Some(mut share1), Some(mut share2)) => {
let share1_msg: ~[u8] = share1.read_to_end();
let share2_msg: ~[u8] = share2.read_to_end();
match (message_file) {
Some(msg) => join(share1_msg, share2_msg, msg),
None => fail!("Error opening output file!"),
}
},
(_, _) => fail!("Error opening input files!"),
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
|
ret
}
fn join(share1_bytes: &[u8], share2_bytes: &[u8], mut message: File) {
let message_bytes = xor(share1_bytes, share2_bytes);
message.write(message_bytes);
}
|
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
|
random_line_split
|
truetype.rs
|
use std::libc::*;
use std::intrinsics;
use std::vec;
struct StbttFontinfo {
userdata: *c_void,
data: *c_uchar,
fontstart: c_int,
numGlyphs: c_int,
loca: c_int,
head: c_int,
glyf: c_int,
hhea: c_int,
hmtx: c_int,
kern: c_int,
index_map: c_int,
indexToLocFormat: c_int
}
#[link(name="stb")]
extern {
fn stbtt_InitFont(
info: *StbttFontinfo, data: *c_uchar, offset: c_int) -> c_int;
fn stbtt_ScaleForPixelHeight(
info: *StbttFontinfo, pixels: c_float) -> c_float;
fn stbtt_FindGlyphIndex(
info: *StbttFontinfo, unicode_codepoint: c_int) -> c_int;
fn stbtt_GetGlyphHMetrics(
info: *StbttFontinfo, glyph_index: c_int,
advanceWidth: *mut c_int, leftSideBearing: *mut c_int);
fn stbtt_GetGlyphBitmapBox(
info: *StbttFontinfo, glyph: c_int,
scale_x: c_float, scale_y: c_float,
ix0: *mut c_int, iy0: *mut c_int, ix1: *mut c_int, iy1: *mut c_int);
fn stbtt_MakeGlyphBitmap(info: *StbttFontinfo, output: *mut c_uchar,
out_w: c_int, out_h: c_int, out_stride: c_int,
scale_x: c_float, scale_y: c_float, glyph: c_int);
}
pub struct Font {
priv info: StbttFontinfo,
priv data: ~[u8],
}
pub struct Glyph {
width: int,
height: int,
xOffset: f32,
yOffset: f32,
xAdvance: f32,
pixels: ~[u8]
}
impl Font {
pub fn new(data: ~[u8]) -> Option<Font> {
unsafe {
let ret = Font {
info: intrinsics::uninit(),
data: data,
};
let status = stbtt_InitFont(
&ret.info, ret.data.as_ptr(), 0 as c_int);
if status == 0 {
return None
}
return Some(ret);
}
}
pub fn
|
(&self, codepoint: uint, height: f32) -> Option<Glyph> {
unsafe {
let g = stbtt_FindGlyphIndex(&self.info, codepoint as c_int);
if g == 0 {
return None
}
let scale = stbtt_ScaleForPixelHeight(
&self.info, height as c_float);
let mut x0 = 0 as c_int;
let mut y0 = 0 as c_int;
let mut x1 = 0 as c_int;
let mut y1 = 0 as c_int;
stbtt_GetGlyphBitmapBox(
&self.info, g, scale, scale,
&mut x0, &mut y0, &mut x1, &mut y1);
let mut advance = 0 as c_int;
let mut lsb = 0 as c_int;
stbtt_GetGlyphHMetrics(&self.info, g, &mut advance, &mut lsb);
let width = (x1 - x0) as int;
let height = (y1 - y0) as int;
let mut pixels = vec::from_elem((width * height) as uint, 0u8);
stbtt_MakeGlyphBitmap(
&self.info, pixels.as_mut_ptr(),
width as c_int, height as c_int,
width as c_int, scale, scale, g);
Some(Glyph{
width: width,
height: height,
xOffset: x0 as f32,
yOffset: y0 as f32,
xAdvance: advance as f32 * scale as f32,
pixels: pixels,
})
}
}
}
|
glyph
|
identifier_name
|
truetype.rs
|
use std::libc::*;
use std::intrinsics;
use std::vec;
struct StbttFontinfo {
userdata: *c_void,
data: *c_uchar,
fontstart: c_int,
numGlyphs: c_int,
loca: c_int,
head: c_int,
glyf: c_int,
hhea: c_int,
hmtx: c_int,
kern: c_int,
index_map: c_int,
indexToLocFormat: c_int
}
#[link(name="stb")]
extern {
fn stbtt_InitFont(
info: *StbttFontinfo, data: *c_uchar, offset: c_int) -> c_int;
fn stbtt_ScaleForPixelHeight(
info: *StbttFontinfo, pixels: c_float) -> c_float;
fn stbtt_FindGlyphIndex(
info: *StbttFontinfo, unicode_codepoint: c_int) -> c_int;
fn stbtt_GetGlyphHMetrics(
info: *StbttFontinfo, glyph_index: c_int,
advanceWidth: *mut c_int, leftSideBearing: *mut c_int);
fn stbtt_GetGlyphBitmapBox(
info: *StbttFontinfo, glyph: c_int,
scale_x: c_float, scale_y: c_float,
ix0: *mut c_int, iy0: *mut c_int, ix1: *mut c_int, iy1: *mut c_int);
fn stbtt_MakeGlyphBitmap(info: *StbttFontinfo, output: *mut c_uchar,
out_w: c_int, out_h: c_int, out_stride: c_int,
scale_x: c_float, scale_y: c_float, glyph: c_int);
}
pub struct Font {
priv info: StbttFontinfo,
priv data: ~[u8],
}
pub struct Glyph {
width: int,
height: int,
xOffset: f32,
yOffset: f32,
xAdvance: f32,
pixels: ~[u8]
}
impl Font {
pub fn new(data: ~[u8]) -> Option<Font> {
unsafe {
let ret = Font {
info: intrinsics::uninit(),
data: data,
};
let status = stbtt_InitFont(
&ret.info, ret.data.as_ptr(), 0 as c_int);
if status == 0
|
return Some(ret);
}
}
pub fn glyph(&self, codepoint: uint, height: f32) -> Option<Glyph> {
unsafe {
let g = stbtt_FindGlyphIndex(&self.info, codepoint as c_int);
if g == 0 {
return None
}
let scale = stbtt_ScaleForPixelHeight(
&self.info, height as c_float);
let mut x0 = 0 as c_int;
let mut y0 = 0 as c_int;
let mut x1 = 0 as c_int;
let mut y1 = 0 as c_int;
stbtt_GetGlyphBitmapBox(
&self.info, g, scale, scale,
&mut x0, &mut y0, &mut x1, &mut y1);
let mut advance = 0 as c_int;
let mut lsb = 0 as c_int;
stbtt_GetGlyphHMetrics(&self.info, g, &mut advance, &mut lsb);
let width = (x1 - x0) as int;
let height = (y1 - y0) as int;
let mut pixels = vec::from_elem((width * height) as uint, 0u8);
stbtt_MakeGlyphBitmap(
&self.info, pixels.as_mut_ptr(),
width as c_int, height as c_int,
width as c_int, scale, scale, g);
Some(Glyph{
width: width,
height: height,
xOffset: x0 as f32,
yOffset: y0 as f32,
xAdvance: advance as f32 * scale as f32,
pixels: pixels,
})
}
}
}
|
{
return None
}
|
conditional_block
|
truetype.rs
|
use std::libc::*;
use std::intrinsics;
use std::vec;
struct StbttFontinfo {
userdata: *c_void,
data: *c_uchar,
fontstart: c_int,
numGlyphs: c_int,
loca: c_int,
head: c_int,
glyf: c_int,
hhea: c_int,
hmtx: c_int,
kern: c_int,
index_map: c_int,
indexToLocFormat: c_int
}
#[link(name="stb")]
extern {
fn stbtt_InitFont(
info: *StbttFontinfo, data: *c_uchar, offset: c_int) -> c_int;
fn stbtt_ScaleForPixelHeight(
info: *StbttFontinfo, pixels: c_float) -> c_float;
fn stbtt_FindGlyphIndex(
info: *StbttFontinfo, unicode_codepoint: c_int) -> c_int;
fn stbtt_GetGlyphHMetrics(
info: *StbttFontinfo, glyph_index: c_int,
advanceWidth: *mut c_int, leftSideBearing: *mut c_int);
fn stbtt_GetGlyphBitmapBox(
info: *StbttFontinfo, glyph: c_int,
scale_x: c_float, scale_y: c_float,
ix0: *mut c_int, iy0: *mut c_int, ix1: *mut c_int, iy1: *mut c_int);
fn stbtt_MakeGlyphBitmap(info: *StbttFontinfo, output: *mut c_uchar,
out_w: c_int, out_h: c_int, out_stride: c_int,
scale_x: c_float, scale_y: c_float, glyph: c_int);
}
pub struct Font {
priv info: StbttFontinfo,
priv data: ~[u8],
}
pub struct Glyph {
width: int,
height: int,
xOffset: f32,
yOffset: f32,
xAdvance: f32,
pixels: ~[u8]
}
impl Font {
pub fn new(data: ~[u8]) -> Option<Font> {
unsafe {
let ret = Font {
info: intrinsics::uninit(),
data: data,
|
}
return Some(ret);
}
}
pub fn glyph(&self, codepoint: uint, height: f32) -> Option<Glyph> {
unsafe {
let g = stbtt_FindGlyphIndex(&self.info, codepoint as c_int);
if g == 0 {
return None
}
let scale = stbtt_ScaleForPixelHeight(
&self.info, height as c_float);
let mut x0 = 0 as c_int;
let mut y0 = 0 as c_int;
let mut x1 = 0 as c_int;
let mut y1 = 0 as c_int;
stbtt_GetGlyphBitmapBox(
&self.info, g, scale, scale,
&mut x0, &mut y0, &mut x1, &mut y1);
let mut advance = 0 as c_int;
let mut lsb = 0 as c_int;
stbtt_GetGlyphHMetrics(&self.info, g, &mut advance, &mut lsb);
let width = (x1 - x0) as int;
let height = (y1 - y0) as int;
let mut pixels = vec::from_elem((width * height) as uint, 0u8);
stbtt_MakeGlyphBitmap(
&self.info, pixels.as_mut_ptr(),
width as c_int, height as c_int,
width as c_int, scale, scale, g);
Some(Glyph{
width: width,
height: height,
xOffset: x0 as f32,
yOffset: y0 as f32,
xAdvance: advance as f32 * scale as f32,
pixels: pixels,
})
}
}
}
|
};
let status = stbtt_InitFont(
&ret.info, ret.data.as_ptr(), 0 as c_int);
if status == 0 {
return None
|
random_line_split
|
x86_64_unknown_freebsd.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target;
pub fn target() -> Target {
|
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
llvm_target: "x86_64-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
arch: "x86_64".to_string(),
target_os: "freebsd".to_string(),
target_env: "".to_string(),
options: base,
}
}
|
let mut base = super::freebsd_base::opts();
|
random_line_split
|
x86_64_unknown_freebsd.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target;
pub fn target() -> Target
|
{
let mut base = super::freebsd_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
llvm_target: "x86_64-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
arch: "x86_64".to_string(),
target_os: "freebsd".to_string(),
target_env: "".to_string(),
options: base,
}
}
|
identifier_body
|
|
x86_64_unknown_freebsd.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::Target;
pub fn
|
() -> Target {
let mut base = super::freebsd_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
llvm_target: "x86_64-unknown-freebsd".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
arch: "x86_64".to_string(),
target_os: "freebsd".to_string(),
target_env: "".to_string(),
options: base,
}
}
|
target
|
identifier_name
|
safe_contract.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set maintained in a contract, updated using `getValidators` method.
use std::sync::Weak;
use util::*;
use client::{Client, BlockChainClient};
use client::chain_notify::ChainNotify;
use super::ValidatorSet;
use super::simple_list::SimpleList;
/// The validator contract should have the following interface:
/// [{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}]
pub struct ValidatorSafeContract {
pub address: Address,
validators: RwLock<SimpleList>,
provider: RwLock<Option<provider::Contract>>,
}
impl ValidatorSafeContract {
pub fn new(contract_address: Address) -> Self {
ValidatorSafeContract {
address: contract_address,
validators: Default::default(),
provider: RwLock::new(None),
}
}
/// Queries the state and updates the set of validators.
pub fn update(&self) {
if let Some(ref provider) = *self.provider.read() {
match provider.get_validators() {
Ok(new) => {
debug!(target: "engine", "Set of validators obtained: {:?}", new);
*self.validators.write() = SimpleList::new(new);
},
Err(s) => warn!(target: "engine", "Set of validators could not be updated: {}", s),
}
} else {
warn!(target: "engine", "Set of validators could not be updated: no provider contract.")
}
}
}
/// Checks validators on every block.
impl ChainNotify for ValidatorSafeContract {
fn new_blocks(
&self,
_: Vec<H256>,
_: Vec<H256>,
enacted: Vec<H256>,
_: Vec<H256>,
_: Vec<H256>,
_: Vec<Bytes>,
_duration: u64) {
if!enacted.is_empty() {
self.update();
}
}
}
impl ValidatorSet for Arc<ValidatorSafeContract> {
fn contains(&self, address: &Address) -> bool {
self.validators.read().contains(address)
}
fn get(&self, nonce: usize) -> Address {
self.validators.read().get(nonce)
}
fn count(&self) -> usize {
self.validators.read().count()
}
fn register_contract(&self, client: Weak<Client>)
|
}
mod provider {
// Autogenerated from JSON contract definition using Rust contract convertor.
#![allow(unused_imports)]
use std::string::String;
use std::result::Result;
use std::fmt;
use {util, ethabi};
use util::{FixedHash, Uint};
pub struct Contract {
contract: ethabi::Contract,
address: util::Address,
do_call: Box<Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static>,
}
impl Contract {
pub fn new<F>(address: util::Address, do_call: F) -> Self where F: Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static {
Contract {
contract: ethabi::Contract::new(ethabi::Interface::load(b"[{\"constant\":true,\"inputs\":[],\"name\":\"getValidators\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"type\":\"function\"}]").expect("JSON is autogenerated; qed")),
address: address,
do_call: Box::new(do_call),
}
}
fn as_string<T: fmt::Debug>(e: T) -> String { format!("{:?}", e) }
/// Auto-generated from: `{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}`
#[allow(dead_code)]
pub fn get_validators(&self) -> Result<Vec<util::Address>, String> {
let call = self.contract.function("getValidators".into()).map_err(Self::as_string)?;
let data = call.encode_call(
vec![]
).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_array().and_then(|v| v.into_iter().map(|a| a.to_address()).collect::<Option<Vec<[u8; 20]>>>()).ok_or("Invalid type returned")?; r.into_iter().map(|a| util::Address::from(a)).collect::<Vec<_>>() }))
}
}
}
#[cfg(test)]
mod tests {
use util::*;
use spec::Spec;
use account_provider::AccountProvider;
use transaction::{Transaction, Action};
use client::{BlockChainClient, EngineClient};
use ethkey::Secret;
use miner::MinerService;
use tests::helpers::generate_dummy_client_with_spec_and_accounts;
use super::super::ValidatorSet;
use super::ValidatorSafeContract;
#[test]
fn fetches_validators() {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
let vc = Arc::new(ValidatorSafeContract::new(Address::from_str("0000000000000000000000000000000000000005").unwrap()));
vc.register_contract(Arc::downgrade(&client));
assert!(vc.contains(&Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap()));
assert!(vc.contains(&Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap()));
}
#[test]
fn updates_validators() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0 = Secret::from_slice(&"1".sha3()).unwrap();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(Secret::from_slice(&"0".sha3()).unwrap(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap));
client.engine().register_client(Arc::downgrade(&client));
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap();
client.miner().set_engine_signer(v1, "".into()).unwrap();
// Remove "1" validator.
let tx = Transaction {
nonce: 0.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "bfc708a000000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 1);
// Add "1" validator back in.
let tx = Transaction {
nonce: 1.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "4d238c8e00000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// The transaction is not yet included so still unable to seal.
assert_eq!(client.chain_info().best_block_number, 1);
// Switch to the validator that is still there.
client.miner().set_engine_signer(v0, "".into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 2);
// Switch back to the added validator, since the state is updated.
client.miner().set_engine_signer(v1, "".into()).unwrap();
let tx = Transaction {
nonce: 2.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 0.into(),
data: Vec::new(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// Able to seal again.
assert_eq!(client.chain_info().best_block_number, 3);
}
}
|
{
if let Some(c) = client.upgrade() {
c.add_notify(self.clone());
}
{
*self.provider.write() = Some(provider::Contract::new(self.address, move |a, d| client.upgrade().ok_or("No client!".into()).and_then(|c| c.call_contract(a, d))));
}
self.update();
}
|
identifier_body
|
safe_contract.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set maintained in a contract, updated using `getValidators` method.
use std::sync::Weak;
use util::*;
use client::{Client, BlockChainClient};
use client::chain_notify::ChainNotify;
use super::ValidatorSet;
use super::simple_list::SimpleList;
/// The validator contract should have the following interface:
/// [{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}]
pub struct ValidatorSafeContract {
pub address: Address,
validators: RwLock<SimpleList>,
provider: RwLock<Option<provider::Contract>>,
}
impl ValidatorSafeContract {
pub fn new(contract_address: Address) -> Self {
ValidatorSafeContract {
address: contract_address,
validators: Default::default(),
provider: RwLock::new(None),
}
}
/// Queries the state and updates the set of validators.
pub fn update(&self) {
if let Some(ref provider) = *self.provider.read() {
match provider.get_validators() {
Ok(new) => {
debug!(target: "engine", "Set of validators obtained: {:?}", new);
*self.validators.write() = SimpleList::new(new);
},
Err(s) => warn!(target: "engine", "Set of validators could not be updated: {}", s),
}
} else {
warn!(target: "engine", "Set of validators could not be updated: no provider contract.")
}
}
}
/// Checks validators on every block.
impl ChainNotify for ValidatorSafeContract {
fn new_blocks(
&self,
_: Vec<H256>,
_: Vec<H256>,
enacted: Vec<H256>,
_: Vec<H256>,
_: Vec<H256>,
_: Vec<Bytes>,
_duration: u64) {
if!enacted.is_empty() {
self.update();
}
}
}
impl ValidatorSet for Arc<ValidatorSafeContract> {
fn contains(&self, address: &Address) -> bool {
self.validators.read().contains(address)
}
fn get(&self, nonce: usize) -> Address {
self.validators.read().get(nonce)
}
fn count(&self) -> usize {
self.validators.read().count()
}
fn register_contract(&self, client: Weak<Client>) {
if let Some(c) = client.upgrade()
|
{
*self.provider.write() = Some(provider::Contract::new(self.address, move |a, d| client.upgrade().ok_or("No client!".into()).and_then(|c| c.call_contract(a, d))));
}
self.update();
}
}
mod provider {
// Autogenerated from JSON contract definition using Rust contract convertor.
#![allow(unused_imports)]
use std::string::String;
use std::result::Result;
use std::fmt;
use {util, ethabi};
use util::{FixedHash, Uint};
pub struct Contract {
contract: ethabi::Contract,
address: util::Address,
do_call: Box<Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static>,
}
impl Contract {
pub fn new<F>(address: util::Address, do_call: F) -> Self where F: Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static {
Contract {
contract: ethabi::Contract::new(ethabi::Interface::load(b"[{\"constant\":true,\"inputs\":[],\"name\":\"getValidators\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"type\":\"function\"}]").expect("JSON is autogenerated; qed")),
address: address,
do_call: Box::new(do_call),
}
}
fn as_string<T: fmt::Debug>(e: T) -> String { format!("{:?}", e) }
/// Auto-generated from: `{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}`
#[allow(dead_code)]
pub fn get_validators(&self) -> Result<Vec<util::Address>, String> {
let call = self.contract.function("getValidators".into()).map_err(Self::as_string)?;
let data = call.encode_call(
vec![]
).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_array().and_then(|v| v.into_iter().map(|a| a.to_address()).collect::<Option<Vec<[u8; 20]>>>()).ok_or("Invalid type returned")?; r.into_iter().map(|a| util::Address::from(a)).collect::<Vec<_>>() }))
}
}
}
#[cfg(test)]
mod tests {
use util::*;
use spec::Spec;
use account_provider::AccountProvider;
use transaction::{Transaction, Action};
use client::{BlockChainClient, EngineClient};
use ethkey::Secret;
use miner::MinerService;
use tests::helpers::generate_dummy_client_with_spec_and_accounts;
use super::super::ValidatorSet;
use super::ValidatorSafeContract;
#[test]
fn fetches_validators() {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
let vc = Arc::new(ValidatorSafeContract::new(Address::from_str("0000000000000000000000000000000000000005").unwrap()));
vc.register_contract(Arc::downgrade(&client));
assert!(vc.contains(&Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap()));
assert!(vc.contains(&Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap()));
}
#[test]
fn updates_validators() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0 = Secret::from_slice(&"1".sha3()).unwrap();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(Secret::from_slice(&"0".sha3()).unwrap(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap));
client.engine().register_client(Arc::downgrade(&client));
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap();
client.miner().set_engine_signer(v1, "".into()).unwrap();
// Remove "1" validator.
let tx = Transaction {
nonce: 0.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "bfc708a000000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 1);
// Add "1" validator back in.
let tx = Transaction {
nonce: 1.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "4d238c8e00000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// The transaction is not yet included so still unable to seal.
assert_eq!(client.chain_info().best_block_number, 1);
// Switch to the validator that is still there.
client.miner().set_engine_signer(v0, "".into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 2);
// Switch back to the added validator, since the state is updated.
client.miner().set_engine_signer(v1, "".into()).unwrap();
let tx = Transaction {
nonce: 2.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 0.into(),
data: Vec::new(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// Able to seal again.
assert_eq!(client.chain_info().best_block_number, 3);
}
}
|
{
c.add_notify(self.clone());
}
|
conditional_block
|
safe_contract.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set maintained in a contract, updated using `getValidators` method.
use std::sync::Weak;
use util::*;
use client::{Client, BlockChainClient};
use client::chain_notify::ChainNotify;
use super::ValidatorSet;
use super::simple_list::SimpleList;
/// The validator contract should have the following interface:
/// [{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}]
pub struct ValidatorSafeContract {
pub address: Address,
validators: RwLock<SimpleList>,
provider: RwLock<Option<provider::Contract>>,
}
impl ValidatorSafeContract {
pub fn new(contract_address: Address) -> Self {
ValidatorSafeContract {
address: contract_address,
validators: Default::default(),
provider: RwLock::new(None),
}
}
/// Queries the state and updates the set of validators.
pub fn update(&self) {
if let Some(ref provider) = *self.provider.read() {
match provider.get_validators() {
Ok(new) => {
debug!(target: "engine", "Set of validators obtained: {:?}", new);
*self.validators.write() = SimpleList::new(new);
},
Err(s) => warn!(target: "engine", "Set of validators could not be updated: {}", s),
}
} else {
warn!(target: "engine", "Set of validators could not be updated: no provider contract.")
}
}
}
/// Checks validators on every block.
impl ChainNotify for ValidatorSafeContract {
fn new_blocks(
&self,
_: Vec<H256>,
_: Vec<H256>,
enacted: Vec<H256>,
_: Vec<H256>,
_: Vec<H256>,
_: Vec<Bytes>,
_duration: u64) {
if!enacted.is_empty() {
self.update();
}
}
}
impl ValidatorSet for Arc<ValidatorSafeContract> {
fn contains(&self, address: &Address) -> bool {
self.validators.read().contains(address)
}
fn get(&self, nonce: usize) -> Address {
self.validators.read().get(nonce)
}
fn count(&self) -> usize {
self.validators.read().count()
}
fn register_contract(&self, client: Weak<Client>) {
if let Some(c) = client.upgrade() {
c.add_notify(self.clone());
}
{
*self.provider.write() = Some(provider::Contract::new(self.address, move |a, d| client.upgrade().ok_or("No client!".into()).and_then(|c| c.call_contract(a, d))));
}
self.update();
}
}
mod provider {
// Autogenerated from JSON contract definition using Rust contract convertor.
#![allow(unused_imports)]
use std::string::String;
use std::result::Result;
use std::fmt;
use {util, ethabi};
use util::{FixedHash, Uint};
pub struct Contract {
contract: ethabi::Contract,
address: util::Address,
do_call: Box<Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static>,
}
impl Contract {
pub fn new<F>(address: util::Address, do_call: F) -> Self where F: Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static {
Contract {
contract: ethabi::Contract::new(ethabi::Interface::load(b"[{\"constant\":true,\"inputs\":[],\"name\":\"getValidators\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"type\":\"function\"}]").expect("JSON is autogenerated; qed")),
address: address,
do_call: Box::new(do_call),
}
}
fn as_string<T: fmt::Debug>(e: T) -> String { format!("{:?}", e) }
/// Auto-generated from: `{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}`
#[allow(dead_code)]
pub fn get_validators(&self) -> Result<Vec<util::Address>, String> {
let call = self.contract.function("getValidators".into()).map_err(Self::as_string)?;
let data = call.encode_call(
vec![]
).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_array().and_then(|v| v.into_iter().map(|a| a.to_address()).collect::<Option<Vec<[u8; 20]>>>()).ok_or("Invalid type returned")?; r.into_iter().map(|a| util::Address::from(a)).collect::<Vec<_>>() }))
}
}
}
#[cfg(test)]
mod tests {
use util::*;
use spec::Spec;
use account_provider::AccountProvider;
use transaction::{Transaction, Action};
use client::{BlockChainClient, EngineClient};
use ethkey::Secret;
use miner::MinerService;
use tests::helpers::generate_dummy_client_with_spec_and_accounts;
use super::super::ValidatorSet;
use super::ValidatorSafeContract;
#[test]
fn
|
() {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
let vc = Arc::new(ValidatorSafeContract::new(Address::from_str("0000000000000000000000000000000000000005").unwrap()));
vc.register_contract(Arc::downgrade(&client));
assert!(vc.contains(&Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap()));
assert!(vc.contains(&Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap()));
}
#[test]
fn updates_validators() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0 = Secret::from_slice(&"1".sha3()).unwrap();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(Secret::from_slice(&"0".sha3()).unwrap(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap));
client.engine().register_client(Arc::downgrade(&client));
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap();
client.miner().set_engine_signer(v1, "".into()).unwrap();
// Remove "1" validator.
let tx = Transaction {
nonce: 0.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "bfc708a000000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 1);
// Add "1" validator back in.
let tx = Transaction {
nonce: 1.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "4d238c8e00000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// The transaction is not yet included so still unable to seal.
assert_eq!(client.chain_info().best_block_number, 1);
// Switch to the validator that is still there.
client.miner().set_engine_signer(v0, "".into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 2);
// Switch back to the added validator, since the state is updated.
client.miner().set_engine_signer(v1, "".into()).unwrap();
let tx = Transaction {
nonce: 2.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 0.into(),
data: Vec::new(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// Able to seal again.
assert_eq!(client.chain_info().best_block_number, 3);
}
}
|
fetches_validators
|
identifier_name
|
safe_contract.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
/// Validator set maintained in a contract, updated using `getValidators` method.
use std::sync::Weak;
use util::*;
use client::{Client, BlockChainClient};
use client::chain_notify::ChainNotify;
use super::ValidatorSet;
use super::simple_list::SimpleList;
/// The validator contract should have the following interface:
/// [{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}]
pub struct ValidatorSafeContract {
pub address: Address,
validators: RwLock<SimpleList>,
provider: RwLock<Option<provider::Contract>>,
}
impl ValidatorSafeContract {
pub fn new(contract_address: Address) -> Self {
ValidatorSafeContract {
address: contract_address,
validators: Default::default(),
provider: RwLock::new(None),
}
}
/// Queries the state and updates the set of validators.
pub fn update(&self) {
if let Some(ref provider) = *self.provider.read() {
match provider.get_validators() {
Ok(new) => {
debug!(target: "engine", "Set of validators obtained: {:?}", new);
*self.validators.write() = SimpleList::new(new);
},
Err(s) => warn!(target: "engine", "Set of validators could not be updated: {}", s),
}
} else {
warn!(target: "engine", "Set of validators could not be updated: no provider contract.")
}
}
}
/// Checks validators on every block.
impl ChainNotify for ValidatorSafeContract {
fn new_blocks(
&self,
|
_: Vec<H256>,
_: Vec<H256>,
_: Vec<Bytes>,
_duration: u64) {
if!enacted.is_empty() {
self.update();
}
}
}
impl ValidatorSet for Arc<ValidatorSafeContract> {
fn contains(&self, address: &Address) -> bool {
self.validators.read().contains(address)
}
fn get(&self, nonce: usize) -> Address {
self.validators.read().get(nonce)
}
fn count(&self) -> usize {
self.validators.read().count()
}
fn register_contract(&self, client: Weak<Client>) {
if let Some(c) = client.upgrade() {
c.add_notify(self.clone());
}
{
*self.provider.write() = Some(provider::Contract::new(self.address, move |a, d| client.upgrade().ok_or("No client!".into()).and_then(|c| c.call_contract(a, d))));
}
self.update();
}
}
mod provider {
// Autogenerated from JSON contract definition using Rust contract convertor.
#![allow(unused_imports)]
use std::string::String;
use std::result::Result;
use std::fmt;
use {util, ethabi};
use util::{FixedHash, Uint};
pub struct Contract {
contract: ethabi::Contract,
address: util::Address,
do_call: Box<Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static>,
}
impl Contract {
pub fn new<F>(address: util::Address, do_call: F) -> Self where F: Fn(util::Address, Vec<u8>) -> Result<Vec<u8>, String> + Send + Sync +'static {
Contract {
contract: ethabi::Contract::new(ethabi::Interface::load(b"[{\"constant\":true,\"inputs\":[],\"name\":\"getValidators\",\"outputs\":[{\"name\":\"\",\"type\":\"address[]\"}],\"payable\":false,\"type\":\"function\"}]").expect("JSON is autogenerated; qed")),
address: address,
do_call: Box::new(do_call),
}
}
fn as_string<T: fmt::Debug>(e: T) -> String { format!("{:?}", e) }
/// Auto-generated from: `{"constant":true,"inputs":[],"name":"getValidators","outputs":[{"name":"","type":"address[]"}],"payable":false,"type":"function"}`
#[allow(dead_code)]
pub fn get_validators(&self) -> Result<Vec<util::Address>, String> {
let call = self.contract.function("getValidators".into()).map_err(Self::as_string)?;
let data = call.encode_call(
vec![]
).map_err(Self::as_string)?;
let output = call.decode_output((self.do_call)(self.address.clone(), data)?).map_err(Self::as_string)?;
let mut result = output.into_iter().rev().collect::<Vec<_>>();
Ok(({ let r = result.pop().ok_or("Invalid return arity")?; let r = r.to_array().and_then(|v| v.into_iter().map(|a| a.to_address()).collect::<Option<Vec<[u8; 20]>>>()).ok_or("Invalid type returned")?; r.into_iter().map(|a| util::Address::from(a)).collect::<Vec<_>>() }))
}
}
}
#[cfg(test)]
mod tests {
use util::*;
use spec::Spec;
use account_provider::AccountProvider;
use transaction::{Transaction, Action};
use client::{BlockChainClient, EngineClient};
use ethkey::Secret;
use miner::MinerService;
use tests::helpers::generate_dummy_client_with_spec_and_accounts;
use super::super::ValidatorSet;
use super::ValidatorSafeContract;
#[test]
fn fetches_validators() {
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
let vc = Arc::new(ValidatorSafeContract::new(Address::from_str("0000000000000000000000000000000000000005").unwrap()));
vc.register_contract(Arc::downgrade(&client));
assert!(vc.contains(&Address::from_str("7d577a597b2742b498cb5cf0c26cdcd726d39e6e").unwrap()));
assert!(vc.contains(&Address::from_str("82a978b3f5962a5b0957d9ee9eef472ee55b42f1").unwrap()));
}
#[test]
fn updates_validators() {
let tap = Arc::new(AccountProvider::transient_provider());
let s0 = Secret::from_slice(&"1".sha3()).unwrap();
let v0 = tap.insert_account(s0.clone(), "").unwrap();
let v1 = tap.insert_account(Secret::from_slice(&"0".sha3()).unwrap(), "").unwrap();
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap));
client.engine().register_client(Arc::downgrade(&client));
let validator_contract = Address::from_str("0000000000000000000000000000000000000005").unwrap();
client.miner().set_engine_signer(v1, "".into()).unwrap();
// Remove "1" validator.
let tx = Transaction {
nonce: 0.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "bfc708a000000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 1);
// Add "1" validator back in.
let tx = Transaction {
nonce: 1.into(),
gas_price: 0.into(),
gas: 500_000.into(),
action: Action::Call(validator_contract),
value: 0.into(),
data: "4d238c8e00000000000000000000000082a978b3f5962a5b0957d9ee9eef472ee55b42f1".from_hex().unwrap(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// The transaction is not yet included so still unable to seal.
assert_eq!(client.chain_info().best_block_number, 1);
// Switch to the validator that is still there.
client.miner().set_engine_signer(v0, "".into()).unwrap();
client.update_sealing();
assert_eq!(client.chain_info().best_block_number, 2);
// Switch back to the added validator, since the state is updated.
client.miner().set_engine_signer(v1, "".into()).unwrap();
let tx = Transaction {
nonce: 2.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 0.into(),
data: Vec::new(),
}.sign(&s0, None);
client.miner().import_own_transaction(client.as_ref(), tx.into()).unwrap();
client.update_sealing();
// Able to seal again.
assert_eq!(client.chain_info().best_block_number, 3);
}
}
|
_: Vec<H256>,
_: Vec<H256>,
enacted: Vec<H256>,
|
random_line_split
|
npm.rs
|
use super::super::context::{BuildContext};
use super::generic::{run_command, capture_command};
use super::super::packages;
use std::path::Path;
pub fn scan_features(pkgs: &Vec<String>) -> Vec<packages::Package> {
let mut res = vec!();
res.push(packages::BuildEssential);
res.push(packages::NodeJs);
res.push(packages::NodeJsDev);
res.push(packages::Npm);
for name in pkgs.iter() {
if name[..].starts_with("git://") {
res.push(packages::Git);
} // Does npm support mercurial?
}
return res;
}
pub fn ensure_npm(ctx: &mut BuildContext, features: &[packages::Package])
-> Result<(), String>
{
packages::ensure_packages(ctx, features)
}
pub fn npm_install(ctx: &mut BuildContext, pkgs: &Vec<String>)
-> Result<(), String>
|
pub fn list(ctx: &mut BuildContext) -> Result<(), String> {
use std::fs::File; // TODO(tailhook) migrate whole module
use std::io::Write; // TODO(tailhook) migrate whole module
try!(capture_command(ctx, &[
"/usr/bin/npm".to_string(),
"ls".to_string(),
"--global".to_string(),
], &[])
.and_then(|out| {
File::create("/vagga/container/npm-list.txt")
.and_then(|mut f| f.write_all(&out))
.map_err(|e| format!("Error dumping package list: {}", e))
}));
Ok(())
}
|
{
try!(ctx.add_cache_dir(Path::new("/tmp/npm-cache"),
"npm-cache".to_string()));
try!(ensure_npm(ctx, &scan_features(pkgs)[..]));
let mut args = vec!(
"/usr/bin/npm".to_string(),
"install".to_string(),
"--user=root".to_string(),
"--cache=/tmp/npm-cache".to_string(),
"--global".to_string(),
);
args.extend(pkgs.clone().into_iter());
run_command(ctx, &args[..])
}
|
identifier_body
|
npm.rs
|
use super::super::context::{BuildContext};
use super::generic::{run_command, capture_command};
use super::super::packages;
use std::path::Path;
pub fn scan_features(pkgs: &Vec<String>) -> Vec<packages::Package> {
let mut res = vec!();
res.push(packages::BuildEssential);
res.push(packages::NodeJs);
res.push(packages::NodeJsDev);
res.push(packages::Npm);
for name in pkgs.iter() {
if name[..].starts_with("git://") {
res.push(packages::Git);
} // Does npm support mercurial?
}
return res;
}
pub fn ensure_npm(ctx: &mut BuildContext, features: &[packages::Package])
-> Result<(), String>
{
packages::ensure_packages(ctx, features)
}
pub fn npm_install(ctx: &mut BuildContext, pkgs: &Vec<String>)
-> Result<(), String>
{
try!(ctx.add_cache_dir(Path::new("/tmp/npm-cache"),
"npm-cache".to_string()));
try!(ensure_npm(ctx, &scan_features(pkgs)[..]));
let mut args = vec!(
"/usr/bin/npm".to_string(),
"install".to_string(),
"--user=root".to_string(),
"--cache=/tmp/npm-cache".to_string(),
"--global".to_string(),
);
args.extend(pkgs.clone().into_iter());
run_command(ctx, &args[..])
}
pub fn list(ctx: &mut BuildContext) -> Result<(), String> {
use std::fs::File; // TODO(tailhook) migrate whole module
use std::io::Write; // TODO(tailhook) migrate whole module
try!(capture_command(ctx, &[
|
"--global".to_string(),
], &[])
.and_then(|out| {
File::create("/vagga/container/npm-list.txt")
.and_then(|mut f| f.write_all(&out))
.map_err(|e| format!("Error dumping package list: {}", e))
}));
Ok(())
}
|
"/usr/bin/npm".to_string(),
"ls".to_string(),
|
random_line_split
|
npm.rs
|
use super::super::context::{BuildContext};
use super::generic::{run_command, capture_command};
use super::super::packages;
use std::path::Path;
pub fn scan_features(pkgs: &Vec<String>) -> Vec<packages::Package> {
let mut res = vec!();
res.push(packages::BuildEssential);
res.push(packages::NodeJs);
res.push(packages::NodeJsDev);
res.push(packages::Npm);
for name in pkgs.iter() {
if name[..].starts_with("git://")
|
// Does npm support mercurial?
}
return res;
}
pub fn ensure_npm(ctx: &mut BuildContext, features: &[packages::Package])
-> Result<(), String>
{
packages::ensure_packages(ctx, features)
}
pub fn npm_install(ctx: &mut BuildContext, pkgs: &Vec<String>)
-> Result<(), String>
{
try!(ctx.add_cache_dir(Path::new("/tmp/npm-cache"),
"npm-cache".to_string()));
try!(ensure_npm(ctx, &scan_features(pkgs)[..]));
let mut args = vec!(
"/usr/bin/npm".to_string(),
"install".to_string(),
"--user=root".to_string(),
"--cache=/tmp/npm-cache".to_string(),
"--global".to_string(),
);
args.extend(pkgs.clone().into_iter());
run_command(ctx, &args[..])
}
pub fn list(ctx: &mut BuildContext) -> Result<(), String> {
use std::fs::File; // TODO(tailhook) migrate whole module
use std::io::Write; // TODO(tailhook) migrate whole module
try!(capture_command(ctx, &[
"/usr/bin/npm".to_string(),
"ls".to_string(),
"--global".to_string(),
], &[])
.and_then(|out| {
File::create("/vagga/container/npm-list.txt")
.and_then(|mut f| f.write_all(&out))
.map_err(|e| format!("Error dumping package list: {}", e))
}));
Ok(())
}
|
{
res.push(packages::Git);
}
|
conditional_block
|
npm.rs
|
use super::super::context::{BuildContext};
use super::generic::{run_command, capture_command};
use super::super::packages;
use std::path::Path;
pub fn scan_features(pkgs: &Vec<String>) -> Vec<packages::Package> {
let mut res = vec!();
res.push(packages::BuildEssential);
res.push(packages::NodeJs);
res.push(packages::NodeJsDev);
res.push(packages::Npm);
for name in pkgs.iter() {
if name[..].starts_with("git://") {
res.push(packages::Git);
} // Does npm support mercurial?
}
return res;
}
pub fn ensure_npm(ctx: &mut BuildContext, features: &[packages::Package])
-> Result<(), String>
{
packages::ensure_packages(ctx, features)
}
pub fn
|
(ctx: &mut BuildContext, pkgs: &Vec<String>)
-> Result<(), String>
{
try!(ctx.add_cache_dir(Path::new("/tmp/npm-cache"),
"npm-cache".to_string()));
try!(ensure_npm(ctx, &scan_features(pkgs)[..]));
let mut args = vec!(
"/usr/bin/npm".to_string(),
"install".to_string(),
"--user=root".to_string(),
"--cache=/tmp/npm-cache".to_string(),
"--global".to_string(),
);
args.extend(pkgs.clone().into_iter());
run_command(ctx, &args[..])
}
pub fn list(ctx: &mut BuildContext) -> Result<(), String> {
use std::fs::File; // TODO(tailhook) migrate whole module
use std::io::Write; // TODO(tailhook) migrate whole module
try!(capture_command(ctx, &[
"/usr/bin/npm".to_string(),
"ls".to_string(),
"--global".to_string(),
], &[])
.and_then(|out| {
File::create("/vagga/container/npm-list.txt")
.and_then(|mut f| f.write_all(&out))
.map_err(|e| format!("Error dumping package list: {}", e))
}));
Ok(())
}
|
npm_install
|
identifier_name
|
oper.rs
|
use std::fmt;
use protocol::command::CMD_OPER;
use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct OperCommand<'a> {
name: &'a str,
password: &'a str,
}
impl<'a> OperCommand<'a> {
pub fn new(name: &'a str, password: &'a str) -> OperCommand<'a> {
OperCommand {
name: name,
password: password,
}
}
pub fn name(&self) -> &'a str {
self.name
}
pub fn password(&self) -> &'a str {
self.password
}
}
impl<'a> fmt::Display for OperCommand<'a> {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}", CMD_OPER, self.name, self.password)
}
}
impl<'a> IrcMessage<'a> for OperCommand<'a> {
fn from_raw(raw: &RawMessage<'a>) -> Result<OperCommand<'a>, ParseMessageError> {
let mut param = raw.parameters();
let (name, pwd) = match (param.next(), param.next()) {
(Some(name), Some(pwd)) => (name, pwd),
_ => return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams,
"OPER command requires 2 parameters")),
};
Ok(OperCommand::new(name, pwd))
}
}
|
fmt
|
identifier_name
|
oper.rs
|
use std::fmt;
use protocol::command::CMD_OPER;
use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct OperCommand<'a> {
name: &'a str,
password: &'a str,
}
impl<'a> OperCommand<'a> {
pub fn new(name: &'a str, password: &'a str) -> OperCommand<'a> {
OperCommand {
name: name,
password: password,
}
}
|
self.name
}
pub fn password(&self) -> &'a str {
self.password
}
}
impl<'a> fmt::Display for OperCommand<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}", CMD_OPER, self.name, self.password)
}
}
impl<'a> IrcMessage<'a> for OperCommand<'a> {
fn from_raw(raw: &RawMessage<'a>) -> Result<OperCommand<'a>, ParseMessageError> {
let mut param = raw.parameters();
let (name, pwd) = match (param.next(), param.next()) {
(Some(name), Some(pwd)) => (name, pwd),
_ => return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams,
"OPER command requires 2 parameters")),
};
Ok(OperCommand::new(name, pwd))
}
}
|
pub fn name(&self) -> &'a str {
|
random_line_split
|
oper.rs
|
use std::fmt;
use protocol::command::CMD_OPER;
use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct OperCommand<'a> {
name: &'a str,
password: &'a str,
}
impl<'a> OperCommand<'a> {
pub fn new(name: &'a str, password: &'a str) -> OperCommand<'a> {
OperCommand {
name: name,
password: password,
}
}
pub fn name(&self) -> &'a str {
self.name
}
pub fn password(&self) -> &'a str {
self.password
}
}
impl<'a> fmt::Display for OperCommand<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} {}", CMD_OPER, self.name, self.password)
}
}
impl<'a> IrcMessage<'a> for OperCommand<'a> {
fn from_raw(raw: &RawMessage<'a>) -> Result<OperCommand<'a>, ParseMessageError>
|
}
|
{
let mut param = raw.parameters();
let (name, pwd) = match (param.next(), param.next()) {
(Some(name), Some(pwd)) => (name, pwd),
_ => return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams,
"OPER command requires 2 parameters")),
};
Ok(OperCommand::new(name, pwd))
}
|
identifier_body
|
main.rs
|
extern crate fps_counter;
extern crate piston;
extern crate tcod;
extern crate tcod_window;
use std::cell::RefCell;
use std::rc::Rc;
use fps_counter::FPSCounter;
use piston::event_loop::{EventLoop, Events};
use piston::input::Event::{Render, Update};
use piston::window::{Size, WindowSettings};
use tcod::Console;
use tcod::console::{Renderer, Root};
use tcod_window::TcodWindow;
const WINDOW_TITLE: &'static str = "fps_counter";
const WINDOW_SIZE_HEIGHT: u32 = 50;
const WINDOW_SIZE_WIDTH: u32 = 50;
fn
|
() {
let settings = WindowSettings::new(WINDOW_TITLE,
Size {
width: WINDOW_SIZE_WIDTH,
height: WINDOW_SIZE_HEIGHT,
})
.exit_on_esc(true);
let root = Root::initializer()
.size(settings.get_size().width as i32,
settings.get_size().height as i32)
.title(settings.get_title())
.renderer(Renderer::SDL)
.init();
let console = Rc::new(RefCell::new(root));
let mut window = TcodWindow::with_console(console, settings);
let mut events = window.events().ups(140).max_fps(10000);
let mut fps_counter = FPSCounter::new();
let mut fps = fps_counter.tick();
while let Some(e) = events.next(&mut window) {
match e {
Render(_) => {
fps = fps_counter.tick();
},
Update(_) => {
let fps_string = format!("FPS: {:?}", fps);
window.window.borrow_mut().print(0, 0, fps_string);
},
_ => {},
}
}
}
|
main
|
identifier_name
|
main.rs
|
extern crate fps_counter;
extern crate piston;
extern crate tcod;
extern crate tcod_window;
use std::cell::RefCell;
use std::rc::Rc;
use fps_counter::FPSCounter;
use piston::event_loop::{EventLoop, Events};
use piston::input::Event::{Render, Update};
use piston::window::{Size, WindowSettings};
use tcod::Console;
use tcod::console::{Renderer, Root};
use tcod_window::TcodWindow;
const WINDOW_TITLE: &'static str = "fps_counter";
const WINDOW_SIZE_HEIGHT: u32 = 50;
const WINDOW_SIZE_WIDTH: u32 = 50;
fn main() {
let settings = WindowSettings::new(WINDOW_TITLE,
Size {
width: WINDOW_SIZE_WIDTH,
height: WINDOW_SIZE_HEIGHT,
})
.exit_on_esc(true);
let root = Root::initializer()
.size(settings.get_size().width as i32,
settings.get_size().height as i32)
.title(settings.get_title())
.renderer(Renderer::SDL)
.init();
let console = Rc::new(RefCell::new(root));
let mut window = TcodWindow::with_console(console, settings);
let mut events = window.events().ups(140).max_fps(10000);
let mut fps_counter = FPSCounter::new();
let mut fps = fps_counter.tick();
while let Some(e) = events.next(&mut window) {
match e {
Render(_) => {
fps = fps_counter.tick();
},
Update(_) => {
let fps_string = format!("FPS: {:?}", fps);
window.window.borrow_mut().print(0, 0, fps_string);
},
_ => {},
|
}
}
}
|
random_line_split
|
|
main.rs
|
extern crate fps_counter;
extern crate piston;
extern crate tcod;
extern crate tcod_window;
use std::cell::RefCell;
use std::rc::Rc;
use fps_counter::FPSCounter;
use piston::event_loop::{EventLoop, Events};
use piston::input::Event::{Render, Update};
use piston::window::{Size, WindowSettings};
use tcod::Console;
use tcod::console::{Renderer, Root};
use tcod_window::TcodWindow;
const WINDOW_TITLE: &'static str = "fps_counter";
const WINDOW_SIZE_HEIGHT: u32 = 50;
const WINDOW_SIZE_WIDTH: u32 = 50;
fn main()
|
let mut fps = fps_counter.tick();
while let Some(e) = events.next(&mut window) {
match e {
Render(_) => {
fps = fps_counter.tick();
},
Update(_) => {
let fps_string = format!("FPS: {:?}", fps);
window.window.borrow_mut().print(0, 0, fps_string);
},
_ => {},
}
}
}
|
{
let settings = WindowSettings::new(WINDOW_TITLE,
Size {
width: WINDOW_SIZE_WIDTH,
height: WINDOW_SIZE_HEIGHT,
})
.exit_on_esc(true);
let root = Root::initializer()
.size(settings.get_size().width as i32,
settings.get_size().height as i32)
.title(settings.get_title())
.renderer(Renderer::SDL)
.init();
let console = Rc::new(RefCell::new(root));
let mut window = TcodWindow::with_console(console, settings);
let mut events = window.events().ups(140).max_fps(10000);
let mut fps_counter = FPSCounter::new();
|
identifier_body
|
oneshot.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.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an UnsafeArc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
use comm::Receiver;
use kinds::Send;
use mem;
use ops::Drop;
use option::{Some, None, Option};
use result::{Result, Ok, Err};
use rt::local::Local;
use rt::task::{Task, BlockedTask};
use sync::atomics;
// Various states you can find a port in.
static EMPTY: uint = 0;
static DATA: uint = 1;
static DISCONNECTED: uint = 2;
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: atomics::AtomicUint,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(BlockedTask),
}
pub enum SelectionResult<T> {
SelCanceled(BlockedTask),
SelUpgraded(BlockedTask, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: atomics::AtomicUint::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> bool {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => fail!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, atomics::SeqCst) {
// Sent the data, no one was waiting
EMPTY => true,
// Couldn't send the data, the port hung up first. We need to be
// sure to deallocate the sent data (to not leave it stuck in the
// queue)
DISCONNECTED => {
self.data.take_unwrap();
false
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// Anything else means that there was a task waiting on the other
// end. We leave the 'DATA' state inside so it'll pick it up on the
// other end.
n => unsafe {
let t = BlockedTask::cast_from_uint(n);
t.wake().map(|t| t.reawaken());
true
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(atomics::SeqCst) == EMPTY {
let t: ~Task = Local::take();
t.deschedule(1, |task| {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomics::SeqCst) {
// Nothing on the channel, we legitimately block
EMPTY => Ok(()),
// If there's data or it's a disconnected channel, then we
// failed the cmpxchg, so we just wake ourselves back up
DATA | DISCONNECTED => {
unsafe { Err(BlockedTask::cast_from_uint(n)) }
}
// Only one thread is allowed to sleep on this port
_ => unreachable!()
}
});
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(atomics::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, atomics::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => fail!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
n => UpWoke(unsafe { BlockedTask::cast_from_uint(n) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
n => unsafe {
let t = BlockedTask::cast_from_uint(n);
t.wake().map(|t| t.reawaken());
}
}
}
pub fn drop_port(&mut self)
|
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(atomics::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomics::SeqCst) {
EMPTY => SelSuccess,
DATA => SelCanceled(unsafe { BlockedTask::cast_from_uint(n) }),
DISCONNECTED if self.data.is_some() => {
SelCanceled(unsafe { BlockedTask::cast_from_uint(n) })
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { BlockedTask::cast_from_uint(n) },
upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
SelCanceled(unsafe { BlockedTask::cast_from_uint(n) })
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(atomics::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
n => self.state.compare_and_swap(n, EMPTY, atomics::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select. Assert that the task should be
// trashed and returne that we don't have any data.
n => {
let t = unsafe { BlockedTask::cast_from_uint(n) };
t.trash();
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(atomics::SeqCst), DISCONNECTED);
}
}
|
{
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take_unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
|
identifier_body
|
oneshot.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.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an UnsafeArc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
use comm::Receiver;
use kinds::Send;
use mem;
use ops::Drop;
use option::{Some, None, Option};
use result::{Result, Ok, Err};
use rt::local::Local;
use rt::task::{Task, BlockedTask};
use sync::atomics;
// Various states you can find a port in.
static EMPTY: uint = 0;
static DATA: uint = 1;
static DISCONNECTED: uint = 2;
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: atomics::AtomicUint,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(BlockedTask),
}
pub enum SelectionResult<T> {
SelCanceled(BlockedTask),
SelUpgraded(BlockedTask, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: atomics::AtomicUint::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> bool {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => fail!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, atomics::SeqCst) {
// Sent the data, no one was waiting
EMPTY => true,
// Couldn't send the data, the port hung up first. We need to be
// sure to deallocate the sent data (to not leave it stuck in the
// queue)
DISCONNECTED => {
self.data.take_unwrap();
false
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// Anything else means that there was a task waiting on the other
// end. We leave the 'DATA' state inside so it'll pick it up on the
// other end.
n => unsafe {
let t = BlockedTask::cast_from_uint(n);
t.wake().map(|t| t.reawaken());
true
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(atomics::SeqCst) == EMPTY {
let t: ~Task = Local::take();
t.deschedule(1, |task| {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomics::SeqCst) {
// Nothing on the channel, we legitimately block
EMPTY => Ok(()),
// If there's data or it's a disconnected channel, then we
// failed the cmpxchg, so we just wake ourselves back up
DATA | DISCONNECTED => {
unsafe { Err(BlockedTask::cast_from_uint(n)) }
}
// Only one thread is allowed to sleep on this port
_ => unreachable!()
}
});
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(atomics::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, atomics::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
|
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => fail!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
n => UpWoke(unsafe { BlockedTask::cast_from_uint(n) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
n => unsafe {
let t = BlockedTask::cast_from_uint(n);
t.wake().map(|t| t.reawaken());
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take_unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(atomics::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomics::SeqCst) {
EMPTY => SelSuccess,
DATA => SelCanceled(unsafe { BlockedTask::cast_from_uint(n) }),
DISCONNECTED if self.data.is_some() => {
SelCanceled(unsafe { BlockedTask::cast_from_uint(n) })
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { BlockedTask::cast_from_uint(n) },
upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
SelCanceled(unsafe { BlockedTask::cast_from_uint(n) })
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(atomics::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
n => self.state.compare_and_swap(n, EMPTY, atomics::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select. Assert that the task should be
// trashed and returne that we don't have any data.
n => {
let t = unsafe { BlockedTask::cast_from_uint(n) };
t.trash();
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(atomics::SeqCst), DISCONNECTED);
}
}
|
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
|
random_line_split
|
oneshot.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.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an UnsafeArc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
use comm::Receiver;
use kinds::Send;
use mem;
use ops::Drop;
use option::{Some, None, Option};
use result::{Result, Ok, Err};
use rt::local::Local;
use rt::task::{Task, BlockedTask};
use sync::atomics;
// Various states you can find a port in.
static EMPTY: uint = 0;
static DATA: uint = 1;
static DISCONNECTED: uint = 2;
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: atomics::AtomicUint,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(BlockedTask),
}
pub enum SelectionResult<T> {
SelCanceled(BlockedTask),
SelUpgraded(BlockedTask, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: atomics::AtomicUint::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> bool {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => fail!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, atomics::SeqCst) {
// Sent the data, no one was waiting
EMPTY => true,
// Couldn't send the data, the port hung up first. We need to be
// sure to deallocate the sent data (to not leave it stuck in the
// queue)
DISCONNECTED => {
self.data.take_unwrap();
false
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// Anything else means that there was a task waiting on the other
// end. We leave the 'DATA' state inside so it'll pick it up on the
// other end.
n => unsafe {
let t = BlockedTask::cast_from_uint(n);
t.wake().map(|t| t.reawaken());
true
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(atomics::SeqCst) == EMPTY {
let t: ~Task = Local::take();
t.deschedule(1, |task| {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomics::SeqCst) {
// Nothing on the channel, we legitimately block
EMPTY => Ok(()),
// If there's data or it's a disconnected channel, then we
// failed the cmpxchg, so we just wake ourselves back up
DATA | DISCONNECTED => {
unsafe { Err(BlockedTask::cast_from_uint(n)) }
}
// Only one thread is allowed to sleep on this port
_ => unreachable!()
}
});
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(atomics::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, atomics::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn
|
(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => fail!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
n => UpWoke(unsafe { BlockedTask::cast_from_uint(n) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
n => unsafe {
let t = BlockedTask::cast_from_uint(n);
t.wake().map(|t| t.reawaken());
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, atomics::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take_unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(atomics::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, task: BlockedTask) -> SelectionResult<T> {
let n = unsafe { task.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, n, atomics::SeqCst) {
EMPTY => SelSuccess,
DATA => SelCanceled(unsafe { BlockedTask::cast_from_uint(n) }),
DISCONNECTED if self.data.is_some() => {
SelCanceled(unsafe { BlockedTask::cast_from_uint(n) })
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { BlockedTask::cast_from_uint(n) },
upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
SelCanceled(unsafe { BlockedTask::cast_from_uint(n) })
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(atomics::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
n => self.state.compare_and_swap(n, EMPTY, atomics::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select. Assert that the task should be
// trashed and returne that we don't have any data.
n => {
let t = unsafe { BlockedTask::cast_from_uint(n) };
t.trash();
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(atomics::SeqCst), DISCONNECTED);
}
}
|
upgrade
|
identifier_name
|
clock.rs
|
#![cfg_attr(not(feature = "rt"), allow(dead_code))]
//! Source of time abstraction.
//!
//! By default, `std::time::Instant::now()` is used. However, when the
//! `test-util` feature flag is enabled, the values returned for `now()` are
//! configurable.
|
cfg_not_test_util! {
use crate::time::{Instant};
#[derive(Debug, Clone)]
pub(crate) struct Clock {}
pub(crate) fn now() -> Instant {
Instant::from_std(std::time::Instant::now())
}
impl Clock {
pub(crate) fn new(_enable_pausing: bool, _start_paused: bool) -> Clock {
Clock {}
}
pub(crate) fn now(&self) -> Instant {
now()
}
}
}
cfg_test_util! {
use crate::time::{Duration, Instant};
use crate::loom::sync::{Arc, Mutex};
cfg_rt! {
fn clock() -> Option<Clock> {
crate::runtime::context::clock()
}
}
cfg_not_rt! {
fn clock() -> Option<Clock> {
None
}
}
/// A handle to a source of time.
#[derive(Debug, Clone)]
pub(crate) struct Clock {
inner: Arc<Mutex<Inner>>,
}
#[derive(Debug)]
struct Inner {
/// True if the ability to pause time is enabled.
enable_pausing: bool,
/// Instant to use as the clock's base instant.
base: std::time::Instant,
/// Instant at which the clock was last unfrozen.
unfrozen: Option<std::time::Instant>,
}
/// Pauses time.
///
/// The current value of `Instant::now()` is saved and all subsequent calls
/// to `Instant::now()` will return the saved value. The saved value can be
/// changed by [`advance`] or by the time auto-advancing once the runtime
/// has no work to do. This only affects the `Instant` type in Tokio, and
/// the `Instant` in std continues to work as normal.
///
/// Pausing time requires the `current_thread` Tokio runtime. This is the
/// default runtime used by `#[tokio::test]`. The runtime can be initialized
/// with time in a paused state using the `Builder::start_paused` method.
///
/// For cases where time is immediately paused, it is better to pause
/// the time using the `main` or `test` macro:
/// ```
/// #[tokio::main(flavor = "current_thread", start_paused = true)]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// # Panics
///
/// Panics if time is already frozen or if called from outside of a
/// `current_thread` Tokio runtime.
///
/// # Auto-advance
///
/// If time is paused and the runtime has no work to do, the clock is
/// auto-advanced to the next pending timer. This means that [`Sleep`] or
/// other timer-backed primitives can cause the runtime to advance the
/// current time when awaited.
///
/// [`Sleep`]: crate::time::Sleep
/// [`advance`]: crate::time::advance
pub fn pause() {
let clock = clock().expect("time cannot be frozen from outside the Tokio runtime");
clock.pause();
}
/// Resumes time.
///
/// Clears the saved `Instant::now()` value. Subsequent calls to
/// `Instant::now()` will return the value returned by the system call.
///
/// # Panics
///
/// Panics if time is not frozen or if called from outside of the Tokio
/// runtime.
pub fn resume() {
let clock = clock().expect("time cannot be frozen from outside the Tokio runtime");
let mut inner = clock.inner.lock();
if inner.unfrozen.is_some() {
panic!("time is not frozen");
}
inner.unfrozen = Some(std::time::Instant::now());
}
/// Advances time.
///
/// Increments the saved `Instant::now()` value by `duration`. Subsequent
/// calls to `Instant::now()` will return the result of the increment.
///
/// This function will make the current time jump forward by the given
/// duration in one jump. This means that all `sleep` calls with a deadline
/// before the new time will immediately complete "at the same time", and
/// the runtime is free to poll them in any order. Additionally, this
/// method will not wait for the `sleep` calls it advanced past to complete.
/// If you want to do that, you should instead call [`sleep`] and rely on
/// the runtime's auto-advance feature.
///
/// Note that calls to `sleep` are not guaranteed to complete the first time
/// they are polled after a call to `advance`. For example, this can happen
/// if the runtime has not yet touched the timer driver after the call to
/// `advance`. However if they don't, the runtime will poll the task again
/// shortly.
///
/// # Panics
///
/// Panics if time is not frozen or if called from outside of the Tokio
/// runtime.
///
/// # Auto-advance
///
/// If the time is paused and there is no work to do, the runtime advances
/// time to the next timer. See [`pause`](pause#auto-advance) for more
/// details.
///
/// [`sleep`]: fn@crate::time::sleep
pub async fn advance(duration: Duration) {
let clock = clock().expect("time cannot be frozen from outside the Tokio runtime");
clock.advance(duration);
crate::task::yield_now().await;
}
/// Returns the current instant, factoring in frozen time.
pub(crate) fn now() -> Instant {
if let Some(clock) = clock() {
clock.now()
} else {
Instant::from_std(std::time::Instant::now())
}
}
impl Clock {
/// Returns a new `Clock` instance that uses the current execution context's
/// source of time.
pub(crate) fn new(enable_pausing: bool, start_paused: bool) -> Clock {
let now = std::time::Instant::now();
let clock = Clock {
inner: Arc::new(Mutex::new(Inner {
enable_pausing,
base: now,
unfrozen: Some(now),
})),
};
if start_paused {
clock.pause();
}
clock
}
pub(crate) fn pause(&self) {
let mut inner = self.inner.lock();
if!inner.enable_pausing {
drop(inner); // avoid poisoning the lock
panic!("`time::pause()` requires the `current_thread` Tokio runtime. \
This is the default Runtime used by `#[tokio::test].");
}
let elapsed = inner.unfrozen.as_ref().expect("time is already frozen").elapsed();
inner.base += elapsed;
inner.unfrozen = None;
}
pub(crate) fn is_paused(&self) -> bool {
let inner = self.inner.lock();
inner.unfrozen.is_none()
}
pub(crate) fn advance(&self, duration: Duration) {
let mut inner = self.inner.lock();
if inner.unfrozen.is_some() {
panic!("time is not frozen");
}
inner.base += duration;
}
pub(crate) fn now(&self) -> Instant {
let inner = self.inner.lock();
let mut ret = inner.base;
if let Some(unfrozen) = inner.unfrozen {
ret += unfrozen.elapsed();
}
Instant::from_std(ret)
}
}
}
|
random_line_split
|
|
htmlframesetelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding::HTMLFrameSetElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::root::DomRoot;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLFrameSetElement {
htmlelement: HTMLElement
}
impl HTMLFrameSetElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> HTMLFrameSetElement {
HTMLFrameSetElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn
|
(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLFrameSetElement> {
Node::reflect_node(Box::new(HTMLFrameSetElement::new_inherited(local_name, prefix, document)),
document,
HTMLFrameSetElementBinding::Wrap)
}
}
impl HTMLFrameSetElementMethods for HTMLFrameSetElement {
// https://html.spec.whatwg.org/multipage/#windoweventhandlers
window_event_handlers!(ForwardToWindow);
}
|
new
|
identifier_name
|
htmlframesetelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding::HTMLFrameSetElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::root::DomRoot;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLFrameSetElement {
htmlelement: HTMLElement
}
impl HTMLFrameSetElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> HTMLFrameSetElement {
HTMLFrameSetElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLFrameSetElement> {
Node::reflect_node(Box::new(HTMLFrameSetElement::new_inherited(local_name, prefix, document)),
document,
HTMLFrameSetElementBinding::Wrap)
}
}
impl HTMLFrameSetElementMethods for HTMLFrameSetElement {
// https://html.spec.whatwg.org/multipage/#windoweventhandlers
window_event_handlers!(ForwardToWindow);
|
}
|
random_line_split
|
|
lib.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(min_specialization)]
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
#[macro_use]
extern crate lazy_static;
|
$($name:ident => ($suffix:literal, $description:literal, $workaround:literal)),+
) => {
use crate::ErrorCode;
$(pub const $name: ErrorCode = ErrorCode {
code: concat!($prefix, $suffix),
description: $description,
workaround: $workaround,
};)+
lazy_static! {
pub static ref ALL_ERROR_CODES: Vec<ErrorCode> = vec![$($name,)+];
}
};
}
pub const UNKNOWN: ErrorCode = ErrorCode {
code: "KV:Unknown",
description: "",
workaround: "",
};
pub mod cloud;
pub mod codec;
pub mod coprocessor;
pub mod encryption;
pub mod engine;
pub mod pd;
pub mod raft;
pub mod raftstore;
pub mod sst_importer;
pub mod storage;
use std::fmt::{self, Display, Formatter};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub struct ErrorCode {
pub code: &'static str,
pub description: &'static str,
pub workaround: &'static str,
}
impl Display for ErrorCode {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.code)
}
}
pub trait ErrorCodeExt {
fn error_code(&self) -> ErrorCode;
}
#[cfg(test)]
mod tests {
#[test]
fn test_define_error_code() {
define_error_codes!(
"KV:Raftstore:",
ENTRY_TOO_LARGE => ("EntryTooLarge", "", ""),
NOT_LEADER => ("NotLeader", "", "")
);
assert_eq!(
ENTRY_TOO_LARGE,
ErrorCode {
code: "KV:Raftstore:EntryTooLarge",
description: "",
workaround: "",
}
);
assert_eq!(
NOT_LEADER,
ErrorCode {
code: "KV:Raftstore:NotLeader",
description: "",
workaround: "",
}
);
}
}
|
macro_rules! define_error_codes {
($prefix:literal,
|
random_line_split
|
lib.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(min_specialization)]
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
#[macro_use]
extern crate lazy_static;
macro_rules! define_error_codes {
($prefix:literal,
$($name:ident => ($suffix:literal, $description:literal, $workaround:literal)),+
) => {
use crate::ErrorCode;
$(pub const $name: ErrorCode = ErrorCode {
code: concat!($prefix, $suffix),
description: $description,
workaround: $workaround,
};)+
lazy_static! {
pub static ref ALL_ERROR_CODES: Vec<ErrorCode> = vec![$($name,)+];
}
};
}
pub const UNKNOWN: ErrorCode = ErrorCode {
code: "KV:Unknown",
description: "",
workaround: "",
};
pub mod cloud;
pub mod codec;
pub mod coprocessor;
pub mod encryption;
pub mod engine;
pub mod pd;
pub mod raft;
pub mod raftstore;
pub mod sst_importer;
pub mod storage;
use std::fmt::{self, Display, Formatter};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub struct ErrorCode {
pub code: &'static str,
pub description: &'static str,
pub workaround: &'static str,
}
impl Display for ErrorCode {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.code)
}
}
pub trait ErrorCodeExt {
fn error_code(&self) -> ErrorCode;
}
#[cfg(test)]
mod tests {
#[test]
fn test_define_error_code()
|
description: "",
workaround: "",
}
);
}
}
|
{
define_error_codes!(
"KV:Raftstore:",
ENTRY_TOO_LARGE => ("EntryTooLarge", "", ""),
NOT_LEADER => ("NotLeader", "", "")
);
assert_eq!(
ENTRY_TOO_LARGE,
ErrorCode {
code: "KV:Raftstore:EntryTooLarge",
description: "",
workaround: "",
}
);
assert_eq!(
NOT_LEADER,
ErrorCode {
code: "KV:Raftstore:NotLeader",
|
identifier_body
|
lib.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
#![feature(min_specialization)]
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
#[macro_use]
extern crate lazy_static;
macro_rules! define_error_codes {
($prefix:literal,
$($name:ident => ($suffix:literal, $description:literal, $workaround:literal)),+
) => {
use crate::ErrorCode;
$(pub const $name: ErrorCode = ErrorCode {
code: concat!($prefix, $suffix),
description: $description,
workaround: $workaround,
};)+
lazy_static! {
pub static ref ALL_ERROR_CODES: Vec<ErrorCode> = vec![$($name,)+];
}
};
}
pub const UNKNOWN: ErrorCode = ErrorCode {
code: "KV:Unknown",
description: "",
workaround: "",
};
pub mod cloud;
pub mod codec;
pub mod coprocessor;
pub mod encryption;
pub mod engine;
pub mod pd;
pub mod raft;
pub mod raftstore;
pub mod sst_importer;
pub mod storage;
use std::fmt::{self, Display, Formatter};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub struct ErrorCode {
pub code: &'static str,
pub description: &'static str,
pub workaround: &'static str,
}
impl Display for ErrorCode {
fn
|
(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.code)
}
}
pub trait ErrorCodeExt {
fn error_code(&self) -> ErrorCode;
}
#[cfg(test)]
mod tests {
#[test]
fn test_define_error_code() {
define_error_codes!(
"KV:Raftstore:",
ENTRY_TOO_LARGE => ("EntryTooLarge", "", ""),
NOT_LEADER => ("NotLeader", "", "")
);
assert_eq!(
ENTRY_TOO_LARGE,
ErrorCode {
code: "KV:Raftstore:EntryTooLarge",
description: "",
workaround: "",
}
);
assert_eq!(
NOT_LEADER,
ErrorCode {
code: "KV:Raftstore:NotLeader",
description: "",
workaround: "",
}
);
}
}
|
fmt
|
identifier_name
|
schema.rs
|
// Copyright 2020 The Exonum Team
//
// 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 exonum::{
crypto::PublicKey,
merkledb::{
access::{Access, FromAccess},
MapIndex,
},
};
use exonum_derive::{BinaryValue, FromAccess, ObjectHash};
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[derive(BinaryValue, ObjectHash)]
#[binary_value(codec = "bincode")]
pub struct Wallet {
pub name: String,
pub balance: u64,
}
#[derive(FromAccess)]
pub struct WalletSchema<T: Access> {
pub wallets: MapIndex<T::Base, PublicKey, Wallet>,
}
impl<T: Access> WalletSchema<T> {
pub fn
|
(access: T) -> Self {
Self::from_root(access).unwrap()
}
}
|
new
|
identifier_name
|
schema.rs
|
// Copyright 2020 The Exonum Team
//
// 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 exonum::{
|
crypto::PublicKey,
merkledb::{
access::{Access, FromAccess},
MapIndex,
},
};
use exonum_derive::{BinaryValue, FromAccess, ObjectHash};
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq)]
#[derive(Serialize, Deserialize)]
#[derive(BinaryValue, ObjectHash)]
#[binary_value(codec = "bincode")]
pub struct Wallet {
pub name: String,
pub balance: u64,
}
#[derive(FromAccess)]
pub struct WalletSchema<T: Access> {
pub wallets: MapIndex<T::Base, PublicKey, Wallet>,
}
impl<T: Access> WalletSchema<T> {
pub fn new(access: T) -> Self {
Self::from_root(access).unwrap()
}
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.