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 |
---|---|---|---|---|
lr.template.rs | #![allow(dead_code)]
#![allow(unused_mut)]
#![allow(unreachable_code)]
extern crate onig;
#[macro_use]
extern crate lazy_static;
use onig::{Regex, Syntax, RegexOptions};
use std::collections::HashMap;
/**
* Stack value.
*/
enum SV {
Undefined,
{{{SV_ENUM}}}
}
/**
* Lex rules.
*/
static LEX_RULES: {{{LEX_RULES}}};
/**
* EOF value.
*/
static EOF: &'static str = "$";
/**
* A macro for map literals.
*
* hashmap!{ 1 => "one", 2 => "two" };
*/
macro_rules! hashmap(
{ $($key:expr => $value:expr),+ } => {
{
let mut m = ::std::collections::HashMap::new();
$(
m.insert($key, $value);
)+
m
}
};
);
/**
* Unwraps a SV for the result. The result type is known from the grammar.
*/
macro_rules! get_result {
($r:expr, $ty:ident) => (match $r { SV::$ty(v) => v, _ => unreachable!() });
}
/**
* Pops a SV with needed enum value.
*/
macro_rules! pop {
($s:expr, $ty:ident) => (get_result!($s.pop().unwrap(), $ty));
}
/**
* Productions data.
*
* 0 - encoded non-terminal, 1 - length of RHS to pop from the stack
*/
static PRODUCTIONS : {{{PRODUCTIONS}}};
/**
* Table entry.
*/
enum TE {
Accept,
// Shift, and transit to the state.
Shift(usize),
// Reduce by a production number.
Reduce(usize),
// Simple state transition.
Transit(usize),
}
lazy_static! {
/**
* Lexical rules grouped by lexer state (by start condition).
*/
static ref LEX_RULES_BY_START_CONDITIONS: HashMap<&'static str, Vec<i32>> = {{{LEX_RULES_BY_START_CONDITIONS}}};
/**
* Maps a string name of a token type to its encoded number (the first
* token number starts after all numbers for non-terminal).
*/
static ref TOKENS_MAP: HashMap<&'static str, i32> = {{{TOKENS}}};
/**
* Parsing table.
*
* Vector index is the state number, value is a map
* from an encoded symbol to table entry (TE).
*/
static ref TABLE: Vec<HashMap<i32, TE>>= {{{TABLE}}};
}
// ------------------------------------
// Module include prologue.
//
// Should include at least result type:
//
// type TResult = <...>;
//
// Can also include parsing hooks:
//
// fn on_parse_begin(parser: &mut Parser, string: &str) {
// ...
// }
//
// fn on_parse_end(parser: &mut Parser, result: &TResult) {
// ...
// }
//
{{{MODULE_INCLUDE}}}
// --- end of Module include ---------
{{{TOKENIZER}}}
// ------------------------------------------------------------------
// Parser.
/**
* Parser.
*/
pub struct Parser<'t> {
/**
* Parsing stack: semantic values.
*/
values_stack: Vec<SV>,
/**
* Parsing stack: state numbers.
*/
states_stack: Vec<usize>,
/**
* Tokenizer instance.
*/
tokenizer: Tokenizer<'t>,
/**
* Semantic action handlers.
*/
handlers: [fn(&mut Parser<'t>) -> SV; {{{PRODUCTION_HANDLERS_COUNT}}}],
}
impl<'t> Parser<'t> {
/**
* Creates a new Parser instance.
*/
pub fn new() -> Parser<'t> {
Parser {
// Stacks.
values_stack: Vec::new(),
states_stack: Vec::new(),
tokenizer: Tokenizer::new(),
handlers: {{{PRODUCTION_HANDLERS_ARRAY}}}
}
}
/**
* Parses a string.
*/
pub fn parse(&mut self, string: &'t str) -> TResult {
{{{ON_PARSE_BEGIN_CALL}}}
// Initialize the tokenizer and the string.
self.tokenizer.init_string(string);
// Initialize the stacks.
self.values_stack.clear();
// Initial 0 state.
self.states_stack.clear();
self.states_stack.push(0);
let mut token = self.tokenizer.get_next_token();
let mut shifted_token = token;
loop {
let state = *self.states_stack.last().unwrap();
let column = token.kind;
if!TABLE[state].contains_key(&column) {
self.unexpected_token(&token);
break;
}
let entry = &TABLE[state][&column];
match entry {
// Shift a token, go to state.
&TE::Shift(next_state) => {
// Push token.
self.values_stack.push(SV::_0(token));
// Push next state number: "s5" -> 5
self.states_stack.push(next_state as usize);
shifted_token = token;
token = self.tokenizer.get_next_token();
},
// Reduce by production.
&TE::Reduce(production_number) => {
let production = PRODUCTIONS[production_number];
self.tokenizer.yytext = shifted_token.value;
self.tokenizer.yyleng = shifted_token.value.len();
let mut rhs_length = production[1];
while rhs_length > 0 {
self.states_stack.pop();
rhs_length = rhs_length - 1;
}
// Call the handler, push result onto the stack.
let result_value = self.handlers[production_number](self);
let previous_state = *self.states_stack.last().unwrap();
let symbol_to_reduce_with = production[0];
// Then push LHS onto the stack.
self.values_stack.push(result_value);
let next_state = match &TABLE[previous_state][&symbol_to_reduce_with] {
&TE::Transit(next_state) => next_state,
_ => unreachable!(),
};
self.states_stack.push(next_state);
},
// Accept the string.
&TE::Accept => {
// Pop state number.
self.states_stack.pop();
// Pop the parsed value.
let parsed = self.values_stack.pop().unwrap();
if self.states_stack.len()!= 1 ||
self.states_stack.pop().unwrap()!= 0 ||
self.tokenizer.has_more_tokens() {
self.unexpected_token(&token);
}
let result = get_result!(parsed, {{{RESULT_TYPE}}});
{{{ON_PARSE_END_CALL}}}
return result;
},
_ => unreachable!(),
}
}
unreachable!();
}
fn unexpected_token(&self, token: &Token) |
{{{PRODUCTION_HANDLERS}}}
}
| {
{{{ON_PARSE_ERROR_CALL}}}
} | identifier_body |
lr.template.rs | #![allow(dead_code)]
#![allow(unused_mut)]
#![allow(unreachable_code)]
extern crate onig;
#[macro_use]
extern crate lazy_static;
use onig::{Regex, Syntax, RegexOptions};
use std::collections::HashMap;
/**
* Stack value.
*/
enum SV {
Undefined,
{{{SV_ENUM}}}
}
/**
* Lex rules.
*/
static LEX_RULES: {{{LEX_RULES}}};
/**
* EOF value.
*/
static EOF: &'static str = "$";
/**
* A macro for map literals.
*
* hashmap!{ 1 => "one", 2 => "two" };
*/
macro_rules! hashmap(
{ $($key:expr => $value:expr),+ } => {
{
let mut m = ::std::collections::HashMap::new();
$(
m.insert($key, $value);
)+
m
}
};
);
/**
* Unwraps a SV for the result. The result type is known from the grammar.
*/
macro_rules! get_result {
($r:expr, $ty:ident) => (match $r { SV::$ty(v) => v, _ => unreachable!() });
}
/**
* Pops a SV with needed enum value.
*/
macro_rules! pop {
($s:expr, $ty:ident) => (get_result!($s.pop().unwrap(), $ty));
}
/**
* Productions data.
*
* 0 - encoded non-terminal, 1 - length of RHS to pop from the stack
*/
static PRODUCTIONS : {{{PRODUCTIONS}}};
/**
* Table entry.
*/
enum TE {
Accept,
// Shift, and transit to the state.
Shift(usize),
// Reduce by a production number.
Reduce(usize),
// Simple state transition.
Transit(usize),
}
lazy_static! {
/**
* Lexical rules grouped by lexer state (by start condition).
*/
static ref LEX_RULES_BY_START_CONDITIONS: HashMap<&'static str, Vec<i32>> = {{{LEX_RULES_BY_START_CONDITIONS}}};
/**
* Maps a string name of a token type to its encoded number (the first
* token number starts after all numbers for non-terminal).
*/
static ref TOKENS_MAP: HashMap<&'static str, i32> = {{{TOKENS}}};
/**
* Parsing table.
*
* Vector index is the state number, value is a map
* from an encoded symbol to table entry (TE).
*/
static ref TABLE: Vec<HashMap<i32, TE>>= {{{TABLE}}};
}
// ------------------------------------
// Module include prologue.
//
// Should include at least result type:
//
// type TResult = <...>;
//
// Can also include parsing hooks:
//
// fn on_parse_begin(parser: &mut Parser, string: &str) {
// ...
// }
//
// fn on_parse_end(parser: &mut Parser, result: &TResult) {
// ...
// }
//
{{{MODULE_INCLUDE}}}
// --- end of Module include ---------
{{{TOKENIZER}}}
// ------------------------------------------------------------------
// Parser.
/**
* Parser.
*/
pub struct Parser<'t> {
/**
* Parsing stack: semantic values.
*/
values_stack: Vec<SV>,
/**
* Parsing stack: state numbers.
*/
states_stack: Vec<usize>,
/**
* Tokenizer instance.
*/
tokenizer: Tokenizer<'t>,
/**
* Semantic action handlers.
*/
handlers: [fn(&mut Parser<'t>) -> SV; {{{PRODUCTION_HANDLERS_COUNT}}}],
}
impl<'t> Parser<'t> {
/**
* Creates a new Parser instance.
*/
pub fn new() -> Parser<'t> {
Parser {
// Stacks.
values_stack: Vec::new(),
states_stack: Vec::new(),
tokenizer: Tokenizer::new(),
handlers: {{{PRODUCTION_HANDLERS_ARRAY}}}
}
}
/**
* Parses a string.
*/
pub fn parse(&mut self, string: &'t str) -> TResult {
{{{ON_PARSE_BEGIN_CALL}}}
// Initialize the tokenizer and the string.
self.tokenizer.init_string(string);
// Initialize the stacks.
self.values_stack.clear();
// Initial 0 state.
self.states_stack.clear();
self.states_stack.push(0);
let mut token = self.tokenizer.get_next_token();
let mut shifted_token = token;
loop {
let state = *self.states_stack.last().unwrap();
let column = token.kind;
if!TABLE[state].contains_key(&column) {
self.unexpected_token(&token);
break;
}
let entry = &TABLE[state][&column];
match entry {
// Shift a token, go to state.
&TE::Shift(next_state) => {
// Push token.
self.values_stack.push(SV::_0(token));
// Push next state number: "s5" -> 5
self.states_stack.push(next_state as usize);
shifted_token = token;
token = self.tokenizer.get_next_token();
},
// Reduce by production.
&TE::Reduce(production_number) => {
let production = PRODUCTIONS[production_number];
self.tokenizer.yytext = shifted_token.value;
self.tokenizer.yyleng = shifted_token.value.len(); | while rhs_length > 0 {
self.states_stack.pop();
rhs_length = rhs_length - 1;
}
// Call the handler, push result onto the stack.
let result_value = self.handlers[production_number](self);
let previous_state = *self.states_stack.last().unwrap();
let symbol_to_reduce_with = production[0];
// Then push LHS onto the stack.
self.values_stack.push(result_value);
let next_state = match &TABLE[previous_state][&symbol_to_reduce_with] {
&TE::Transit(next_state) => next_state,
_ => unreachable!(),
};
self.states_stack.push(next_state);
},
// Accept the string.
&TE::Accept => {
// Pop state number.
self.states_stack.pop();
// Pop the parsed value.
let parsed = self.values_stack.pop().unwrap();
if self.states_stack.len()!= 1 ||
self.states_stack.pop().unwrap()!= 0 ||
self.tokenizer.has_more_tokens() {
self.unexpected_token(&token);
}
let result = get_result!(parsed, {{{RESULT_TYPE}}});
{{{ON_PARSE_END_CALL}}}
return result;
},
_ => unreachable!(),
}
}
unreachable!();
}
fn unexpected_token(&self, token: &Token) {
{{{ON_PARSE_ERROR_CALL}}}
}
{{{PRODUCTION_HANDLERS}}}
} |
let mut rhs_length = production[1]; | random_line_split |
registrar.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use attr;
use codemap::Span;
use diagnostic;
use visit;
use visit::Visitor;
struct MacroRegistrarContext { | impl Visitor<()> for MacroRegistrarContext {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"macro_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => {}
}
visit::walk_item(self, item, ());
}
}
pub fn find_macro_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::DefId> {
let mut ctx = MacroRegistrarContext { registrars: Vec::new() };
visit::walk_crate(&mut ctx, krate, ());
match ctx.registrars.len() {
0 => None,
1 => {
let (node_id, _) = ctx.registrars.pop().unwrap();
Some(ast::DefId {
krate: ast::LOCAL_CRATE,
node: node_id
})
},
_ => {
diagnostic.handler().err("multiple macro registration functions found");
for &(_, span) in ctx.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
} | registrars: Vec<(ast::NodeId, Span)> ,
}
| random_line_split |
registrar.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use attr;
use codemap::Span;
use diagnostic;
use visit;
use visit::Visitor;
struct MacroRegistrarContext {
registrars: Vec<(ast::NodeId, Span)>,
}
impl Visitor<()> for MacroRegistrarContext {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"macro_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => {}
}
visit::walk_item(self, item, ());
}
}
pub fn | (diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::DefId> {
let mut ctx = MacroRegistrarContext { registrars: Vec::new() };
visit::walk_crate(&mut ctx, krate, ());
match ctx.registrars.len() {
0 => None,
1 => {
let (node_id, _) = ctx.registrars.pop().unwrap();
Some(ast::DefId {
krate: ast::LOCAL_CRATE,
node: node_id
})
},
_ => {
diagnostic.handler().err("multiple macro registration functions found");
for &(_, span) in ctx.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
}
| find_macro_registrar | identifier_name |
registrar.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use attr;
use codemap::Span;
use diagnostic;
use visit;
use visit::Visitor;
struct MacroRegistrarContext {
registrars: Vec<(ast::NodeId, Span)>,
}
impl Visitor<()> for MacroRegistrarContext {
fn visit_item(&mut self, item: &ast::Item, _: ()) {
match item.node {
ast::ItemFn(..) => {
if attr::contains_name(item.attrs.as_slice(),
"macro_registrar") {
self.registrars.push((item.id, item.span));
}
}
_ => |
}
visit::walk_item(self, item, ());
}
}
pub fn find_macro_registrar(diagnostic: &diagnostic::SpanHandler,
krate: &ast::Crate) -> Option<ast::DefId> {
let mut ctx = MacroRegistrarContext { registrars: Vec::new() };
visit::walk_crate(&mut ctx, krate, ());
match ctx.registrars.len() {
0 => None,
1 => {
let (node_id, _) = ctx.registrars.pop().unwrap();
Some(ast::DefId {
krate: ast::LOCAL_CRATE,
node: node_id
})
},
_ => {
diagnostic.handler().err("multiple macro registration functions found");
for &(_, span) in ctx.registrars.iter() {
diagnostic.span_note(span, "one is here");
}
diagnostic.handler().abort_if_errors();
unreachable!();
}
}
}
| {} | conditional_block |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use lsp_types::{
notification::{
Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, Notification,
},
DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentItem,
};
pub fn on_did_open_text_document(
lsp_state: &impl GlobalState,
params: <DidOpenTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidOpenTextDocumentParams { text_document } = params;
let TextDocumentItem { text, uri,.. } = text_document;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_opened(&uri, &text)
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_did_close_text_document(
lsp_state: &impl GlobalState,
params: <DidCloseTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> { | .starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_closed(&uri)
}
pub fn on_did_change_text_document(
lsp_state: &impl GlobalState,
params: <DidChangeTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidChangeTextDocumentParams {
content_changes,
text_document,
} = params;
let uri = text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
// We do full text document syncing, so the new text will be in the first content change event.
let content_change = content_changes
.first()
.expect("content_changes should always be non-empty");
lsp_state.document_changed(&uri, &content_change.text)
}
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn on_did_save_text_document(
_lsp_state: &impl GlobalState,
_params: <DidSaveTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_cancel(
_lsp_state: &impl GlobalState,
_params: <Cancel as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
} | let uri = params.text_document.uri;
if !uri
.path() | random_line_split |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use lsp_types::{
notification::{
Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, Notification,
},
DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentItem,
};
pub fn on_did_open_text_document(
lsp_state: &impl GlobalState,
params: <DidOpenTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidOpenTextDocumentParams { text_document } = params;
let TextDocumentItem { text, uri,.. } = text_document;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_opened(&uri, &text)
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_did_close_text_document(
lsp_state: &impl GlobalState,
params: <DidCloseTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let uri = params.text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_closed(&uri)
}
pub fn on_did_change_text_document(
lsp_state: &impl GlobalState,
params: <DidChangeTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidChangeTextDocumentParams {
content_changes,
text_document,
} = params;
let uri = text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
// We do full text document syncing, so the new text will be in the first content change event.
let content_change = content_changes
.first()
.expect("content_changes should always be non-empty");
lsp_state.document_changed(&uri, &content_change.text)
}
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn on_did_save_text_document(
_lsp_state: &impl GlobalState,
_params: <DidSaveTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> |
#[allow(clippy::unnecessary_wraps)]
pub fn on_cancel(
_lsp_state: &impl GlobalState,
_params: <Cancel as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
| {
Ok(())
} | identifier_body |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use lsp_types::{
notification::{
Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, Notification,
},
DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentItem,
};
pub fn on_did_open_text_document(
lsp_state: &impl GlobalState,
params: <DidOpenTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidOpenTextDocumentParams { text_document } = params;
let TextDocumentItem { text, uri,.. } = text_document;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
|
lsp_state.document_opened(&uri, &text)
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_did_close_text_document(
lsp_state: &impl GlobalState,
params: <DidCloseTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let uri = params.text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_closed(&uri)
}
pub fn on_did_change_text_document(
lsp_state: &impl GlobalState,
params: <DidChangeTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidChangeTextDocumentParams {
content_changes,
text_document,
} = params;
let uri = text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
// We do full text document syncing, so the new text will be in the first content change event.
let content_change = content_changes
.first()
.expect("content_changes should always be non-empty");
lsp_state.document_changed(&uri, &content_change.text)
}
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn on_did_save_text_document(
_lsp_state: &impl GlobalState,
_params: <DidSaveTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_cancel(
_lsp_state: &impl GlobalState,
_params: <Cancel as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
| {
return Ok(());
} | conditional_block |
text_documents.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
//! Utilities related to LSP text document syncing
use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState};
use lsp_types::{
notification::{
Cancel, DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument,
DidSaveTextDocument, Notification,
},
DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentItem,
};
pub fn | (
lsp_state: &impl GlobalState,
params: <DidOpenTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidOpenTextDocumentParams { text_document } = params;
let TextDocumentItem { text, uri,.. } = text_document;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_opened(&uri, &text)
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_did_close_text_document(
lsp_state: &impl GlobalState,
params: <DidCloseTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let uri = params.text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
lsp_state.document_closed(&uri)
}
pub fn on_did_change_text_document(
lsp_state: &impl GlobalState,
params: <DidChangeTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
let DidChangeTextDocumentParams {
content_changes,
text_document,
} = params;
let uri = text_document.uri;
if!uri
.path()
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref())
{
return Ok(());
}
// We do full text document syncing, so the new text will be in the first content change event.
let content_change = content_changes
.first()
.expect("content_changes should always be non-empty");
lsp_state.document_changed(&uri, &content_change.text)
}
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn on_did_save_text_document(
_lsp_state: &impl GlobalState,
_params: <DidSaveTextDocument as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
#[allow(clippy::unnecessary_wraps)]
pub fn on_cancel(
_lsp_state: &impl GlobalState,
_params: <Cancel as Notification>::Params,
) -> LSPRuntimeResult<()> {
Ok(())
}
| on_did_open_text_document | identifier_name |
vpcmpistri.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistri_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 214, 114], OperandSize::Dword)
}
fn vpcmpistri_2() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM0)), operand2: Some(Indirect(EDI, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(41)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 7, 41], OperandSize::Dword)
}
fn vpcmpistri_3() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(0)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 240, 0], OperandSize::Qword)
}
fn vpcmpistri_4() | {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 20, 221, 15, 11, 5, 63, 114], OperandSize::Qword)
} | identifier_body |
|
vpcmpistri.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vpcmpistri_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 214, 114], OperandSize::Dword)
}
fn vpcmpistri_2() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM0)), operand2: Some(Indirect(EDI, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(41)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 7, 41], OperandSize::Dword)
}
fn vpcmpistri_3() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(0)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 240, 0], OperandSize::Qword)
}
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 20, 221, 15, 11, 5, 63, 114], OperandSize::Qword)
}
| vpcmpistri_4 | identifier_name |
vpcmpistri.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*; | run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 214, 114], OperandSize::Dword)
}
fn vpcmpistri_2() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM0)), operand2: Some(Indirect(EDI, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(41)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 7, 41], OperandSize::Dword)
}
fn vpcmpistri_3() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(0)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 240, 0], OperandSize::Qword)
}
fn vpcmpistri_4() {
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 20, 221, 15, 11, 5, 63, 114], OperandSize::Qword)
} | use ::Reg::*;
use ::RegScale::*;
fn vpcmpistri_1() { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// For simd (currently x86_64/aarch64)
#![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "windows"), feature(heap_api))]
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![feature(range_contains)]
#![feature(unique)]
#![plugin(heapsize_plugin)]
#![plugin(plugins)]
#![plugin(serde_macros)]
#![deny(unsafe_code)]
extern crate alloc;
extern crate app_units;
extern crate azure;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
// Mac OS-specific library dependencies
#[cfg(target_os = "macos")] extern crate byteorder;
#[cfg(target_os = "macos")] extern crate core_foundation;
#[cfg(target_os = "macos")] extern crate core_graphics;
#[cfg(target_os = "macos")] extern crate core_text; | // Platforms that use Freetype/Fontconfig library dependencies
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate fontconfig;
#[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))]
extern crate freetype;
extern crate gfx_traits;
// Eventually we would like the shaper to be pluggable, as many operating systems have their own
// shapers. For now, however, this is a hard dependency.
extern crate harfbuzz_sys as harfbuzz;
extern crate heapsize;
extern crate ipc_channel;
extern crate layers;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate lazy_static;
extern crate libc;
#[macro_use]
extern crate log;
extern crate mime;
extern crate msg;
extern crate net_traits;
extern crate ordered_float;
#[macro_use]
extern crate profile_traits;
extern crate rand;
#[macro_use]
extern crate range;
extern crate rustc_serialize;
extern crate serde;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
extern crate simd;
extern crate smallvec;
#[macro_use]
extern crate string_cache;
extern crate style;
extern crate style_traits;
extern crate time;
extern crate unicode_script;
extern crate url;
extern crate util;
extern crate webrender_traits;
extern crate xi_unicode;
pub use paint_context::PaintContext;
// Misc.
mod filters;
// Private painting modules
mod paint_context;
#[deny(unsafe_code)]
pub mod display_list;
// Fonts
#[macro_use] pub mod font;
pub mod font_cache_thread;
pub mod font_context;
pub mod font_template;
pub mod paint_thread;
// Platform-specific implementations.
#[allow(unsafe_code)]
mod platform;
// Text
pub mod text; |
extern crate euclid;
extern crate fnv;
| random_line_split |
unparse.rs | use crate::{
ast::{Ast, AstContents, AstContents::*},
grammar::{
FormPat::{self, *},
SynEnv,
},
name::*,
util::mbe::EnvMBE,
};
fn node_names_mentioned(pat: &FormPat) -> Vec<Name> {
match *pat {
Named(n, ref body) => {
let mut res = node_names_mentioned(&*body);
res.push(n);
res
}
Scope(_, _) => vec![],
Pick(_, _) => vec![],
Star(ref body)
| Plus(ref body)
| NameImport(ref body, _)
| NameImportPhaseless(ref body, _)
| VarRef(ref body)
| Literal(ref body, _)
| QuoteDeepen(ref body, _)
| QuoteEscape(ref body, _)
| Common(ref body)
| Reserved(ref body, _) => node_names_mentioned(&*body),
Seq(ref sub_pats) | Alt(ref sub_pats) => {
let mut res = vec![];
for pat in sub_pats {
res.append(&mut node_names_mentioned(pat));
}
res
}
Biased(ref lhs, ref rhs) => {
let mut res = node_names_mentioned(&*lhs);
res.append(&mut node_names_mentioned(&*rhs));
res
}
Anyways(_) | Impossible | Scan(_, _) | Call(_) | SynImport(_, _, _) => vec![],
}
}
pub fn unparse_mbe(pat: &FormPat, actl: &AstContents, context: &EnvMBE<Ast>, s: &SynEnv) -> String {
// HACK: handle underdetermined forms
let undet = crate::ty_compare::underdetermined_form.with(|u| u.clone());
match actl {
Node(form, body, _) if form == &undet => {
return crate::ty_compare::unification.with(|unif| {
let var = body.get_leaf_or_panic(&n("id")).to_name();
let looked_up = unif.borrow().get(&var).cloned();
match looked_up {
// Apparently the environment is recursive; `{}`ing it stack-overflows
Some(ref clo) => {
format!("{} in some environment", clo.it /*, {:#?} clo.env */)
}
None => format!("¿{}?", var),
}
});
}
_ => {}
}
// TODO: this really ought to notice when `actl` is ill-formed for `pat`.
match (pat, actl) {
(&Named(name, ref body), _) => {
// TODO: why does the `unwrap_or` case happen once after each variable is printed?
unparse_mbe(&*body, context.get_leaf(name).unwrap_or(&ast!((at ""))).c(), context, s)
}
(&Call(sub_form), _) => unparse_mbe(s.find_or_panic(&sub_form), actl, context, s),
(&Anyways(_), _) | (&Impossible, _) => "".to_string(),
(&Literal(_, n), _) => n.print(),
(&Scan(_, _), &Atom(n)) => n.print(),
(&Scan(_, _), _) => "".to_string(), // HACK for `Alt`
(&VarRef(ref sub_form), &VariableReference(n)) => {
unparse_mbe(&*sub_form, &Atom(n), context, s)
}
(&VarRef(_), _) => "".to_string(), // HACK for `Alt`
(&Seq(ref sub_pats), _) => {
let mut prev_empty = true;
let mut res = String::new();
for sub_pat in sub_pats {
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if!prev_empty && sub_res!= "" {
res.push(' ');
}
prev_empty = sub_res == "";
res.push_str(&sub_res);
}
res
}
(&Alt(ref sub_pats), _) => {
let mut any_scopes = false;
for sub_pat in sub_pats {
if let Scope(_, _) = &**sub_pat {
any_scopes = true;
continue;
}
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if sub_res!= "" {
return sub_res;
} // HACK: should use `Option`
}
// HACK: certain forms don't live in the syntax environment,
// but "belong" under an `Alt`, so just assume forms know their grammar:
if any_scopes {
if let &Node(ref form_actual, ref body, _) = actl {
return unparse_mbe(&*form_actual.grammar, actl, body, s);
}
}
return "".to_string(); // Not sure if it's an error, or really just empty
}
(&Biased(ref lhs, ref rhs), _) => {
format!("{}{}", unparse_mbe(lhs, actl, context, s), unparse_mbe(rhs, actl, context, s))
}
(&Star(ref sub_pat), _) | (&Plus(ref sub_pat), _) => {
let mut first = true;
let mut res = String::new();
for marched_ctxt in context.march_all(&node_names_mentioned(&*sub_pat)) { | }
first = false;
res.push_str(&unparse_mbe(&*sub_pat, actl, &marched_ctxt, s));
}
res
}
(&Scope(ref form, _), &Node(ref form_actual, ref body, _)) => {
if form == form_actual {
unparse_mbe(&*form.grammar, actl, body, s)
} else {
"".to_string() // HACK for `Alt`
}
}
(&Scope(_, _), _) => "".to_string(), // Non-match
(&Pick(ref body, _), _) | (&Common(ref body), _) => unparse_mbe(&*body, actl, context, s),
(&NameImport(ref body, _), &ExtendEnv(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImport(_, _), _) => format!("[Missing import]→{:#?}←", actl),
(&NameImportPhaseless(ref body, _), &ExtendEnvPhaseless(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImportPhaseless(_, _), _) => format!("[Missing import]±→{:#?}←±", actl),
(&QuoteDeepen(ref body, _), &QuoteMore(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteDeepen(_, _), _) => format!("[Missing qm]{:#?}", actl),
(&QuoteEscape(ref body, _), &QuoteLess(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteEscape(_, _), _) => format!("[Missing ql]{:#?}", actl),
(&SynImport(ref _lhs_grammar, ref _rhs, _), &Node(_, ref actl_body, _)) => {
// TODO: I think we need to store the LHS or the new SynEnv to make this pretty.
format!("?syntax import? {}", actl_body)
}
(&SynImport(_, _, _), _) => "".to_string(),
(&Reserved(ref body, _), _) => unparse_mbe(body, actl, context, s),
}
} | if !first {
res.push(' '); | random_line_split |
unparse.rs | use crate::{
ast::{Ast, AstContents, AstContents::*},
grammar::{
FormPat::{self, *},
SynEnv,
},
name::*,
util::mbe::EnvMBE,
};
fn node_names_mentioned(pat: &FormPat) -> Vec<Name> {
match *pat {
Named(n, ref body) => {
let mut res = node_names_mentioned(&*body);
res.push(n);
res
}
Scope(_, _) => vec![],
Pick(_, _) => vec![],
Star(ref body)
| Plus(ref body)
| NameImport(ref body, _)
| NameImportPhaseless(ref body, _)
| VarRef(ref body)
| Literal(ref body, _)
| QuoteDeepen(ref body, _)
| QuoteEscape(ref body, _)
| Common(ref body)
| Reserved(ref body, _) => node_names_mentioned(&*body),
Seq(ref sub_pats) | Alt(ref sub_pats) => {
let mut res = vec![];
for pat in sub_pats {
res.append(&mut node_names_mentioned(pat));
}
res
}
Biased(ref lhs, ref rhs) => {
let mut res = node_names_mentioned(&*lhs);
res.append(&mut node_names_mentioned(&*rhs));
res
}
Anyways(_) | Impossible | Scan(_, _) | Call(_) | SynImport(_, _, _) => vec![],
}
}
pub fn unparse_mbe(pat: &FormPat, actl: &AstContents, context: &EnvMBE<Ast>, s: &SynEnv) -> String | // TODO: this really ought to notice when `actl` is ill-formed for `pat`.
match (pat, actl) {
(&Named(name, ref body), _) => {
// TODO: why does the `unwrap_or` case happen once after each variable is printed?
unparse_mbe(&*body, context.get_leaf(name).unwrap_or(&ast!((at ""))).c(), context, s)
}
(&Call(sub_form), _) => unparse_mbe(s.find_or_panic(&sub_form), actl, context, s),
(&Anyways(_), _) | (&Impossible, _) => "".to_string(),
(&Literal(_, n), _) => n.print(),
(&Scan(_, _), &Atom(n)) => n.print(),
(&Scan(_, _), _) => "".to_string(), // HACK for `Alt`
(&VarRef(ref sub_form), &VariableReference(n)) => {
unparse_mbe(&*sub_form, &Atom(n), context, s)
}
(&VarRef(_), _) => "".to_string(), // HACK for `Alt`
(&Seq(ref sub_pats), _) => {
let mut prev_empty = true;
let mut res = String::new();
for sub_pat in sub_pats {
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if!prev_empty && sub_res!= "" {
res.push(' ');
}
prev_empty = sub_res == "";
res.push_str(&sub_res);
}
res
}
(&Alt(ref sub_pats), _) => {
let mut any_scopes = false;
for sub_pat in sub_pats {
if let Scope(_, _) = &**sub_pat {
any_scopes = true;
continue;
}
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if sub_res!= "" {
return sub_res;
} // HACK: should use `Option`
}
// HACK: certain forms don't live in the syntax environment,
// but "belong" under an `Alt`, so just assume forms know their grammar:
if any_scopes {
if let &Node(ref form_actual, ref body, _) = actl {
return unparse_mbe(&*form_actual.grammar, actl, body, s);
}
}
return "".to_string(); // Not sure if it's an error, or really just empty
}
(&Biased(ref lhs, ref rhs), _) => {
format!("{}{}", unparse_mbe(lhs, actl, context, s), unparse_mbe(rhs, actl, context, s))
}
(&Star(ref sub_pat), _) | (&Plus(ref sub_pat), _) => {
let mut first = true;
let mut res = String::new();
for marched_ctxt in context.march_all(&node_names_mentioned(&*sub_pat)) {
if!first {
res.push(' ');
}
first = false;
res.push_str(&unparse_mbe(&*sub_pat, actl, &marched_ctxt, s));
}
res
}
(&Scope(ref form, _), &Node(ref form_actual, ref body, _)) => {
if form == form_actual {
unparse_mbe(&*form.grammar, actl, body, s)
} else {
"".to_string() // HACK for `Alt`
}
}
(&Scope(_, _), _) => "".to_string(), // Non-match
(&Pick(ref body, _), _) | (&Common(ref body), _) => unparse_mbe(&*body, actl, context, s),
(&NameImport(ref body, _), &ExtendEnv(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImport(_, _), _) => format!("[Missing import]→{:#?}←", actl),
(&NameImportPhaseless(ref body, _), &ExtendEnvPhaseless(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImportPhaseless(_, _), _) => format!("[Missing import]±→{:#?}←±", actl),
(&QuoteDeepen(ref body, _), &QuoteMore(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteDeepen(_, _), _) => format!("[Missing qm]{:#?}", actl),
(&QuoteEscape(ref body, _), &QuoteLess(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteEscape(_, _), _) => format!("[Missing ql]{:#?}", actl),
(&SynImport(ref _lhs_grammar, ref _rhs, _), &Node(_, ref actl_body, _)) => {
// TODO: I think we need to store the LHS or the new SynEnv to make this pretty.
format!("?syntax import? {}", actl_body)
}
(&SynImport(_, _, _), _) => "".to_string(),
(&Reserved(ref body, _), _) => unparse_mbe(body, actl, context, s),
}
}
| {
// HACK: handle underdetermined forms
let undet = crate::ty_compare::underdetermined_form.with(|u| u.clone());
match actl {
Node(form, body, _) if form == &undet => {
return crate::ty_compare::unification.with(|unif| {
let var = body.get_leaf_or_panic(&n("id")).to_name();
let looked_up = unif.borrow().get(&var).cloned();
match looked_up {
// Apparently the environment is recursive; `{}`ing it stack-overflows
Some(ref clo) => {
format!("{} in some environment", clo.it /* , {:#?} clo.env */)
}
None => format!("¿{}?", var),
}
});
}
_ => {}
}
| identifier_body |
unparse.rs | use crate::{
ast::{Ast, AstContents, AstContents::*},
grammar::{
FormPat::{self, *},
SynEnv,
},
name::*,
util::mbe::EnvMBE,
};
fn | (pat: &FormPat) -> Vec<Name> {
match *pat {
Named(n, ref body) => {
let mut res = node_names_mentioned(&*body);
res.push(n);
res
}
Scope(_, _) => vec![],
Pick(_, _) => vec![],
Star(ref body)
| Plus(ref body)
| NameImport(ref body, _)
| NameImportPhaseless(ref body, _)
| VarRef(ref body)
| Literal(ref body, _)
| QuoteDeepen(ref body, _)
| QuoteEscape(ref body, _)
| Common(ref body)
| Reserved(ref body, _) => node_names_mentioned(&*body),
Seq(ref sub_pats) | Alt(ref sub_pats) => {
let mut res = vec![];
for pat in sub_pats {
res.append(&mut node_names_mentioned(pat));
}
res
}
Biased(ref lhs, ref rhs) => {
let mut res = node_names_mentioned(&*lhs);
res.append(&mut node_names_mentioned(&*rhs));
res
}
Anyways(_) | Impossible | Scan(_, _) | Call(_) | SynImport(_, _, _) => vec![],
}
}
pub fn unparse_mbe(pat: &FormPat, actl: &AstContents, context: &EnvMBE<Ast>, s: &SynEnv) -> String {
// HACK: handle underdetermined forms
let undet = crate::ty_compare::underdetermined_form.with(|u| u.clone());
match actl {
Node(form, body, _) if form == &undet => {
return crate::ty_compare::unification.with(|unif| {
let var = body.get_leaf_or_panic(&n("id")).to_name();
let looked_up = unif.borrow().get(&var).cloned();
match looked_up {
// Apparently the environment is recursive; `{}`ing it stack-overflows
Some(ref clo) => {
format!("{} in some environment", clo.it /*, {:#?} clo.env */)
}
None => format!("¿{}?", var),
}
});
}
_ => {}
}
// TODO: this really ought to notice when `actl` is ill-formed for `pat`.
match (pat, actl) {
(&Named(name, ref body), _) => {
// TODO: why does the `unwrap_or` case happen once after each variable is printed?
unparse_mbe(&*body, context.get_leaf(name).unwrap_or(&ast!((at ""))).c(), context, s)
}
(&Call(sub_form), _) => unparse_mbe(s.find_or_panic(&sub_form), actl, context, s),
(&Anyways(_), _) | (&Impossible, _) => "".to_string(),
(&Literal(_, n), _) => n.print(),
(&Scan(_, _), &Atom(n)) => n.print(),
(&Scan(_, _), _) => "".to_string(), // HACK for `Alt`
(&VarRef(ref sub_form), &VariableReference(n)) => {
unparse_mbe(&*sub_form, &Atom(n), context, s)
}
(&VarRef(_), _) => "".to_string(), // HACK for `Alt`
(&Seq(ref sub_pats), _) => {
let mut prev_empty = true;
let mut res = String::new();
for sub_pat in sub_pats {
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if!prev_empty && sub_res!= "" {
res.push(' ');
}
prev_empty = sub_res == "";
res.push_str(&sub_res);
}
res
}
(&Alt(ref sub_pats), _) => {
let mut any_scopes = false;
for sub_pat in sub_pats {
if let Scope(_, _) = &**sub_pat {
any_scopes = true;
continue;
}
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if sub_res!= "" {
return sub_res;
} // HACK: should use `Option`
}
// HACK: certain forms don't live in the syntax environment,
// but "belong" under an `Alt`, so just assume forms know their grammar:
if any_scopes {
if let &Node(ref form_actual, ref body, _) = actl {
return unparse_mbe(&*form_actual.grammar, actl, body, s);
}
}
return "".to_string(); // Not sure if it's an error, or really just empty
}
(&Biased(ref lhs, ref rhs), _) => {
format!("{}{}", unparse_mbe(lhs, actl, context, s), unparse_mbe(rhs, actl, context, s))
}
(&Star(ref sub_pat), _) | (&Plus(ref sub_pat), _) => {
let mut first = true;
let mut res = String::new();
for marched_ctxt in context.march_all(&node_names_mentioned(&*sub_pat)) {
if!first {
res.push(' ');
}
first = false;
res.push_str(&unparse_mbe(&*sub_pat, actl, &marched_ctxt, s));
}
res
}
(&Scope(ref form, _), &Node(ref form_actual, ref body, _)) => {
if form == form_actual {
unparse_mbe(&*form.grammar, actl, body, s)
} else {
"".to_string() // HACK for `Alt`
}
}
(&Scope(_, _), _) => "".to_string(), // Non-match
(&Pick(ref body, _), _) | (&Common(ref body), _) => unparse_mbe(&*body, actl, context, s),
(&NameImport(ref body, _), &ExtendEnv(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImport(_, _), _) => format!("[Missing import]→{:#?}←", actl),
(&NameImportPhaseless(ref body, _), &ExtendEnvPhaseless(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImportPhaseless(_, _), _) => format!("[Missing import]±→{:#?}←±", actl),
(&QuoteDeepen(ref body, _), &QuoteMore(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteDeepen(_, _), _) => format!("[Missing qm]{:#?}", actl),
(&QuoteEscape(ref body, _), &QuoteLess(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteEscape(_, _), _) => format!("[Missing ql]{:#?}", actl),
(&SynImport(ref _lhs_grammar, ref _rhs, _), &Node(_, ref actl_body, _)) => {
// TODO: I think we need to store the LHS or the new SynEnv to make this pretty.
format!("?syntax import? {}", actl_body)
}
(&SynImport(_, _, _), _) => "".to_string(),
(&Reserved(ref body, _), _) => unparse_mbe(body, actl, context, s),
}
}
| node_names_mentioned | identifier_name |
unparse.rs | use crate::{
ast::{Ast, AstContents, AstContents::*},
grammar::{
FormPat::{self, *},
SynEnv,
},
name::*,
util::mbe::EnvMBE,
};
fn node_names_mentioned(pat: &FormPat) -> Vec<Name> {
match *pat {
Named(n, ref body) => {
let mut res = node_names_mentioned(&*body);
res.push(n);
res
}
Scope(_, _) => vec![],
Pick(_, _) => vec![],
Star(ref body)
| Plus(ref body)
| NameImport(ref body, _)
| NameImportPhaseless(ref body, _)
| VarRef(ref body)
| Literal(ref body, _)
| QuoteDeepen(ref body, _)
| QuoteEscape(ref body, _)
| Common(ref body)
| Reserved(ref body, _) => node_names_mentioned(&*body),
Seq(ref sub_pats) | Alt(ref sub_pats) => {
let mut res = vec![];
for pat in sub_pats {
res.append(&mut node_names_mentioned(pat));
}
res
}
Biased(ref lhs, ref rhs) => {
let mut res = node_names_mentioned(&*lhs);
res.append(&mut node_names_mentioned(&*rhs));
res
}
Anyways(_) | Impossible | Scan(_, _) | Call(_) | SynImport(_, _, _) => vec![],
}
}
pub fn unparse_mbe(pat: &FormPat, actl: &AstContents, context: &EnvMBE<Ast>, s: &SynEnv) -> String {
// HACK: handle underdetermined forms
let undet = crate::ty_compare::underdetermined_form.with(|u| u.clone());
match actl {
Node(form, body, _) if form == &undet => {
return crate::ty_compare::unification.with(|unif| {
let var = body.get_leaf_or_panic(&n("id")).to_name();
let looked_up = unif.borrow().get(&var).cloned();
match looked_up {
// Apparently the environment is recursive; `{}`ing it stack-overflows
Some(ref clo) => {
format!("{} in some environment", clo.it /*, {:#?} clo.env */)
}
None => format!("¿{}?", var),
}
});
}
_ => {}
}
// TODO: this really ought to notice when `actl` is ill-formed for `pat`.
match (pat, actl) {
(&Named(name, ref body), _) => {
// TODO: why does the `unwrap_or` case happen once after each variable is printed?
unparse_mbe(&*body, context.get_leaf(name).unwrap_or(&ast!((at ""))).c(), context, s)
}
(&Call(sub_form), _) => unparse_mbe(s.find_or_panic(&sub_form), actl, context, s),
(&Anyways(_), _) | (&Impossible, _) => "".to_string(),
(&Literal(_, n), _) => n.print(),
(&Scan(_, _), &Atom(n)) => n.print(),
(&Scan(_, _), _) => "".to_string(), // HACK for `Alt`
(&VarRef(ref sub_form), &VariableReference(n)) => {
unparse_mbe(&*sub_form, &Atom(n), context, s)
}
(&VarRef(_), _) => "".to_string(), // HACK for `Alt`
(&Seq(ref sub_pats), _) => {
let mut prev_empty = true;
let mut res = String::new();
for sub_pat in sub_pats {
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if!prev_empty && sub_res!= "" {
res.push(' ');
}
prev_empty = sub_res == "";
res.push_str(&sub_res);
}
res
}
(&Alt(ref sub_pats), _) => {
let mut any_scopes = false;
for sub_pat in sub_pats {
if let Scope(_, _) = &**sub_pat { |
let sub_res = unparse_mbe(&*sub_pat, actl, context, s);
if sub_res!= "" {
return sub_res;
} // HACK: should use `Option`
}
// HACK: certain forms don't live in the syntax environment,
// but "belong" under an `Alt`, so just assume forms know their grammar:
if any_scopes {
if let &Node(ref form_actual, ref body, _) = actl {
return unparse_mbe(&*form_actual.grammar, actl, body, s);
}
}
return "".to_string(); // Not sure if it's an error, or really just empty
}
(&Biased(ref lhs, ref rhs), _) => {
format!("{}{}", unparse_mbe(lhs, actl, context, s), unparse_mbe(rhs, actl, context, s))
}
(&Star(ref sub_pat), _) | (&Plus(ref sub_pat), _) => {
let mut first = true;
let mut res = String::new();
for marched_ctxt in context.march_all(&node_names_mentioned(&*sub_pat)) {
if!first {
res.push(' ');
}
first = false;
res.push_str(&unparse_mbe(&*sub_pat, actl, &marched_ctxt, s));
}
res
}
(&Scope(ref form, _), &Node(ref form_actual, ref body, _)) => {
if form == form_actual {
unparse_mbe(&*form.grammar, actl, body, s)
} else {
"".to_string() // HACK for `Alt`
}
}
(&Scope(_, _), _) => "".to_string(), // Non-match
(&Pick(ref body, _), _) | (&Common(ref body), _) => unparse_mbe(&*body, actl, context, s),
(&NameImport(ref body, _), &ExtendEnv(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImport(_, _), _) => format!("[Missing import]→{:#?}←", actl),
(&NameImportPhaseless(ref body, _), &ExtendEnvPhaseless(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&NameImportPhaseless(_, _), _) => format!("[Missing import]±→{:#?}←±", actl),
(&QuoteDeepen(ref body, _), &QuoteMore(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteDeepen(_, _), _) => format!("[Missing qm]{:#?}", actl),
(&QuoteEscape(ref body, _), &QuoteLess(ref actl_body, _)) => {
unparse_mbe(&*body, actl_body.c(), context, s)
}
(&QuoteEscape(_, _), _) => format!("[Missing ql]{:#?}", actl),
(&SynImport(ref _lhs_grammar, ref _rhs, _), &Node(_, ref actl_body, _)) => {
// TODO: I think we need to store the LHS or the new SynEnv to make this pretty.
format!("?syntax import? {}", actl_body)
}
(&SynImport(_, _, _), _) => "".to_string(),
(&Reserved(ref body, _), _) => unparse_mbe(body, actl, context, s),
}
}
|
any_scopes = true;
continue;
}
| conditional_block |
flow_control.rs | #![allow(dead_code, unreachable_code, unused_variables)]
pub fn flow_control() {
println!("***Flow Control***");
if_else();
loops();
whiles();
for_ranges();
matching();
if_let();
while_let();
println!("");
}
fn if_else() {
let n = 5;
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero!", n);
}
let big_n = if n < 10 && n > -10 {
println!(", and is small number, increase ten-fold");
10 * n
} else {
println!(", and is a big number, reduce by two");
n / 2
};
println!("{} -> {}", n, big_n);
}
fn loops() {
let mut count = 0_u32;
println!("Let's count until infinity!");
// Infinite loop
loop {
count += 1;
if count == 3 {
println!("three!");
continue;
}
println!("{}", count);
if count == 5 {
println!("that's enough!");
break;
}
}
// nesting and labels
'outer: loop {
println!("Entered the outer loop.");
'inner: loop {
println!("Entered the inner loop.");
// this would only break the inner loop
// break;
// this breaks the outer loop
break 'outer;
}
unreachable!();
}
println!("Exited the outer loop.");
}
fn whiles() {
// let mut n = 1;
// while n < 101 {
// if n % 15 == 0 {
// println!("fizzbuzz");
// } else if n % 3 == 0 {
// println!("fizz");
// } else if n % 5 == 0 {
// println!("buzz", );
// } else {
// println!("{}", n);
// }
// n += 1;
// }
}
fn for_ranges() {
// for n in 1..101 {
// if n % 15 == 0 {
// println!("fizzbuzz");
// } else if n % 3 == 0 {
// println!("fizz");
// } else if n % 5 == 0 {
// println!("buzz");
// } else {
// println!("{}", n);
// }
// }
}
enum Color {
Red,
Blue,
Green,
RGB(u32, u32, u32),
}
fn matching() {
let number = 13;
match number {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13...19 => println!("A teen"),
_ => println!("ain't special", ),
}
let boolean = true;
let binary = match boolean {
false => 0,
true => 1,
};
println!("{} -> {}", boolean, binary);
// destructuring tuples
let pair = (0, -2);
match pair {
(0, y) => println!("first is 0 and y is {:?}", y),
(x, 0) => println!("first is {:?} and y is 0", x),
_ => println!("it doesn't matter what they are"),
}
// enums
let color = Color::RGB(112, 17, 40);
match color {
Color::Red => println!("The Color is Red!"),
Color::Green => println!("The Color is Green!"),
Color::Blue => println!("The Color is Blue!"),
Color::RGB(r, g, b) => println!("R: {}, G: {}, B: {}", r, g, b),
}
// pointers / refs |
match reference {
&val => println!("Got by destructuring: {:?}", val),
}
// to avoid the '&', dereference before matching
match *reference {
val => println!("Got by dereferencing: {:?}", val),
}
// same as &3
let ref is_a_ref = 3;
let value = 5;
let mut mut_value = 6;
// use ref keyword to create a reference
match value {
ref r => println!("got a reference to a value: {:?}", r),
}
match mut_value {
ref mut m => {
*m += 10;
println!("we added 10, mut_value is now {:?}", m);
}
}
// destructuring structs
struct Foo { x: (u32, u32), y: u32 }
let foo = Foo { x: (1, 2), y: 3 };
let Foo { x: (a, b), y } = foo;
println!("a = {}, b = {}, y = {}", a, b, y);
let Foo { y: i, x: j } = foo;
println!("i = {:?}, j = {:?}", i, j);
let Foo { y,.. } = foo;
println!("y = {}", y);
// match guards
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("These are twins"),
(x, y) if x + y == 0 => println!("animatter!"),
(x, _) if x % 2 == 1 => println!("The first one is odd.."),
_ => println!("no corelation.."),
}
match age() {
0 => println!("I'm not born yet?"),
n @ 1... 12 => println!("I'm a child of age {:?}", n),
n @ 13... 19 => println!("I'm a teen of age {:?}", n),
n => println!("I'm an old person of age {:?}", n),
}
}
fn if_let() {
let number = Some(7);
let letter: Option<i32> = None;
let emoji: Option<i32> = None;
if let Some(i) = number {
println!("Matched {:?}", i);
}
if let Some(i) = letter {
println!("Matched {:?}", i);
} else {
println!("Didn't match a number! Let's go with a letter.");
}
// altered failing condition
let i_like_letters = false;
if let Some(i) = emoji {
println!("Matched {:?}", i);
} else if i_like_letters {
println!("Didn't match a number! Let's go with a letter.");
} else {
println!("Maybe go with an emoji instead?");
}
}
fn while_let() {
let mut optional = Some(0);
while let Some(i) = optional {
if i > 9 {
println!("Greater than 9, quit!");
optional = None;
} else {
println!("i is {:?}, try again!", i);
optional = Some(i + 1);
}
}
}
fn age() -> u32 {
15
} |
let reference = &4; | random_line_split |
flow_control.rs | #![allow(dead_code, unreachable_code, unused_variables)]
pub fn flow_control() {
println!("***Flow Control***");
if_else();
loops();
whiles();
for_ranges();
matching();
if_let();
while_let();
println!("");
}
fn if_else() {
let n = 5;
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero!", n);
}
let big_n = if n < 10 && n > -10 {
println!(", and is small number, increase ten-fold");
10 * n
} else {
println!(", and is a big number, reduce by two");
n / 2
};
println!("{} -> {}", n, big_n);
}
fn loops() {
let mut count = 0_u32;
println!("Let's count until infinity!");
// Infinite loop
loop {
count += 1;
if count == 3 {
println!("three!");
continue;
}
println!("{}", count);
if count == 5 {
println!("that's enough!");
break;
}
}
// nesting and labels
'outer: loop {
println!("Entered the outer loop.");
'inner: loop {
println!("Entered the inner loop.");
// this would only break the inner loop
// break;
// this breaks the outer loop
break 'outer;
}
unreachable!();
}
println!("Exited the outer loop.");
}
fn whiles() {
// let mut n = 1;
// while n < 101 {
// if n % 15 == 0 {
// println!("fizzbuzz");
// } else if n % 3 == 0 {
// println!("fizz");
// } else if n % 5 == 0 {
// println!("buzz", );
// } else {
// println!("{}", n);
// }
// n += 1;
// }
}
fn for_ranges() {
// for n in 1..101 {
// if n % 15 == 0 {
// println!("fizzbuzz");
// } else if n % 3 == 0 {
// println!("fizz");
// } else if n % 5 == 0 {
// println!("buzz");
// } else {
// println!("{}", n);
// }
// }
}
enum Color {
Red,
Blue,
Green,
RGB(u32, u32, u32),
}
fn matching() {
let number = 13;
match number {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13...19 => println!("A teen"),
_ => println!("ain't special", ),
}
let boolean = true;
let binary = match boolean {
false => 0,
true => 1,
};
println!("{} -> {}", boolean, binary);
// destructuring tuples
let pair = (0, -2);
match pair {
(0, y) => println!("first is 0 and y is {:?}", y),
(x, 0) => println!("first is {:?} and y is 0", x),
_ => println!("it doesn't matter what they are"),
}
// enums
let color = Color::RGB(112, 17, 40);
match color {
Color::Red => println!("The Color is Red!"),
Color::Green => println!("The Color is Green!"),
Color::Blue => println!("The Color is Blue!"),
Color::RGB(r, g, b) => println!("R: {}, G: {}, B: {}", r, g, b),
}
// pointers / refs
let reference = &4;
match reference {
&val => println!("Got by destructuring: {:?}", val),
}
// to avoid the '&', dereference before matching
match *reference {
val => println!("Got by dereferencing: {:?}", val),
}
// same as &3
let ref is_a_ref = 3;
let value = 5;
let mut mut_value = 6;
// use ref keyword to create a reference
match value {
ref r => println!("got a reference to a value: {:?}", r),
}
match mut_value {
ref mut m => {
*m += 10;
println!("we added 10, mut_value is now {:?}", m);
}
}
// destructuring structs
struct Foo { x: (u32, u32), y: u32 }
let foo = Foo { x: (1, 2), y: 3 };
let Foo { x: (a, b), y } = foo;
println!("a = {}, b = {}, y = {}", a, b, y);
let Foo { y: i, x: j } = foo;
println!("i = {:?}, j = {:?}", i, j);
let Foo { y,.. } = foo;
println!("y = {}", y);
// match guards
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("These are twins"),
(x, y) if x + y == 0 => println!("animatter!"),
(x, _) if x % 2 == 1 => println!("The first one is odd.."),
_ => println!("no corelation.."),
}
match age() {
0 => println!("I'm not born yet?"),
n @ 1... 12 => println!("I'm a child of age {:?}", n),
n @ 13... 19 => println!("I'm a teen of age {:?}", n),
n => println!("I'm an old person of age {:?}", n),
}
}
fn if_let() {
let number = Some(7);
let letter: Option<i32> = None;
let emoji: Option<i32> = None;
if let Some(i) = number {
println!("Matched {:?}", i);
}
if let Some(i) = letter {
println!("Matched {:?}", i);
} else {
println!("Didn't match a number! Let's go with a letter.");
}
// altered failing condition
let i_like_letters = false;
if let Some(i) = emoji {
println!("Matched {:?}", i);
} else if i_like_letters {
println!("Didn't match a number! Let's go with a letter.");
} else {
println!("Maybe go with an emoji instead?");
}
}
fn while_let() {
let mut optional = Some(0);
while let Some(i) = optional {
if i > 9 {
println!("Greater than 9, quit!");
optional = None;
} else {
println!("i is {:?}, try again!", i);
optional = Some(i + 1);
}
}
}
fn age() -> u32 | {
15
} | identifier_body |
|
flow_control.rs | #![allow(dead_code, unreachable_code, unused_variables)]
pub fn flow_control() {
println!("***Flow Control***");
if_else();
loops();
whiles();
for_ranges();
matching();
if_let();
while_let();
println!("");
}
fn if_else() {
let n = 5;
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero!", n);
}
let big_n = if n < 10 && n > -10 {
println!(", and is small number, increase ten-fold");
10 * n
} else {
println!(", and is a big number, reduce by two");
n / 2
};
println!("{} -> {}", n, big_n);
}
fn loops() {
let mut count = 0_u32;
println!("Let's count until infinity!");
// Infinite loop
loop {
count += 1;
if count == 3 {
println!("three!");
continue;
}
println!("{}", count);
if count == 5 {
println!("that's enough!");
break;
}
}
// nesting and labels
'outer: loop {
println!("Entered the outer loop.");
'inner: loop {
println!("Entered the inner loop.");
// this would only break the inner loop
// break;
// this breaks the outer loop
break 'outer;
}
unreachable!();
}
println!("Exited the outer loop.");
}
fn whiles() {
// let mut n = 1;
// while n < 101 {
// if n % 15 == 0 {
// println!("fizzbuzz");
// } else if n % 3 == 0 {
// println!("fizz");
// } else if n % 5 == 0 {
// println!("buzz", );
// } else {
// println!("{}", n);
// }
// n += 1;
// }
}
fn for_ranges() {
// for n in 1..101 {
// if n % 15 == 0 {
// println!("fizzbuzz");
// } else if n % 3 == 0 {
// println!("fizz");
// } else if n % 5 == 0 {
// println!("buzz");
// } else {
// println!("{}", n);
// }
// }
}
enum Color {
Red,
Blue,
Green,
RGB(u32, u32, u32),
}
fn matching() {
let number = 13;
match number {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13...19 => println!("A teen"),
_ => println!("ain't special", ),
}
let boolean = true;
let binary = match boolean {
false => 0,
true => 1,
};
println!("{} -> {}", boolean, binary);
// destructuring tuples
let pair = (0, -2);
match pair {
(0, y) => println!("first is 0 and y is {:?}", y),
(x, 0) => println!("first is {:?} and y is 0", x),
_ => println!("it doesn't matter what they are"),
}
// enums
let color = Color::RGB(112, 17, 40);
match color {
Color::Red => println!("The Color is Red!"),
Color::Green => println!("The Color is Green!"),
Color::Blue => println!("The Color is Blue!"),
Color::RGB(r, g, b) => println!("R: {}, G: {}, B: {}", r, g, b),
}
// pointers / refs
let reference = &4;
match reference {
&val => println!("Got by destructuring: {:?}", val),
}
// to avoid the '&', dereference before matching
match *reference {
val => println!("Got by dereferencing: {:?}", val),
}
// same as &3
let ref is_a_ref = 3;
let value = 5;
let mut mut_value = 6;
// use ref keyword to create a reference
match value {
ref r => println!("got a reference to a value: {:?}", r),
}
match mut_value {
ref mut m => {
*m += 10;
println!("we added 10, mut_value is now {:?}", m);
}
}
// destructuring structs
struct Foo { x: (u32, u32), y: u32 }
let foo = Foo { x: (1, 2), y: 3 };
let Foo { x: (a, b), y } = foo;
println!("a = {}, b = {}, y = {}", a, b, y);
let Foo { y: i, x: j } = foo;
println!("i = {:?}, j = {:?}", i, j);
let Foo { y,.. } = foo;
println!("y = {}", y);
// match guards
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("These are twins"),
(x, y) if x + y == 0 => println!("animatter!"),
(x, _) if x % 2 == 1 => println!("The first one is odd.."),
_ => println!("no corelation.."),
}
match age() {
0 => println!("I'm not born yet?"),
n @ 1... 12 => println!("I'm a child of age {:?}", n),
n @ 13... 19 => println!("I'm a teen of age {:?}", n),
n => println!("I'm an old person of age {:?}", n),
}
}
fn if_let() {
let number = Some(7);
let letter: Option<i32> = None;
let emoji: Option<i32> = None;
if let Some(i) = number {
println!("Matched {:?}", i);
}
if let Some(i) = letter {
println!("Matched {:?}", i);
} else {
println!("Didn't match a number! Let's go with a letter.");
}
// altered failing condition
let i_like_letters = false;
if let Some(i) = emoji {
println!("Matched {:?}", i);
} else if i_like_letters {
println!("Didn't match a number! Let's go with a letter.");
} else {
println!("Maybe go with an emoji instead?");
}
}
fn while_let() {
let mut optional = Some(0);
while let Some(i) = optional {
if i > 9 {
println!("Greater than 9, quit!");
optional = None;
} else {
println!("i is {:?}, try again!", i);
optional = Some(i + 1);
}
}
}
fn | () -> u32 {
15
}
| age | identifier_name |
context.rs | //! Provides a Rust wrapper around Cuda's context.
use device::{IDevice, DeviceType, IDeviceSyncOut};
use device::Error as DeviceError;
use super::api::DriverFFI;
use super::{Driver, DriverError, Device};
use super::memory::*;
#[cfg(feature = "native")]
use frameworks::native::flatbox::FlatBox;
use memory::MemoryType;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
#[derive(Debug, Clone)]
/// Defines a Cuda Context.
pub struct Context {
id: Rc<isize>,
devices: Vec<Device>,
}
impl Drop for Context {
#[allow(unused_must_use)]
fn drop(&mut self) {
let id_c = self.id_c().clone();
if let Some(_) = Rc::get_mut(&mut self.id) {
Driver::destroy_context(id_c);
}
}
}
impl Context {
/// Initializes a new Cuda context.
pub fn new(devices: Device) -> Result<Context, DriverError> {
Ok(
Context::from_c(
try!(Driver::create_context(devices.clone())),
vec!(devices.clone())
)
)
} | id: Rc::new(id as isize),
devices: devices
}
}
/// Returns the id as isize.
pub fn id(&self) -> isize {
*self.id
}
/// Returns the id as its C type.
pub fn id_c(&self) -> DriverFFI::CUcontext {
*self.id as DriverFFI::CUcontext
}
/// Synchronize this Context.
pub fn synchronize(&self) -> Result<(), DriverError> {
Driver::synchronize_context()
}
}
#[cfg(feature = "native")]
impl IDeviceSyncOut<FlatBox> for Context {
type M = Memory;
fn sync_out(&self, source_data: &Memory, dest_data: &mut FlatBox) -> Result<(), DeviceError> {
Ok(try!(Driver::mem_cpy_d_to_h(source_data, dest_data)))
}
}
impl IDevice for Context {
type H = Device;
type M = Memory;
fn id(&self) -> &isize {
&self.id
}
fn hardwares(&self) -> &Vec<Device> {
&self.devices
}
fn alloc_memory(&self, size: DriverFFI::size_t) -> Result<Memory, DeviceError> {
Ok(try!(Driver::mem_alloc(size)))
}
fn sync_in(&self, source: &DeviceType, source_data: &MemoryType, dest_data: &mut Memory) -> Result<(), DeviceError> {
match source {
#[cfg(feature = "native")]
&DeviceType::Native(_) => {
match source_data.as_native() {
Some(h_mem) => Ok(try!(Driver::mem_cpy_h_to_d(h_mem, dest_data))),
None => unimplemented!()
}
},
_ => unimplemented!()
}
}
}
impl PartialEq for Context {
fn eq(&self, other: &Self) -> bool {
self.hardwares() == other.hardwares()
}
}
impl Eq for Context {}
impl Hash for Context {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
} |
/// Initializes a new Cuda platform from its C type.
pub fn from_c(id: DriverFFI::CUcontext, devices: Vec<Device>) -> Context {
Context { | random_line_split |
context.rs | //! Provides a Rust wrapper around Cuda's context.
use device::{IDevice, DeviceType, IDeviceSyncOut};
use device::Error as DeviceError;
use super::api::DriverFFI;
use super::{Driver, DriverError, Device};
use super::memory::*;
#[cfg(feature = "native")]
use frameworks::native::flatbox::FlatBox;
use memory::MemoryType;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
#[derive(Debug, Clone)]
/// Defines a Cuda Context.
pub struct Context {
id: Rc<isize>,
devices: Vec<Device>,
}
impl Drop for Context {
#[allow(unused_must_use)]
fn drop(&mut self) {
let id_c = self.id_c().clone();
if let Some(_) = Rc::get_mut(&mut self.id) {
Driver::destroy_context(id_c);
}
}
}
impl Context {
/// Initializes a new Cuda context.
pub fn | (devices: Device) -> Result<Context, DriverError> {
Ok(
Context::from_c(
try!(Driver::create_context(devices.clone())),
vec!(devices.clone())
)
)
}
/// Initializes a new Cuda platform from its C type.
pub fn from_c(id: DriverFFI::CUcontext, devices: Vec<Device>) -> Context {
Context {
id: Rc::new(id as isize),
devices: devices
}
}
/// Returns the id as isize.
pub fn id(&self) -> isize {
*self.id
}
/// Returns the id as its C type.
pub fn id_c(&self) -> DriverFFI::CUcontext {
*self.id as DriverFFI::CUcontext
}
/// Synchronize this Context.
pub fn synchronize(&self) -> Result<(), DriverError> {
Driver::synchronize_context()
}
}
#[cfg(feature = "native")]
impl IDeviceSyncOut<FlatBox> for Context {
type M = Memory;
fn sync_out(&self, source_data: &Memory, dest_data: &mut FlatBox) -> Result<(), DeviceError> {
Ok(try!(Driver::mem_cpy_d_to_h(source_data, dest_data)))
}
}
impl IDevice for Context {
type H = Device;
type M = Memory;
fn id(&self) -> &isize {
&self.id
}
fn hardwares(&self) -> &Vec<Device> {
&self.devices
}
fn alloc_memory(&self, size: DriverFFI::size_t) -> Result<Memory, DeviceError> {
Ok(try!(Driver::mem_alloc(size)))
}
fn sync_in(&self, source: &DeviceType, source_data: &MemoryType, dest_data: &mut Memory) -> Result<(), DeviceError> {
match source {
#[cfg(feature = "native")]
&DeviceType::Native(_) => {
match source_data.as_native() {
Some(h_mem) => Ok(try!(Driver::mem_cpy_h_to_d(h_mem, dest_data))),
None => unimplemented!()
}
},
_ => unimplemented!()
}
}
}
impl PartialEq for Context {
fn eq(&self, other: &Self) -> bool {
self.hardwares() == other.hardwares()
}
}
impl Eq for Context {}
impl Hash for Context {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
}
| new | identifier_name |
context.rs | //! Provides a Rust wrapper around Cuda's context.
use device::{IDevice, DeviceType, IDeviceSyncOut};
use device::Error as DeviceError;
use super::api::DriverFFI;
use super::{Driver, DriverError, Device};
use super::memory::*;
#[cfg(feature = "native")]
use frameworks::native::flatbox::FlatBox;
use memory::MemoryType;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
#[derive(Debug, Clone)]
/// Defines a Cuda Context.
pub struct Context {
id: Rc<isize>,
devices: Vec<Device>,
}
impl Drop for Context {
#[allow(unused_must_use)]
fn drop(&mut self) {
let id_c = self.id_c().clone();
if let Some(_) = Rc::get_mut(&mut self.id) {
Driver::destroy_context(id_c);
}
}
}
impl Context {
/// Initializes a new Cuda context.
pub fn new(devices: Device) -> Result<Context, DriverError> {
Ok(
Context::from_c(
try!(Driver::create_context(devices.clone())),
vec!(devices.clone())
)
)
}
/// Initializes a new Cuda platform from its C type.
pub fn from_c(id: DriverFFI::CUcontext, devices: Vec<Device>) -> Context {
Context {
id: Rc::new(id as isize),
devices: devices
}
}
/// Returns the id as isize.
pub fn id(&self) -> isize {
*self.id
}
/// Returns the id as its C type.
pub fn id_c(&self) -> DriverFFI::CUcontext |
/// Synchronize this Context.
pub fn synchronize(&self) -> Result<(), DriverError> {
Driver::synchronize_context()
}
}
#[cfg(feature = "native")]
impl IDeviceSyncOut<FlatBox> for Context {
type M = Memory;
fn sync_out(&self, source_data: &Memory, dest_data: &mut FlatBox) -> Result<(), DeviceError> {
Ok(try!(Driver::mem_cpy_d_to_h(source_data, dest_data)))
}
}
impl IDevice for Context {
type H = Device;
type M = Memory;
fn id(&self) -> &isize {
&self.id
}
fn hardwares(&self) -> &Vec<Device> {
&self.devices
}
fn alloc_memory(&self, size: DriverFFI::size_t) -> Result<Memory, DeviceError> {
Ok(try!(Driver::mem_alloc(size)))
}
fn sync_in(&self, source: &DeviceType, source_data: &MemoryType, dest_data: &mut Memory) -> Result<(), DeviceError> {
match source {
#[cfg(feature = "native")]
&DeviceType::Native(_) => {
match source_data.as_native() {
Some(h_mem) => Ok(try!(Driver::mem_cpy_h_to_d(h_mem, dest_data))),
None => unimplemented!()
}
},
_ => unimplemented!()
}
}
}
impl PartialEq for Context {
fn eq(&self, other: &Self) -> bool {
self.hardwares() == other.hardwares()
}
}
impl Eq for Context {}
impl Hash for Context {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id().hash(state);
}
}
| {
*self.id as DriverFFI::CUcontext
} | identifier_body |
macros.rs | //macro_rules! batch {
//($name : ident, [ $($parts: ident : $pty: ty),* ], [$($defid : ident : $val : expr),*]) => {
//impl<T, V> $name<T, V>
//where T: EndOffset,
//V:Batch + BatchIterator + Act {
//#[inline]
//pub fn new($( $parts : $pty ),*) -> $name<T, V> {
//$name{ $( $parts: $parts ),*, $($defid : $val),* }
//}
//}
//batch_no_new!{$name}
//};
//($name: ident, [ $($parts: ident : $pty: ty),* ]) => {
//batch!{$name, [$($parts:$pty),*], []}
//}
//}
macro_rules! batch_no_new {
($name : ident) => {
impl<T, V> Batch for $name<T, V>
where T: EndOffset,
V:Batch + BatchIterator<Header=T> + Act {
} | batch!{$name, [$($parts:$pty),*], []}
}
}
macro_rules! act {
() => {
#[inline]
fn act(&mut self) {
self.parent.act();
}
#[inline]
fn done(&mut self) {
self.parent.done();
}
#[inline]
fn send_q(&mut self, port: &PacketTx) -> Result<u32> {
self.parent.send_q(port)
}
#[inline]
fn capacity(&self) -> i32 {
self.parent.capacity()
}
#[inline]
fn drop_packets(&mut self, idxes: &[usize]) -> Option<usize> {
self.parent.drop_packets(idxes)
}
#[inline]
fn clear_packets(&mut self) {
self.parent.clear_packets()
}
#[inline]
fn get_packet_batch(&mut self) -> &mut PacketBatch {
self.parent.get_packet_batch()
}
#[inline]
fn get_task_dependencies(&self) -> Vec<usize> {
self.parent.get_task_dependencies()
}
}
} | };
($name: ident, [ $($parts: ident : $pty: ty),* ]) => { | random_line_split |
unify.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use syntax::ast;
use util::ppaux::Repr;
use util::snapshot_vec as sv;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `IntVid`, which represents integral
* variables.
*
* Each key type has an associated value type `V`. For example, for
* `IntVid`, this is `Option<IntVarValue>`, representing some
* (possibly not yet known) sort of integer.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note that
* this is typically not the end type that the value will take on, but
* rather an `Option` wrapper (where `None` represents a variable
* whose value is not yet set).
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: sv::SnapshotVec<VarValue<K,V>,(),Delegate>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *committed* or *rolled back*.
*/
pub struct Snapshot<K> {
// Link snapshot to the key type `K` of the table.
marker: marker::CovariantType<K>,
snapshot: sv::Snapshot,
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
pub struct Delegate;
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Option<U> for some
// other type parameter U, and we have no way to say
// Option<U>:LatticeValue.
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: sv::SnapshotVec::new(Delegate),
}
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or committed in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
Snapshot { marker: marker::CovariantType::<K>,
snapshot: self.values.start_snapshot() }
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, snapshot: Snapshot<K>) {
debug!("{}: rollback_to()", UnifyKey::tag(None::<K>));
self.values.rollback_to(snapshot.snapshot);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit()", UnifyKey::tag(None::<K>));
self.values.commit(snapshot.snapshot);
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
self.values.set(index, Redirect(node.key.clone()));
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
self.values.set(key.index(), new_value);
}
pub fn unify(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
impl<K,V> sv::SnapshotVecDelegate<VarValue<K,V>,()> for Delegate {
fn reverse(&mut self, _: &mut Vec<VarValue<K,V>>, _: ()) {
fail!("Nothing to reverse");
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool,
a_t: V,
b_t: V)
-> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) => {
Some((*v).clone())
}
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
| if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
impl<K:Repr,V:Repr> Repr for VarValue<K,V> {
fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
Redirect(ref k) => format!("Redirect({})", k.repr(tcx)),
Root(ref v, r) => format!("Root({}, {})", v.repr(tcx), r)
}
}
}
| {
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => { | identifier_body |
unify.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use syntax::ast;
use util::ppaux::Repr;
use util::snapshot_vec as sv;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `IntVid`, which represents integral
* variables.
*
* Each key type has an associated value type `V`. For example, for
* `IntVid`, this is `Option<IntVarValue>`, representing some
* (possibly not yet known) sort of integer.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note that
* this is typically not the end type that the value will take on, but
* rather an `Option` wrapper (where `None` represents a variable
* whose value is not yet set).
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: sv::SnapshotVec<VarValue<K,V>,(),Delegate>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *committed* or *rolled back*.
*/
pub struct Snapshot<K> {
// Link snapshot to the key type `K` of the table.
marker: marker::CovariantType<K>,
snapshot: sv::Snapshot,
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
pub struct Delegate;
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Option<U> for some
// other type parameter U, and we have no way to say
// Option<U>:LatticeValue.
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: sv::SnapshotVec::new(Delegate),
}
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or committed in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
Snapshot { marker: marker::CovariantType::<K>,
snapshot: self.values.start_snapshot() }
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, snapshot: Snapshot<K>) {
debug!("{}: rollback_to()", UnifyKey::tag(None::<K>));
self.values.rollback_to(snapshot.snapshot);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit()", UnifyKey::tag(None::<K>));
self.values.commit(snapshot.snapshot);
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
self.values.set(index, Redirect(node.key.clone()));
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
self.values.set(key.index(), new_value);
}
pub fn unify(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
impl<K,V> sv::SnapshotVecDelegate<VarValue<K,V>,()> for Delegate {
fn reverse(&mut self, _: &mut Vec<VarValue<K,V>>, _: ()) {
fail!("Nothing to reverse");
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool,
a_t: V,
b_t: V)
-> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) => {
Some((*v).clone())
}
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
{
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => {
if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn | (i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
impl<K:Repr,V:Repr> Repr for VarValue<K,V> {
fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
Redirect(ref k) => format!("Redirect({})", k.repr(tcx)),
Root(ref v, r) => format!("Root({}, {})", v.repr(tcx), r)
}
}
}
| from_index | identifier_name |
unify.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::kinds::marker;
use middle::ty::{expected_found, IntVarValue};
use middle::ty;
use middle::typeck::infer::{uok, ures};
use middle::typeck::infer::InferCtxt;
use std::cell::RefCell;
use std::fmt::Show;
use syntax::ast;
use util::ppaux::Repr;
use util::snapshot_vec as sv;
/**
* This trait is implemented by any type that can serve as a type
* variable. We call such variables *unification keys*. For example,
* this trait is implemented by `IntVid`, which represents integral
* variables.
*
* Each key type has an associated value type `V`. For example, for
* `IntVid`, this is `Option<IntVarValue>`, representing some
* (possibly not yet known) sort of integer.
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyKey<V> : Clone + Show + PartialEq + Repr {
fn index(&self) -> uint;
fn from_index(u: uint) -> Self;
/**
* Given an inference context, returns the unification table
* appropriate to this key type.
*/
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<Self,V>>;
fn tag(k: Option<Self>) -> &'static str;
}
/**
* Trait for valid types that a type variable can be set to. Note that
* this is typically not the end type that the value will take on, but
* rather an `Option` wrapper (where `None` represents a variable
* whose value is not yet set).
*
* Implementations of this trait are at the end of this file.
*/
pub trait UnifyValue : Clone + Repr + PartialEq {
}
/**
* Value of a unification key. We implement Tarjan's union-find
* algorithm: when two keys are unified, one of them is converted
* into a "redirect" pointing at the other. These redirects form a
* DAG: the roots of the DAG (nodes that are not redirected) are each
* associated with a value of type `V` and a rank. The rank is used
* to keep the DAG relatively balanced, which helps keep the running
* time of the algorithm under control. For more information, see
* <http://en.wikipedia.org/wiki/Disjoint-set_data_structure>.
*/
#[deriving(PartialEq,Clone)]
pub enum VarValue<K,V> {
Redirect(K),
Root(V, uint),
}
/**
* Table of unification keys and their values.
*/
pub struct UnificationTable<K,V> {
/**
* Indicates the current value of each key.
*/
values: sv::SnapshotVec<VarValue<K,V>,(),Delegate>,
}
/**
* At any time, users may snapshot a unification table. The changes
* made during the snapshot may either be *committed* or *rolled back*.
*/
pub struct Snapshot<K> {
// Link snapshot to the key type `K` of the table.
marker: marker::CovariantType<K>,
snapshot: sv::Snapshot,
}
/**
* Internal type used to represent the result of a `get()` operation.
* Conveys the current root and value of the key.
*/
pub struct Node<K,V> {
pub key: K,
pub value: V,
pub rank: uint,
}
pub struct Delegate;
// We can't use V:LatticeValue, much as I would like to,
// because frequently the pattern is that V=Option<U> for some
// other type parameter U, and we have no way to say
// Option<U>:LatticeValue.
impl<V:PartialEq+Clone+Repr,K:UnifyKey<V>> UnificationTable<K,V> {
pub fn new() -> UnificationTable<K,V> {
UnificationTable {
values: sv::SnapshotVec::new(Delegate),
}
}
/**
* Starts a new snapshot. Each snapshot must be either
* rolled back or committed in a "LIFO" (stack) order.
*/
pub fn snapshot(&mut self) -> Snapshot<K> {
Snapshot { marker: marker::CovariantType::<K>,
snapshot: self.values.start_snapshot() }
}
/**
* Reverses all changes since the last snapshot. Also
* removes any keys that have been created since then.
*/
pub fn rollback_to(&mut self, snapshot: Snapshot<K>) {
debug!("{}: rollback_to()", UnifyKey::tag(None::<K>));
self.values.rollback_to(snapshot.snapshot);
}
/**
* Commits all changes since the last snapshot. Of course, they
* can still be undone if there is a snapshot further out.
*/
pub fn commit(&mut self, snapshot: Snapshot<K>) {
debug!("{}: commit()", UnifyKey::tag(None::<K>));
self.values.commit(snapshot.snapshot);
}
pub fn new_key(&mut self, value: V) -> K {
let index = self.values.push(Root(value, 0));
let k = UnifyKey::from_index(index);
debug!("{}: created new key: {}",
UnifyKey::tag(None::<K>),
k);
k
}
pub fn get(&mut self, tcx: &ty::ctxt, vid: K) -> Node<K,V> {
/*!
* Find the root node for `vid`. This uses the standard
* union-find algorithm with path compression:
* http://en.wikipedia.org/wiki/Disjoint-set_data_structure
*/
let index = vid.index();
let value = (*self.values.get(index)).clone();
match value {
Redirect(redirect) => {
let node: Node<K,V> = self.get(tcx, redirect.clone());
if node.key!= redirect {
// Path compression
self.values.set(index, Redirect(node.key.clone()));
}
node
}
Root(value, rank) => {
Node { key: vid, value: value, rank: rank }
}
}
}
fn is_root(&self, key: &K) -> bool {
match *self.values.get(key.index()) {
Redirect(..) => false,
Root(..) => true,
}
}
pub fn set(&mut self,
tcx: &ty::ctxt,
key: K,
new_value: VarValue<K,V>)
{
/*!
* Sets the value for `vid` to `new_value`. `vid` MUST be a
* root node! Also, we must be in the middle of a snapshot.
*/
assert!(self.is_root(&key));
debug!("Updating variable {} to {}",
key.repr(tcx),
new_value.repr(tcx));
self.values.set(key.index(), new_value);
}
pub fn unify(&mut self,
tcx: &ty::ctxt,
node_a: &Node<K,V>,
node_b: &Node<K,V>)
-> (K, uint)
{
/*!
* Either redirects node_a to node_b or vice versa, depending
* on the relative rank. Returns the new root and rank. You
* should then update the value of the new root to something
* suitable.
*/
debug!("unify(node_a(id={}, rank={}), node_b(id={}, rank={}))",
node_a.key.repr(tcx),
node_a.rank,
node_b.key.repr(tcx),
node_b.rank);
if node_a.rank > node_b.rank {
// a has greater rank, so a should become b's parent,
// i.e., b should redirect to a.
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank)
} else if node_a.rank < node_b.rank {
// b has greater rank, so a should redirect to b.
self.set(tcx, node_a.key.clone(), Redirect(node_b.key.clone()));
(node_b.key.clone(), node_b.rank)
} else {
// If equal, redirect one to the other and increment the
// other's rank.
assert_eq!(node_a.rank, node_b.rank);
self.set(tcx, node_b.key.clone(), Redirect(node_a.key.clone()));
(node_a.key.clone(), node_a.rank + 1)
}
}
}
impl<K,V> sv::SnapshotVecDelegate<VarValue<K,V>,()> for Delegate {
fn reverse(&mut self, _: &mut Vec<VarValue<K,V>>, _: ()) {
fail!("Nothing to reverse");
}
}
///////////////////////////////////////////////////////////////////////////
// Code to handle simple keys like ints, floats---anything that
// doesn't have a subtyping relationship we need to worry about.
/**
* Indicates a type that does not have any kind of subtyping
* relationship.
*/
pub trait SimplyUnifiable : Clone + PartialEq + Repr {
fn to_type_err(expected_found<Self>) -> ty::type_err;
}
pub fn err<V:SimplyUnifiable>(a_is_expected: bool, | b_t: V)
-> ures {
if a_is_expected {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: a_t, found: b_t}))
} else {
Err(SimplyUnifiable::to_type_err(
ty::expected_found {expected: b_t, found: a_t}))
}
}
pub trait InferCtxtMethodsForSimplyUnifiableTypes<V:SimplyUnifiable,
K:UnifyKey<Option<V>>> {
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures;
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures;
}
impl<'tcx,V:SimplyUnifiable,K:UnifyKey<Option<V>>>
InferCtxtMethodsForSimplyUnifiableTypes<V,K> for InferCtxt<'tcx>
{
fn simple_vars(&self,
a_is_expected: bool,
a_id: K,
b_id: K)
-> ures
{
/*!
* Unifies two simple keys. Because simple keys do
* not have any subtyping relationships, if both keys
* have already been associated with a value, then those two
* values must be the same.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let node_b = table.borrow_mut().get(tcx, b_id);
let a_id = node_a.key.clone();
let b_id = node_b.key.clone();
if a_id == b_id { return uok(); }
let combined = {
match (&node_a.value, &node_b.value) {
(&None, &None) => {
None
}
(&Some(ref v), &None) | (&None, &Some(ref v)) => {
Some((*v).clone())
}
(&Some(ref v1), &Some(ref v2)) => {
if *v1!= *v2 {
return err(a_is_expected, (*v1).clone(), (*v2).clone())
}
Some((*v1).clone())
}
}
};
let (new_root, new_rank) = table.borrow_mut().unify(tcx,
&node_a,
&node_b);
table.borrow_mut().set(tcx, new_root, Root(combined, new_rank));
return Ok(())
}
fn simple_var_t(&self,
a_is_expected: bool,
a_id: K,
b: V)
-> ures
{
/*!
* Sets the value of the key `a_id` to `b`. Because
* simple keys do not have any subtyping relationships,
* if `a_id` already has a value, it must be the same as
* `b`.
*/
let tcx = self.tcx;
let table = UnifyKey::unification_table(self);
let node_a = table.borrow_mut().get(tcx, a_id);
let a_id = node_a.key.clone();
match node_a.value {
None => {
table.borrow_mut().set(tcx, a_id, Root(Some(b), node_a.rank));
return Ok(());
}
Some(ref a_t) => {
if *a_t == b {
return Ok(());
} else {
return err(a_is_expected, (*a_t).clone(), b);
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Integral type keys
impl UnifyKey<Option<IntVarValue>> for ty::IntVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::IntVid { ty::IntVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::IntVid, Option<IntVarValue>>>
{
return &infcx.int_unification_table;
}
fn tag(_: Option<ty::IntVid>) -> &'static str {
"IntVid"
}
}
impl SimplyUnifiable for IntVarValue {
fn to_type_err(err: expected_found<IntVarValue>) -> ty::type_err {
return ty::terr_int_mismatch(err);
}
}
impl UnifyValue for Option<IntVarValue> { }
// Floating point type keys
impl UnifyKey<Option<ast::FloatTy>> for ty::FloatVid {
fn index(&self) -> uint { self.index }
fn from_index(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } }
fn unification_table<'v>(infcx: &'v InferCtxt)
-> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>>
{
return &infcx.float_unification_table;
}
fn tag(_: Option<ty::FloatVid>) -> &'static str {
"FloatVid"
}
}
impl UnifyValue for Option<ast::FloatTy> {
}
impl SimplyUnifiable for ast::FloatTy {
fn to_type_err(err: expected_found<ast::FloatTy>) -> ty::type_err {
return ty::terr_float_mismatch(err);
}
}
impl<K:Repr,V:Repr> Repr for VarValue<K,V> {
fn repr(&self, tcx: &ty::ctxt) -> String {
match *self {
Redirect(ref k) => format!("Redirect({})", k.repr(tcx)),
Root(ref v, r) => format!("Root({}, {})", v.repr(tcx), r)
}
}
} | a_t: V, | random_line_split |
borrowck-loan-blocks-move-cc.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
use std::thread::Thread;
fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) {
f(v);
}
fn box_imm() {
let v = box 3;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move `v` into closure
});
}
fn box_imm_explicit() {
let v = box 3;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move
});
}
fn | () {
}
| main | identifier_name |
borrowck-loan-blocks-move-cc.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
use std::thread::Thread;
fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) {
f(v);
}
fn box_imm() {
let v = box 3;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move `v` into closure
});
}
fn box_imm_explicit() {
let v = box 3;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move
});
}
fn main() | {
} | identifier_body |
|
borrowck-loan-blocks-move-cc.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 |
use std::thread::Thread;
fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) {
f(v);
}
fn box_imm() {
let v = box 3;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move `v` into closure
});
}
fn box_imm_explicit() {
let v = box 3;
let _w = &v;
Thread::spawn(move|| {
println!("v={}", *v);
//~^ ERROR cannot move
});
}
fn main() {
} | // <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(box_syntax)] | random_line_split |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate jni;
use jni::*;
#[test]
fn test() {
assert!(!mytest().is_err());
}
fn | () -> Result<(),jni::Exception> {
let opt1 = JavaVMOption::new("-Xcheck:jni");
println!("Opt is {:?}", opt1);
let opt2 = JavaVMOption::new("-verbose:jni");
println!("Opt is {:?}", opt2);
let args = JavaVMInitArgs::new(
jni::JniVersion::JNI_VERSION_1_4,
&[/*opt1, JavaVMOption::new("-verbose:jni")*/][..],
false,
);
println!("Args are {:?}", args);
let jvm = JavaVM::new(args).unwrap();
println!("Jvm is {:?}", jvm);
let (env, cap) = jvm.get_env().unwrap();
println!("Env is {:?}", env);
println!("Env version is {:?}", env.version(&cap));
let (cls, cap) = match JavaClass::find(&env, "java/lang/String", cap) {
Ok(a) => a,
_ => panic!("unexpected exception")
};
let proto = "Hello, world!";
let (st, cap) = match JavaString::new(&env, proto, cap) {
Ok(a) => a,
_ => panic!("unexpected exception")
};
println!("St is {:?}", st.to_str(&cap).unwrap());
// assert_eq!(st.to_str(&cap), proto);
println!("St len is {:?} == {:?}", st.to_str(&cap).unwrap().len(), proto.len());
let class = st.get_class(&cap);
let class2 = st.get_class(&cap);
println!(
"Clses are {:?}, {:?}, {:?}, {:?}", cls, class,
cls == class2,
st.is_instance_of(&cls, &cap)
);
println!("st[2:7] == {:?}", st.region(2, 5, cap));
let cap = JavaThrowable::check(&env).unwrap();
let (gst, cap) = try!(st.global(cap));
let (wgst, cap) = try!(gst.weak(cap));
let (wst, cap) = try!(st.weak(cap));
println!("Wst is null: {:?}", wst.is_null(&cap));
println!("{:?} {:?} {:?} {:?} {:?}", st, gst, wgst, wst, wgst);
println!("Wst is null: {:?}", wst.is_null(&cap));
Ok(())
}
/*
use ::std::marker::PhantomData;
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare(&'a self, l: &Obj<'a>, r: &Obj<'a>) -> bool {
l.val == r.val
}
pub fn obj(&'a self, v: u64) -> Obj<'a> {
Obj {
val: v,
child: self,
}
}
}
struct Obj<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a> PartialEq<Obj<'a>> for Obj<'a> {
fn eq(&self, other: &Obj<'a>) -> bool {
self.child.compare(self, other)
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj(3);
let obj2 = child.obj(3);
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj(3);
let obj22 = child2.obj(3);
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// assert!(obj1 == obj12);
assert!(obj12 == obj1);
}
*/
/*
use ::std::marker::PhantomData;
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare<'b, L: 'a + Obj<'a>, R: 'a + Obj<'b>>(&'a self, l: &L, r: &R) -> bool {
l.get_val() == r.get_val()
}
pub fn obj1(&'a self, v: u64) -> Obj1<'a> {
Obj1 {
val: v,
child: self,
}
}
pub fn obj2(&'a self, v: u64) -> Obj2<'a> {
Obj2 {
val: v,
child: self,
}
}
}
trait Obj<'a> {
fn get_child(&'a self) -> &'a Child<'a>;
fn get_val(&self) -> u64;
}
struct Obj1<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a, R: 'a + Obj<'a>> PartialEq<R> for Obj1<'a> {
fn eq(&self, other: &R) -> bool {
self.get_child().compare(self, other)
}
}
impl<'a> Obj<'a> for Obj1<'a> {
fn get_child(&'a self) -> &'a Child<'a> {
self.child
}
fn get_val(&self) -> u64 {
self.val
}
}
struct Obj2<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a, R: 'a + Obj<'a>> PartialEq<R> for Obj2<'a> {
fn eq(&self, other: &R) -> bool {
self.get_child().compare(self, other)
}
}
impl<'a> Obj<'a> for Obj2<'a> {
fn get_child(&'a self) -> &'a Child<'a> {
self.child
}
fn get_val(&self) -> u64 {
self.val
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj1(3);
let obj2 = child.obj2(3);
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj1(3);
let obj22 = child2.obj2(3);
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// assert!(obj1 == obj12);
assert!(obj12 == obj1);
}
*/
| mytest | identifier_name |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate jni;
use jni::*;
#[test]
fn test() {
assert!(!mytest().is_err());
}
fn mytest() -> Result<(),jni::Exception> {
let opt1 = JavaVMOption::new("-Xcheck:jni");
println!("Opt is {:?}", opt1);
let opt2 = JavaVMOption::new("-verbose:jni");
println!("Opt is {:?}", opt2);
let args = JavaVMInitArgs::new(
jni::JniVersion::JNI_VERSION_1_4,
&[/*opt1, JavaVMOption::new("-verbose:jni")*/][..],
false,
);
println!("Args are {:?}", args);
let jvm = JavaVM::new(args).unwrap();
println!("Jvm is {:?}", jvm);
let (env, cap) = jvm.get_env().unwrap();
println!("Env is {:?}", env);
println!("Env version is {:?}", env.version(&cap));
let (cls, cap) = match JavaClass::find(&env, "java/lang/String", cap) {
Ok(a) => a,
_ => panic!("unexpected exception")
};
let proto = "Hello, world!";
let (st, cap) = match JavaString::new(&env, proto, cap) {
Ok(a) => a,
_ => panic!("unexpected exception")
};
println!("St is {:?}", st.to_str(&cap).unwrap());
// assert_eq!(st.to_str(&cap), proto);
println!("St len is {:?} == {:?}", st.to_str(&cap).unwrap().len(), proto.len());
let class = st.get_class(&cap);
let class2 = st.get_class(&cap);
println!(
"Clses are {:?}, {:?}, {:?}, {:?}", cls, class,
cls == class2,
st.is_instance_of(&cls, &cap)
);
println!("st[2:7] == {:?}", st.region(2, 5, cap));
let cap = JavaThrowable::check(&env).unwrap();
let (gst, cap) = try!(st.global(cap));
let (wgst, cap) = try!(gst.weak(cap));
let (wst, cap) = try!(st.weak(cap));
println!("Wst is null: {:?}", wst.is_null(&cap));
println!("{:?} {:?} {:?} {:?} {:?}", st, gst, wgst, wst, wgst);
println!("Wst is null: {:?}", wst.is_null(&cap));
Ok(())
}
/*
use ::std::marker::PhantomData;
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare(&'a self, l: &Obj<'a>, r: &Obj<'a>) -> bool {
l.val == r.val
}
pub fn obj(&'a self, v: u64) -> Obj<'a> {
Obj {
val: v,
child: self,
}
}
}
struct Obj<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a> PartialEq<Obj<'a>> for Obj<'a> {
fn eq(&self, other: &Obj<'a>) -> bool {
self.child.compare(self, other)
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj(3);
let obj2 = child.obj(3);
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj(3);
let obj22 = child2.obj(3);
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// assert!(obj1 == obj12);
assert!(obj12 == obj1);
}
*/
/*
use ::std::marker::PhantomData;
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare<'b, L: 'a + Obj<'a>, R: 'a + Obj<'b>>(&'a self, l: &L, r: &R) -> bool {
l.get_val() == r.get_val()
}
pub fn obj1(&'a self, v: u64) -> Obj1<'a> {
Obj1 {
val: v,
child: self,
}
}
pub fn obj2(&'a self, v: u64) -> Obj2<'a> {
Obj2 {
val: v,
child: self,
}
}
}
trait Obj<'a> {
fn get_child(&'a self) -> &'a Child<'a>;
fn get_val(&self) -> u64;
}
struct Obj1<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a, R: 'a + Obj<'a>> PartialEq<R> for Obj1<'a> {
fn eq(&self, other: &R) -> bool {
self.get_child().compare(self, other)
}
}
impl<'a> Obj<'a> for Obj1<'a> {
fn get_child(&'a self) -> &'a Child<'a> {
self.child
}
fn get_val(&self) -> u64 {
self.val
}
}
struct Obj2<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a, R: 'a + Obj<'a>> PartialEq<R> for Obj2<'a> {
fn eq(&self, other: &R) -> bool {
self.get_child().compare(self, other)
}
}
impl<'a> Obj<'a> for Obj2<'a> {
fn get_child(&'a self) -> &'a Child<'a> {
self.child |
fn get_val(&self) -> u64 {
self.val
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj1(3);
let obj2 = child.obj2(3);
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj1(3);
let obj22 = child2.obj2(3);
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// assert!(obj1 == obj12);
assert!(obj12 == obj1);
}
*/ | } | random_line_split |
main.rs | #![allow(dead_code)]
extern crate libc;
extern crate jni;
use jni::*;
#[test]
fn test() |
fn mytest() -> Result<(),jni::Exception> {
let opt1 = JavaVMOption::new("-Xcheck:jni");
println!("Opt is {:?}", opt1);
let opt2 = JavaVMOption::new("-verbose:jni");
println!("Opt is {:?}", opt2);
let args = JavaVMInitArgs::new(
jni::JniVersion::JNI_VERSION_1_4,
&[/*opt1, JavaVMOption::new("-verbose:jni")*/][..],
false,
);
println!("Args are {:?}", args);
let jvm = JavaVM::new(args).unwrap();
println!("Jvm is {:?}", jvm);
let (env, cap) = jvm.get_env().unwrap();
println!("Env is {:?}", env);
println!("Env version is {:?}", env.version(&cap));
let (cls, cap) = match JavaClass::find(&env, "java/lang/String", cap) {
Ok(a) => a,
_ => panic!("unexpected exception")
};
let proto = "Hello, world!";
let (st, cap) = match JavaString::new(&env, proto, cap) {
Ok(a) => a,
_ => panic!("unexpected exception")
};
println!("St is {:?}", st.to_str(&cap).unwrap());
// assert_eq!(st.to_str(&cap), proto);
println!("St len is {:?} == {:?}", st.to_str(&cap).unwrap().len(), proto.len());
let class = st.get_class(&cap);
let class2 = st.get_class(&cap);
println!(
"Clses are {:?}, {:?}, {:?}, {:?}", cls, class,
cls == class2,
st.is_instance_of(&cls, &cap)
);
println!("st[2:7] == {:?}", st.region(2, 5, cap));
let cap = JavaThrowable::check(&env).unwrap();
let (gst, cap) = try!(st.global(cap));
let (wgst, cap) = try!(gst.weak(cap));
let (wst, cap) = try!(st.weak(cap));
println!("Wst is null: {:?}", wst.is_null(&cap));
println!("{:?} {:?} {:?} {:?} {:?}", st, gst, wgst, wst, wgst);
println!("Wst is null: {:?}", wst.is_null(&cap));
Ok(())
}
/*
use ::std::marker::PhantomData;
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare(&'a self, l: &Obj<'a>, r: &Obj<'a>) -> bool {
l.val == r.val
}
pub fn obj(&'a self, v: u64) -> Obj<'a> {
Obj {
val: v,
child: self,
}
}
}
struct Obj<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a> PartialEq<Obj<'a>> for Obj<'a> {
fn eq(&self, other: &Obj<'a>) -> bool {
self.child.compare(self, other)
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj(3);
let obj2 = child.obj(3);
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj(3);
let obj22 = child2.obj(3);
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// assert!(obj1 == obj12);
assert!(obj12 == obj1);
}
*/
/*
use ::std::marker::PhantomData;
struct Parent {
val: u64,
}
impl Parent {
pub fn new(v: u64) -> Parent {
Parent { val: v }
}
pub fn child(&self, v: u64) -> Child {
Child {
val: v,
phantom: PhantomData,
}
}
}
struct Child<'a> {
val: u64,
phantom: PhantomData<&'a Parent>,
}
impl<'a> Child<'a> {
pub fn compare<'b, L: 'a + Obj<'a>, R: 'a + Obj<'b>>(&'a self, l: &L, r: &R) -> bool {
l.get_val() == r.get_val()
}
pub fn obj1(&'a self, v: u64) -> Obj1<'a> {
Obj1 {
val: v,
child: self,
}
}
pub fn obj2(&'a self, v: u64) -> Obj2<'a> {
Obj2 {
val: v,
child: self,
}
}
}
trait Obj<'a> {
fn get_child(&'a self) -> &'a Child<'a>;
fn get_val(&self) -> u64;
}
struct Obj1<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a, R: 'a + Obj<'a>> PartialEq<R> for Obj1<'a> {
fn eq(&self, other: &R) -> bool {
self.get_child().compare(self, other)
}
}
impl<'a> Obj<'a> for Obj1<'a> {
fn get_child(&'a self) -> &'a Child<'a> {
self.child
}
fn get_val(&self) -> u64 {
self.val
}
}
struct Obj2<'a> {
val: u64,
child: &'a Child<'a>,
}
impl<'a, R: 'a + Obj<'a>> PartialEq<R> for Obj2<'a> {
fn eq(&self, other: &R) -> bool {
self.get_child().compare(self, other)
}
}
impl<'a> Obj<'a> for Obj2<'a> {
fn get_child(&'a self) -> &'a Child<'a> {
self.child
}
fn get_val(&self) -> u64 {
self.val
}
}
#[test]
fn test() {
let parent = Parent::new(1);
let child = parent.child(2);
let obj1 = child.obj1(3);
let obj2 = child.obj2(3);
assert!(obj1 == obj2);
assert!(obj2 == obj1);
let parent2 = Parent::new(1);
let child2 = parent2.child(2);
let obj12 = child2.obj1(3);
let obj22 = child2.obj2(3);
assert!(obj12 == obj22);
assert!(obj22 == obj12);
// assert!(obj1 == obj12);
assert!(obj12 == obj1);
}
*/
| {
assert!(!mytest().is_err());
} | identifier_body |
animated_properties.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 cssparser::RGBA;
use style::properties::animated_properties::{Animatable, IntermediateRGBA};
fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA {
let from: IntermediateRGBA = from.into();
let to: IntermediateRGBA = to.into();
from.interpolate(&to, progress).unwrap().into()
}
#[test]
fn test_rgba_color_interepolation_preserves_transparent() {
assert_eq!(interpolate_rgba(RGBA::transparent(),
RGBA::transparent(), 0.5),
RGBA::transparent());
}
#[test]
fn test_rgba_color_interepolation_alpha() {
assert_eq!(interpolate_rgba(RGBA::new(200, 0, 0, 100),
RGBA::new(0, 200, 0, 200), 0.5),
RGBA::new(67, 133, 0, 150));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_1() {
// Some cubic-bezier functions produce values that are out of range [0, 1].
// Unclamped cases.
assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4), | RGBA::new(154, 0, 0, 77));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_2() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6),
RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5),
RGBA::new(0, 154, 0, 77));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_1() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
RGBA::from_floats(0.0, 1.0, 0.0, 0.2), -0.5),
RGBA::from_floats(1.0, 0.0, 0.0, 1.0));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_2() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
RGBA::from_floats(0.0, 1.0, 0.0, 0.2), 1.5),
RGBA::from_floats(0.0, 0.0, 0.0, 0.0));
} | RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5), | random_line_split |
animated_properties.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 cssparser::RGBA;
use style::properties::animated_properties::{Animatable, IntermediateRGBA};
fn | (from: RGBA, to: RGBA, progress: f64) -> RGBA {
let from: IntermediateRGBA = from.into();
let to: IntermediateRGBA = to.into();
from.interpolate(&to, progress).unwrap().into()
}
#[test]
fn test_rgba_color_interepolation_preserves_transparent() {
assert_eq!(interpolate_rgba(RGBA::transparent(),
RGBA::transparent(), 0.5),
RGBA::transparent());
}
#[test]
fn test_rgba_color_interepolation_alpha() {
assert_eq!(interpolate_rgba(RGBA::new(200, 0, 0, 100),
RGBA::new(0, 200, 0, 200), 0.5),
RGBA::new(67, 133, 0, 150));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_1() {
// Some cubic-bezier functions produce values that are out of range [0, 1].
// Unclamped cases.
assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4),
RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5),
RGBA::new(154, 0, 0, 77));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_2() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6),
RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5),
RGBA::new(0, 154, 0, 77));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_1() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
RGBA::from_floats(0.0, 1.0, 0.0, 0.2), -0.5),
RGBA::from_floats(1.0, 0.0, 0.0, 1.0));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_2() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
RGBA::from_floats(0.0, 1.0, 0.0, 0.2), 1.5),
RGBA::from_floats(0.0, 0.0, 0.0, 0.0));
}
| interpolate_rgba | identifier_name |
animated_properties.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 cssparser::RGBA;
use style::properties::animated_properties::{Animatable, IntermediateRGBA};
fn interpolate_rgba(from: RGBA, to: RGBA, progress: f64) -> RGBA {
let from: IntermediateRGBA = from.into();
let to: IntermediateRGBA = to.into();
from.interpolate(&to, progress).unwrap().into()
}
#[test]
fn test_rgba_color_interepolation_preserves_transparent() {
assert_eq!(interpolate_rgba(RGBA::transparent(),
RGBA::transparent(), 0.5),
RGBA::transparent());
}
#[test]
fn test_rgba_color_interepolation_alpha() {
assert_eq!(interpolate_rgba(RGBA::new(200, 0, 0, 100),
RGBA::new(0, 200, 0, 200), 0.5),
RGBA::new(67, 133, 0, 150));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_1() |
#[test]
fn test_rgba_color_interepolation_out_of_range_2() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6),
RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5),
RGBA::new(0, 154, 0, 77));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_1() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
RGBA::from_floats(0.0, 1.0, 0.0, 0.2), -0.5),
RGBA::from_floats(1.0, 0.0, 0.0, 1.0));
}
#[test]
fn test_rgba_color_interepolation_out_of_range_clamped_2() {
assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.8),
RGBA::from_floats(0.0, 1.0, 0.0, 0.2), 1.5),
RGBA::from_floats(0.0, 0.0, 0.0, 0.0));
}
| {
// Some cubic-bezier functions produce values that are out of range [0, 1].
// Unclamped cases.
assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4),
RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5),
RGBA::new(154, 0, 0, 77));
} | identifier_body |
multihash.rs | use crate::Error;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::convert::TryInto;
use core::fmt::Debug;
#[cfg(feature = "serde-codec")]
use serde_big_array::BigArray;
use unsigned_varint::encode as varint_encode;
#[cfg(feature = "std")]
use std::io;
#[cfg(not(feature = "std"))]
use core2::io;
/// Trait that implements hashing.
///
/// It is usually implemented by a custom code table enum that derives the [`Multihash` derive].
///
/// [`Multihash` derive]: crate::derive
pub trait MultihashDigest<const S: usize>:
TryFrom<u64> + Into<u64> + Send + Sync + Unpin + Copy + Eq + Debug +'static
{
/// Calculate the hash of some input data.
///
/// # Example
///
/// ```
/// // `Code` implements `MultihashDigest`
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// println!("{:02x?}", hash);
/// ```
fn digest(&self, input: &[u8]) -> Multihash<S>;
/// Create a multihash from an existing multihash digest.
///
/// # Example
///
/// ```
/// use multihash::{Code, Hasher, MultihashDigest, Sha3_256};
///
/// let mut hasher = Sha3_256::default();
/// hasher.update(b"Hello world!");
/// let hash = Code::Sha3_256.wrap(&hasher.finalize()).unwrap();
/// println!("{:02x?}", hash);
/// ```
fn wrap(&self, digest: &[u8]) -> Result<Multihash<S>, Error>;
}
/// A Multihash instance that only supports the basic functionality and no hashing.
///
/// With this Multihash implementation you can operate on Multihashes in a generic way, but
/// no hasher implementation is associated with the code.
///
/// # Example
///
/// ```
/// use multihash::Multihash;
///
/// const Sha3_256: u64 = 0x16;
/// let digest_bytes = [
/// 0x16, 0x20, 0x64, 0x4b, 0xcc, 0x7e, 0x56, 0x43, 0x73, 0x04, 0x09, 0x99, 0xaa, 0xc8, 0x9e,
/// 0x76, 0x22, 0xf3, 0xca, 0x71, 0xfb, 0xa1, 0xd9, 0x72, 0xfd, 0x94, 0xa3, 0x1c, 0x3b, 0xfb,
/// 0xf2, 0x4e, 0x39, 0x38,
/// ];
/// let mh = Multihash::from_bytes(&digest_bytes).unwrap();
/// assert_eq!(mh.code(), Sha3_256);
/// assert_eq!(mh.size(), 32);
/// assert_eq!(mh.digest(), &digest_bytes[2..]);
/// ```
#[cfg_attr(feature = "serde-codec", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde-codec", derive(serde::Serialize))]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)]
pub struct Multihash<const S: usize> {
/// The code of the Multihash.
code: u64,
/// The actual size of the digest in bytes (not the allocated size).
size: u8,
/// The digest.
#[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))]
digest: [u8; S],
}
impl<const S: usize> Default for Multihash<S> {
fn default() -> Self {
Self {
code: 0,
size: 0,
digest: [0; S],
}
}
}
impl<const S: usize> Multihash<S> {
/// Wraps the digest in a multihash.
pub const fn wrap(code: u64, input_digest: &[u8]) -> Result<Self, Error> {
if input_digest.len() > S {
return Err(Error::InvalidSize(input_digest.len() as _));
}
let size = input_digest.len();
let mut digest = [0; S];
let mut i = 0;
while i < size {
digest[i] = input_digest[i];
i += 1;
}
Ok(Self {
code,
size: size as u8,
digest,
})
}
/// Returns the code of the multihash.
pub const fn code(&self) -> u64 {
self.code
}
/// Returns the size of the digest.
pub const fn size(&self) -> u8 {
self.size
}
/// Returns the digest.
pub fn digest(&self) -> &[u8] {
&self.digest[..self.size as usize]
}
/// Reads a multihash from a byte stream.
pub fn read<R: io::Read>(r: R) -> Result<Self, Error>
where
Self: Sized,
{
let (code, size, digest) = read_multihash(r)?;
Ok(Self { code, size, digest })
}
/// Parses a multihash from a bytes.
///
/// You need to make sure the passed in bytes have the correct length. The digest length
/// needs to match the `size` value of the multihash.
pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, Error>
where
Self: Sized,
{
let result = Self::read(&mut bytes)?;
// There were more bytes supplied than read
if!bytes.is_empty() {
return Err(Error::InvalidSize(bytes.len().try_into().expect(
"Currently the maximum size is 255, therefore always fits into usize",
)));
}
Ok(result)
}
/// Writes a multihash to a byte stream.
pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> {
write_multihash(w, self.code(), self.size(), self.digest())
}
#[cfg(feature = "alloc")]
/// Returns the bytes of a multihash.
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(self.size().into());
self.write(&mut bytes)
.expect("writing to a vec should never fail");
bytes
}
/// Truncates the multihash to the given size. It's up to the caller to ensure that the new size
/// is secure (cryptographically) to use.
///
/// If the new size is larger than the current size, this method does nothing.
///
/// ```
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!").truncate(20);
/// ```
pub fn truncate(&self, size: u8) -> Self {
let mut mh = *self;
mh.size = mh.size.min(size);
mh
}
/// Resizes the backing multihash buffer. This function fails if the hash digest is larger than
/// the target size.
///
/// ```
/// use multihash::{Code, MultihashDigest, MultihashGeneric};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// let large_hash: MultihashGeneric<32> = hash.resize().unwrap();
/// ```
pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> {
let size = self.size as usize;
if size > R {
return Err(Error::InvalidSize(self.size as u64));
}
let mut mh = Multihash {
code: self.code,
size: self.size,
digest: [0; R],
};
mh.digest[..size].copy_from_slice(&self.digest[..size]);
Ok(mh)
}
}
// Don't hash the whole allocated space, but just the actual digest
#[allow(clippy::derive_hash_xor_eq)]
impl<const S: usize> core::hash::Hash for Multihash<S> {
fn hash<T: core::hash::Hasher>(&self, state: &mut T) {
self.code.hash(state);
self.digest().hash(state);
}
}
#[cfg(feature = "alloc")]
impl<const S: usize> From<Multihash<S>> for Vec<u8> {
fn from(multihash: Multihash<S>) -> Self {
multihash.to_bytes()
}
}
impl<const A: usize, const B: usize> PartialEq<Multihash<B>> for Multihash<A> {
fn eq(&self, other: &Multihash<B>) -> bool {
// NOTE: there's no need to explicitly check the sizes, that's implicit in the digest.
self.code == other.code && self.digest() == other.digest()
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Encode for Multihash<S> {
fn encode_to<EncOut: parity_scale_codec::Output +?Sized>(&self, dest: &mut EncOut) {
self.code.encode_to(dest);
self.size.encode_to(dest);
// **NOTE** We write the digest directly to dest, since we have known the size of digest.
//
// We do not choose to encode &[u8] directly, because it will add extra bytes (the compact length of digest).
// For a valid multihash, the length of digest must equal to `size`.
// Therefore, we can only read raw bytes whose length is equal to `size` when decoding.
dest.write(self.digest());
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::EncodeLike for Multihash<S> {}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Decode for Multihash<S> {
fn decode<DecIn: parity_scale_codec::Input>(
input: &mut DecIn,
) -> Result<Self, parity_scale_codec::Error> {
let mut mh = Multihash {
code: parity_scale_codec::Decode::decode(input)?,
size: parity_scale_codec::Decode::decode(input)?,
digest: [0; S],
};
if mh.size as usize > S {
return Err(parity_scale_codec::Error::from("invalid size"));
}
// For a valid multihash, the length of digest must equal to the size.
input.read(&mut mh.digest[..mh.size as usize])?;
Ok(mh)
}
}
/// Writes the multihash to a byte stream.
pub fn write_multihash<W>(mut w: W, code: u64, size: u8, digest: &[u8]) -> Result<(), Error>
where
W: io::Write,
{
let mut code_buf = varint_encode::u64_buffer();
let code = varint_encode::u64(code, &mut code_buf);
let mut size_buf = varint_encode::u8_buffer();
let size = varint_encode::u8(size, &mut size_buf);
w.write_all(code)?;
w.write_all(size)?;
w.write_all(digest)?;
Ok(())
}
/// Reads a multihash from a byte stream that contains a full multihash (code, size and the digest)
///
/// Returns the code, size and the digest. The size is the actual size and not the
/// maximum/allocated size of the digest.
///
/// Currently the maximum size for a digest is 255 bytes.
pub fn read_multihash<R, const S: usize>(mut r: R) -> Result<(u64, u8, [u8; S]), Error>
where
R: io::Read,
{
let code = read_u64(&mut r)?;
let size = read_u64(&mut r)?;
if size > S as u64 || size > u8::MAX as u64 {
return Err(Error::InvalidSize(size));
}
let mut digest = [0; S];
r.read_exact(&mut digest[..size as usize])?;
Ok((code, size as u8, digest))
}
#[cfg(feature = "std")]
pub(crate) use unsigned_varint::io::read_u64;
/// Reads 64 bits from a byte array into a u64
/// Adapted from unsigned-varint's generated read_u64 function at
/// https://github.com/paritytech/unsigned-varint/blob/master/src/io.rs
#[cfg(not(feature = "std"))]
pub(crate) fn | <R: io::Read>(mut r: R) -> Result<u64, Error> {
use unsigned_varint::decode;
let mut b = varint_encode::u64_buffer();
for i in 0..b.len() {
let n = r.read(&mut (b[i..i + 1]))?;
if n == 0 {
return Err(Error::Varint(decode::Error::Insufficient));
} else if decode::is_last(b[i]) {
return Ok(decode::u64(&b[..=i]).unwrap().0);
}
}
Err(Error::Varint(decode::Error::Overflow))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::multihash_impl::Code;
#[test]
fn roundtrip() {
let hash = Code::Sha2_256.digest(b"hello world");
let mut buf = [0u8; 35];
hash.write(&mut buf[..]).unwrap();
let hash2 = Multihash::<32>::read(&buf[..]).unwrap();
assert_eq!(hash, hash2);
}
#[test]
fn test_truncate_down() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(20);
assert_eq!(small.size(), 20);
}
#[test]
fn test_truncate_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(100);
assert_eq!(small.size(), 32);
}
#[test]
fn test_resize_fits() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<32> = hash.resize().unwrap();
}
#[test]
fn test_resize_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<100> = hash.resize().unwrap();
}
#[test]
fn test_resize_truncate() {
let hash = Code::Sha2_256.digest(b"hello world");
hash.resize::<20>().unwrap_err();
}
#[test]
#[cfg(feature = "scale-codec")]
fn test_scale() {
use parity_scale_codec::{Decode, Encode};
let mh1 = Code::Sha2_256.digest(b"hello world");
// println!("mh1: code = {}, size = {}, digest = {:?}", mh1.code(), mh1.size(), mh1.digest());
let mh1_bytes = mh1.encode();
// println!("Multihash<32>: {}", hex::encode(&mh1_bytes));
let mh2: Multihash<32> = Decode::decode(&mut &mh1_bytes[..]).unwrap();
assert_eq!(mh1, mh2);
let mh3: Multihash<64> = Code::Sha2_256.digest(b"hello world");
// println!("mh3: code = {}, size = {}, digest = {:?}", mh3.code(), mh3.size(), mh3.digest());
let mh3_bytes = mh3.encode();
// println!("Multihash<64>: {}", hex::encode(&mh3_bytes));
let mh4: Multihash<64> = Decode::decode(&mut &mh3_bytes[..]).unwrap();
assert_eq!(mh3, mh4);
assert_eq!(mh1_bytes, mh3_bytes);
}
#[test]
#[cfg(feature = "serde-codec")]
fn test_serde() {
let mh = Multihash::<32>::default();
let bytes = serde_json::to_string(&mh).unwrap();
let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap();
assert_eq!(mh, mh2);
}
#[test]
fn test_eq_sizes() {
let mh1 = Multihash::<32>::default();
let mh2 = Multihash::<64>::default();
assert_eq!(mh1, mh2);
}
}
| read_u64 | identifier_name |
multihash.rs | use crate::Error;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::convert::TryInto;
use core::fmt::Debug;
#[cfg(feature = "serde-codec")]
use serde_big_array::BigArray;
use unsigned_varint::encode as varint_encode;
#[cfg(feature = "std")]
use std::io;
#[cfg(not(feature = "std"))]
use core2::io;
/// Trait that implements hashing.
///
/// It is usually implemented by a custom code table enum that derives the [`Multihash` derive].
///
/// [`Multihash` derive]: crate::derive
pub trait MultihashDigest<const S: usize>:
TryFrom<u64> + Into<u64> + Send + Sync + Unpin + Copy + Eq + Debug +'static
{
/// Calculate the hash of some input data.
///
/// # Example
///
/// ```
/// // `Code` implements `MultihashDigest`
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// println!("{:02x?}", hash);
/// ```
fn digest(&self, input: &[u8]) -> Multihash<S>;
/// Create a multihash from an existing multihash digest.
///
/// # Example
///
/// ```
/// use multihash::{Code, Hasher, MultihashDigest, Sha3_256};
///
/// let mut hasher = Sha3_256::default();
/// hasher.update(b"Hello world!");
/// let hash = Code::Sha3_256.wrap(&hasher.finalize()).unwrap();
/// println!("{:02x?}", hash);
/// ```
fn wrap(&self, digest: &[u8]) -> Result<Multihash<S>, Error>;
}
/// A Multihash instance that only supports the basic functionality and no hashing.
///
/// With this Multihash implementation you can operate on Multihashes in a generic way, but
/// no hasher implementation is associated with the code.
///
/// # Example
///
/// ```
/// use multihash::Multihash;
///
/// const Sha3_256: u64 = 0x16;
/// let digest_bytes = [
/// 0x16, 0x20, 0x64, 0x4b, 0xcc, 0x7e, 0x56, 0x43, 0x73, 0x04, 0x09, 0x99, 0xaa, 0xc8, 0x9e,
/// 0x76, 0x22, 0xf3, 0xca, 0x71, 0xfb, 0xa1, 0xd9, 0x72, 0xfd, 0x94, 0xa3, 0x1c, 0x3b, 0xfb,
/// 0xf2, 0x4e, 0x39, 0x38,
/// ];
/// let mh = Multihash::from_bytes(&digest_bytes).unwrap();
/// assert_eq!(mh.code(), Sha3_256);
/// assert_eq!(mh.size(), 32);
/// assert_eq!(mh.digest(), &digest_bytes[2..]);
/// ```
#[cfg_attr(feature = "serde-codec", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde-codec", derive(serde::Serialize))]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)]
pub struct Multihash<const S: usize> {
/// The code of the Multihash.
code: u64,
/// The actual size of the digest in bytes (not the allocated size).
size: u8,
/// The digest.
#[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))]
digest: [u8; S],
}
impl<const S: usize> Default for Multihash<S> {
fn default() -> Self {
Self {
code: 0,
size: 0,
digest: [0; S],
}
}
}
impl<const S: usize> Multihash<S> {
/// Wraps the digest in a multihash.
pub const fn wrap(code: u64, input_digest: &[u8]) -> Result<Self, Error> {
if input_digest.len() > S {
return Err(Error::InvalidSize(input_digest.len() as _));
}
let size = input_digest.len();
let mut digest = [0; S];
let mut i = 0;
while i < size {
digest[i] = input_digest[i];
i += 1;
}
Ok(Self {
code,
size: size as u8,
digest,
})
}
/// Returns the code of the multihash.
pub const fn code(&self) -> u64 {
self.code
}
/// Returns the size of the digest.
pub const fn size(&self) -> u8 {
self.size
}
/// Returns the digest.
pub fn digest(&self) -> &[u8] {
&self.digest[..self.size as usize]
}
/// Reads a multihash from a byte stream.
pub fn read<R: io::Read>(r: R) -> Result<Self, Error>
where
Self: Sized,
{
let (code, size, digest) = read_multihash(r)?;
Ok(Self { code, size, digest })
}
/// Parses a multihash from a bytes.
///
/// You need to make sure the passed in bytes have the correct length. The digest length
/// needs to match the `size` value of the multihash.
pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, Error>
where
Self: Sized,
{
let result = Self::read(&mut bytes)?;
// There were more bytes supplied than read
if!bytes.is_empty() {
return Err(Error::InvalidSize(bytes.len().try_into().expect(
"Currently the maximum size is 255, therefore always fits into usize",
)));
}
Ok(result)
}
/// Writes a multihash to a byte stream.
pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> {
write_multihash(w, self.code(), self.size(), self.digest())
}
#[cfg(feature = "alloc")]
/// Returns the bytes of a multihash.
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(self.size().into());
self.write(&mut bytes)
.expect("writing to a vec should never fail");
bytes
}
/// Truncates the multihash to the given size. It's up to the caller to ensure that the new size
/// is secure (cryptographically) to use.
///
/// If the new size is larger than the current size, this method does nothing.
///
/// ```
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!").truncate(20);
/// ```
pub fn truncate(&self, size: u8) -> Self {
let mut mh = *self;
mh.size = mh.size.min(size);
mh
}
/// Resizes the backing multihash buffer. This function fails if the hash digest is larger than
/// the target size.
///
/// ```
/// use multihash::{Code, MultihashDigest, MultihashGeneric};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// let large_hash: MultihashGeneric<32> = hash.resize().unwrap();
/// ```
pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> {
let size = self.size as usize;
if size > R {
return Err(Error::InvalidSize(self.size as u64));
}
let mut mh = Multihash {
code: self.code,
size: self.size,
digest: [0; R],
};
mh.digest[..size].copy_from_slice(&self.digest[..size]);
Ok(mh)
}
}
// Don't hash the whole allocated space, but just the actual digest
#[allow(clippy::derive_hash_xor_eq)]
impl<const S: usize> core::hash::Hash for Multihash<S> {
fn hash<T: core::hash::Hasher>(&self, state: &mut T) {
self.code.hash(state);
self.digest().hash(state);
}
}
#[cfg(feature = "alloc")]
impl<const S: usize> From<Multihash<S>> for Vec<u8> {
fn from(multihash: Multihash<S>) -> Self {
multihash.to_bytes()
}
}
impl<const A: usize, const B: usize> PartialEq<Multihash<B>> for Multihash<A> {
fn eq(&self, other: &Multihash<B>) -> bool {
// NOTE: there's no need to explicitly check the sizes, that's implicit in the digest.
self.code == other.code && self.digest() == other.digest()
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Encode for Multihash<S> {
fn encode_to<EncOut: parity_scale_codec::Output +?Sized>(&self, dest: &mut EncOut) {
self.code.encode_to(dest);
self.size.encode_to(dest);
// **NOTE** We write the digest directly to dest, since we have known the size of digest.
//
// We do not choose to encode &[u8] directly, because it will add extra bytes (the compact length of digest).
// For a valid multihash, the length of digest must equal to `size`.
// Therefore, we can only read raw bytes whose length is equal to `size` when decoding.
dest.write(self.digest());
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::EncodeLike for Multihash<S> {}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Decode for Multihash<S> {
fn decode<DecIn: parity_scale_codec::Input>(
input: &mut DecIn,
) -> Result<Self, parity_scale_codec::Error> {
let mut mh = Multihash {
code: parity_scale_codec::Decode::decode(input)?,
size: parity_scale_codec::Decode::decode(input)?,
digest: [0; S],
};
if mh.size as usize > S {
return Err(parity_scale_codec::Error::from("invalid size"));
}
// For a valid multihash, the length of digest must equal to the size.
input.read(&mut mh.digest[..mh.size as usize])?;
Ok(mh)
}
}
/// Writes the multihash to a byte stream.
pub fn write_multihash<W>(mut w: W, code: u64, size: u8, digest: &[u8]) -> Result<(), Error>
where
W: io::Write,
{
let mut code_buf = varint_encode::u64_buffer();
let code = varint_encode::u64(code, &mut code_buf);
let mut size_buf = varint_encode::u8_buffer();
let size = varint_encode::u8(size, &mut size_buf);
w.write_all(code)?;
w.write_all(size)?;
w.write_all(digest)?;
Ok(())
}
/// Reads a multihash from a byte stream that contains a full multihash (code, size and the digest)
///
/// Returns the code, size and the digest. The size is the actual size and not the
/// maximum/allocated size of the digest.
///
/// Currently the maximum size for a digest is 255 bytes.
pub fn read_multihash<R, const S: usize>(mut r: R) -> Result<(u64, u8, [u8; S]), Error>
where
R: io::Read,
{
let code = read_u64(&mut r)?;
let size = read_u64(&mut r)?;
if size > S as u64 || size > u8::MAX as u64 {
return Err(Error::InvalidSize(size));
}
let mut digest = [0; S];
r.read_exact(&mut digest[..size as usize])?;
Ok((code, size as u8, digest))
}
#[cfg(feature = "std")]
pub(crate) use unsigned_varint::io::read_u64;
/// Reads 64 bits from a byte array into a u64
/// Adapted from unsigned-varint's generated read_u64 function at
/// https://github.com/paritytech/unsigned-varint/blob/master/src/io.rs
#[cfg(not(feature = "std"))]
pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> {
use unsigned_varint::decode;
let mut b = varint_encode::u64_buffer();
for i in 0..b.len() {
let n = r.read(&mut (b[i..i + 1]))?;
if n == 0 {
return Err(Error::Varint(decode::Error::Insufficient));
} else if decode::is_last(b[i]) {
return Ok(decode::u64(&b[..=i]).unwrap().0);
}
}
Err(Error::Varint(decode::Error::Overflow))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::multihash_impl::Code;
#[test]
fn roundtrip() {
let hash = Code::Sha2_256.digest(b"hello world");
let mut buf = [0u8; 35];
hash.write(&mut buf[..]).unwrap();
let hash2 = Multihash::<32>::read(&buf[..]).unwrap();
assert_eq!(hash, hash2);
}
#[test]
fn test_truncate_down() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(20);
assert_eq!(small.size(), 20);
}
#[test]
fn test_truncate_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(100);
assert_eq!(small.size(), 32);
}
#[test]
fn test_resize_fits() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<32> = hash.resize().unwrap();
}
#[test]
fn test_resize_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<100> = hash.resize().unwrap();
}
#[test]
fn test_resize_truncate() {
let hash = Code::Sha2_256.digest(b"hello world");
hash.resize::<20>().unwrap_err();
}
#[test]
#[cfg(feature = "scale-codec")]
fn test_scale() {
use parity_scale_codec::{Decode, Encode};
let mh1 = Code::Sha2_256.digest(b"hello world");
// println!("mh1: code = {}, size = {}, digest = {:?}", mh1.code(), mh1.size(), mh1.digest());
let mh1_bytes = mh1.encode();
// println!("Multihash<32>: {}", hex::encode(&mh1_bytes));
let mh2: Multihash<32> = Decode::decode(&mut &mh1_bytes[..]).unwrap();
assert_eq!(mh1, mh2);
let mh3: Multihash<64> = Code::Sha2_256.digest(b"hello world");
// println!("mh3: code = {}, size = {}, digest = {:?}", mh3.code(), mh3.size(), mh3.digest());
let mh3_bytes = mh3.encode();
// println!("Multihash<64>: {}", hex::encode(&mh3_bytes));
let mh4: Multihash<64> = Decode::decode(&mut &mh3_bytes[..]).unwrap();
assert_eq!(mh3, mh4);
assert_eq!(mh1_bytes, mh3_bytes);
}
#[test]
#[cfg(feature = "serde-codec")]
fn test_serde() |
#[test]
fn test_eq_sizes() {
let mh1 = Multihash::<32>::default();
let mh2 = Multihash::<64>::default();
assert_eq!(mh1, mh2);
}
}
| {
let mh = Multihash::<32>::default();
let bytes = serde_json::to_string(&mh).unwrap();
let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap();
assert_eq!(mh, mh2);
} | identifier_body |
multihash.rs | use crate::Error;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::convert::TryInto;
use core::fmt::Debug;
#[cfg(feature = "serde-codec")]
use serde_big_array::BigArray;
use unsigned_varint::encode as varint_encode;
#[cfg(feature = "std")]
use std::io;
#[cfg(not(feature = "std"))]
use core2::io;
/// Trait that implements hashing.
///
/// It is usually implemented by a custom code table enum that derives the [`Multihash` derive].
///
/// [`Multihash` derive]: crate::derive
pub trait MultihashDigest<const S: usize>:
TryFrom<u64> + Into<u64> + Send + Sync + Unpin + Copy + Eq + Debug +'static
{
/// Calculate the hash of some input data.
///
/// # Example
///
/// ```
/// // `Code` implements `MultihashDigest`
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// println!("{:02x?}", hash);
/// ```
fn digest(&self, input: &[u8]) -> Multihash<S>;
/// Create a multihash from an existing multihash digest.
///
/// # Example
///
/// ```
/// use multihash::{Code, Hasher, MultihashDigest, Sha3_256};
///
/// let mut hasher = Sha3_256::default();
/// hasher.update(b"Hello world!");
/// let hash = Code::Sha3_256.wrap(&hasher.finalize()).unwrap();
/// println!("{:02x?}", hash);
/// ```
fn wrap(&self, digest: &[u8]) -> Result<Multihash<S>, Error>;
}
/// A Multihash instance that only supports the basic functionality and no hashing.
///
/// With this Multihash implementation you can operate on Multihashes in a generic way, but
/// no hasher implementation is associated with the code.
///
/// # Example
///
/// ```
/// use multihash::Multihash;
///
/// const Sha3_256: u64 = 0x16;
/// let digest_bytes = [
/// 0x16, 0x20, 0x64, 0x4b, 0xcc, 0x7e, 0x56, 0x43, 0x73, 0x04, 0x09, 0x99, 0xaa, 0xc8, 0x9e,
/// 0x76, 0x22, 0xf3, 0xca, 0x71, 0xfb, 0xa1, 0xd9, 0x72, 0xfd, 0x94, 0xa3, 0x1c, 0x3b, 0xfb,
/// 0xf2, 0x4e, 0x39, 0x38,
/// ];
/// let mh = Multihash::from_bytes(&digest_bytes).unwrap();
/// assert_eq!(mh.code(), Sha3_256);
/// assert_eq!(mh.size(), 32);
/// assert_eq!(mh.digest(), &digest_bytes[2..]);
/// ```
#[cfg_attr(feature = "serde-codec", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde-codec", derive(serde::Serialize))]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)]
pub struct Multihash<const S: usize> {
/// The code of the Multihash.
code: u64,
/// The actual size of the digest in bytes (not the allocated size).
size: u8,
/// The digest.
#[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))]
digest: [u8; S],
}
impl<const S: usize> Default for Multihash<S> {
fn default() -> Self {
Self {
code: 0,
size: 0,
digest: [0; S],
}
}
}
impl<const S: usize> Multihash<S> {
/// Wraps the digest in a multihash.
pub const fn wrap(code: u64, input_digest: &[u8]) -> Result<Self, Error> {
if input_digest.len() > S {
return Err(Error::InvalidSize(input_digest.len() as _));
}
let size = input_digest.len();
let mut digest = [0; S];
let mut i = 0;
while i < size {
digest[i] = input_digest[i];
i += 1;
}
Ok(Self {
code,
size: size as u8,
digest,
})
}
/// Returns the code of the multihash.
pub const fn code(&self) -> u64 {
self.code
}
/// Returns the size of the digest.
pub const fn size(&self) -> u8 {
self.size
}
/// Returns the digest.
pub fn digest(&self) -> &[u8] {
&self.digest[..self.size as usize]
}
/// Reads a multihash from a byte stream.
pub fn read<R: io::Read>(r: R) -> Result<Self, Error>
where
Self: Sized,
{
let (code, size, digest) = read_multihash(r)?;
Ok(Self { code, size, digest })
}
/// Parses a multihash from a bytes.
///
/// You need to make sure the passed in bytes have the correct length. The digest length
/// needs to match the `size` value of the multihash.
pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, Error>
where
Self: Sized,
{
let result = Self::read(&mut bytes)?;
// There were more bytes supplied than read
if!bytes.is_empty() { | return Err(Error::InvalidSize(bytes.len().try_into().expect(
"Currently the maximum size is 255, therefore always fits into usize",
)));
}
Ok(result)
}
/// Writes a multihash to a byte stream.
pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> {
write_multihash(w, self.code(), self.size(), self.digest())
}
#[cfg(feature = "alloc")]
/// Returns the bytes of a multihash.
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(self.size().into());
self.write(&mut bytes)
.expect("writing to a vec should never fail");
bytes
}
/// Truncates the multihash to the given size. It's up to the caller to ensure that the new size
/// is secure (cryptographically) to use.
///
/// If the new size is larger than the current size, this method does nothing.
///
/// ```
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!").truncate(20);
/// ```
pub fn truncate(&self, size: u8) -> Self {
let mut mh = *self;
mh.size = mh.size.min(size);
mh
}
/// Resizes the backing multihash buffer. This function fails if the hash digest is larger than
/// the target size.
///
/// ```
/// use multihash::{Code, MultihashDigest, MultihashGeneric};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// let large_hash: MultihashGeneric<32> = hash.resize().unwrap();
/// ```
pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> {
let size = self.size as usize;
if size > R {
return Err(Error::InvalidSize(self.size as u64));
}
let mut mh = Multihash {
code: self.code,
size: self.size,
digest: [0; R],
};
mh.digest[..size].copy_from_slice(&self.digest[..size]);
Ok(mh)
}
}
// Don't hash the whole allocated space, but just the actual digest
#[allow(clippy::derive_hash_xor_eq)]
impl<const S: usize> core::hash::Hash for Multihash<S> {
fn hash<T: core::hash::Hasher>(&self, state: &mut T) {
self.code.hash(state);
self.digest().hash(state);
}
}
#[cfg(feature = "alloc")]
impl<const S: usize> From<Multihash<S>> for Vec<u8> {
fn from(multihash: Multihash<S>) -> Self {
multihash.to_bytes()
}
}
impl<const A: usize, const B: usize> PartialEq<Multihash<B>> for Multihash<A> {
fn eq(&self, other: &Multihash<B>) -> bool {
// NOTE: there's no need to explicitly check the sizes, that's implicit in the digest.
self.code == other.code && self.digest() == other.digest()
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Encode for Multihash<S> {
fn encode_to<EncOut: parity_scale_codec::Output +?Sized>(&self, dest: &mut EncOut) {
self.code.encode_to(dest);
self.size.encode_to(dest);
// **NOTE** We write the digest directly to dest, since we have known the size of digest.
//
// We do not choose to encode &[u8] directly, because it will add extra bytes (the compact length of digest).
// For a valid multihash, the length of digest must equal to `size`.
// Therefore, we can only read raw bytes whose length is equal to `size` when decoding.
dest.write(self.digest());
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::EncodeLike for Multihash<S> {}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Decode for Multihash<S> {
fn decode<DecIn: parity_scale_codec::Input>(
input: &mut DecIn,
) -> Result<Self, parity_scale_codec::Error> {
let mut mh = Multihash {
code: parity_scale_codec::Decode::decode(input)?,
size: parity_scale_codec::Decode::decode(input)?,
digest: [0; S],
};
if mh.size as usize > S {
return Err(parity_scale_codec::Error::from("invalid size"));
}
// For a valid multihash, the length of digest must equal to the size.
input.read(&mut mh.digest[..mh.size as usize])?;
Ok(mh)
}
}
/// Writes the multihash to a byte stream.
pub fn write_multihash<W>(mut w: W, code: u64, size: u8, digest: &[u8]) -> Result<(), Error>
where
W: io::Write,
{
let mut code_buf = varint_encode::u64_buffer();
let code = varint_encode::u64(code, &mut code_buf);
let mut size_buf = varint_encode::u8_buffer();
let size = varint_encode::u8(size, &mut size_buf);
w.write_all(code)?;
w.write_all(size)?;
w.write_all(digest)?;
Ok(())
}
/// Reads a multihash from a byte stream that contains a full multihash (code, size and the digest)
///
/// Returns the code, size and the digest. The size is the actual size and not the
/// maximum/allocated size of the digest.
///
/// Currently the maximum size for a digest is 255 bytes.
pub fn read_multihash<R, const S: usize>(mut r: R) -> Result<(u64, u8, [u8; S]), Error>
where
R: io::Read,
{
let code = read_u64(&mut r)?;
let size = read_u64(&mut r)?;
if size > S as u64 || size > u8::MAX as u64 {
return Err(Error::InvalidSize(size));
}
let mut digest = [0; S];
r.read_exact(&mut digest[..size as usize])?;
Ok((code, size as u8, digest))
}
#[cfg(feature = "std")]
pub(crate) use unsigned_varint::io::read_u64;
/// Reads 64 bits from a byte array into a u64
/// Adapted from unsigned-varint's generated read_u64 function at
/// https://github.com/paritytech/unsigned-varint/blob/master/src/io.rs
#[cfg(not(feature = "std"))]
pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> {
use unsigned_varint::decode;
let mut b = varint_encode::u64_buffer();
for i in 0..b.len() {
let n = r.read(&mut (b[i..i + 1]))?;
if n == 0 {
return Err(Error::Varint(decode::Error::Insufficient));
} else if decode::is_last(b[i]) {
return Ok(decode::u64(&b[..=i]).unwrap().0);
}
}
Err(Error::Varint(decode::Error::Overflow))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::multihash_impl::Code;
#[test]
fn roundtrip() {
let hash = Code::Sha2_256.digest(b"hello world");
let mut buf = [0u8; 35];
hash.write(&mut buf[..]).unwrap();
let hash2 = Multihash::<32>::read(&buf[..]).unwrap();
assert_eq!(hash, hash2);
}
#[test]
fn test_truncate_down() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(20);
assert_eq!(small.size(), 20);
}
#[test]
fn test_truncate_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(100);
assert_eq!(small.size(), 32);
}
#[test]
fn test_resize_fits() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<32> = hash.resize().unwrap();
}
#[test]
fn test_resize_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<100> = hash.resize().unwrap();
}
#[test]
fn test_resize_truncate() {
let hash = Code::Sha2_256.digest(b"hello world");
hash.resize::<20>().unwrap_err();
}
#[test]
#[cfg(feature = "scale-codec")]
fn test_scale() {
use parity_scale_codec::{Decode, Encode};
let mh1 = Code::Sha2_256.digest(b"hello world");
// println!("mh1: code = {}, size = {}, digest = {:?}", mh1.code(), mh1.size(), mh1.digest());
let mh1_bytes = mh1.encode();
// println!("Multihash<32>: {}", hex::encode(&mh1_bytes));
let mh2: Multihash<32> = Decode::decode(&mut &mh1_bytes[..]).unwrap();
assert_eq!(mh1, mh2);
let mh3: Multihash<64> = Code::Sha2_256.digest(b"hello world");
// println!("mh3: code = {}, size = {}, digest = {:?}", mh3.code(), mh3.size(), mh3.digest());
let mh3_bytes = mh3.encode();
// println!("Multihash<64>: {}", hex::encode(&mh3_bytes));
let mh4: Multihash<64> = Decode::decode(&mut &mh3_bytes[..]).unwrap();
assert_eq!(mh3, mh4);
assert_eq!(mh1_bytes, mh3_bytes);
}
#[test]
#[cfg(feature = "serde-codec")]
fn test_serde() {
let mh = Multihash::<32>::default();
let bytes = serde_json::to_string(&mh).unwrap();
let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap();
assert_eq!(mh, mh2);
}
#[test]
fn test_eq_sizes() {
let mh1 = Multihash::<32>::default();
let mh2 = Multihash::<64>::default();
assert_eq!(mh1, mh2);
}
} | random_line_split |
|
multihash.rs | use crate::Error;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::convert::TryInto;
use core::fmt::Debug;
#[cfg(feature = "serde-codec")]
use serde_big_array::BigArray;
use unsigned_varint::encode as varint_encode;
#[cfg(feature = "std")]
use std::io;
#[cfg(not(feature = "std"))]
use core2::io;
/// Trait that implements hashing.
///
/// It is usually implemented by a custom code table enum that derives the [`Multihash` derive].
///
/// [`Multihash` derive]: crate::derive
pub trait MultihashDigest<const S: usize>:
TryFrom<u64> + Into<u64> + Send + Sync + Unpin + Copy + Eq + Debug +'static
{
/// Calculate the hash of some input data.
///
/// # Example
///
/// ```
/// // `Code` implements `MultihashDigest`
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// println!("{:02x?}", hash);
/// ```
fn digest(&self, input: &[u8]) -> Multihash<S>;
/// Create a multihash from an existing multihash digest.
///
/// # Example
///
/// ```
/// use multihash::{Code, Hasher, MultihashDigest, Sha3_256};
///
/// let mut hasher = Sha3_256::default();
/// hasher.update(b"Hello world!");
/// let hash = Code::Sha3_256.wrap(&hasher.finalize()).unwrap();
/// println!("{:02x?}", hash);
/// ```
fn wrap(&self, digest: &[u8]) -> Result<Multihash<S>, Error>;
}
/// A Multihash instance that only supports the basic functionality and no hashing.
///
/// With this Multihash implementation you can operate on Multihashes in a generic way, but
/// no hasher implementation is associated with the code.
///
/// # Example
///
/// ```
/// use multihash::Multihash;
///
/// const Sha3_256: u64 = 0x16;
/// let digest_bytes = [
/// 0x16, 0x20, 0x64, 0x4b, 0xcc, 0x7e, 0x56, 0x43, 0x73, 0x04, 0x09, 0x99, 0xaa, 0xc8, 0x9e,
/// 0x76, 0x22, 0xf3, 0xca, 0x71, 0xfb, 0xa1, 0xd9, 0x72, 0xfd, 0x94, 0xa3, 0x1c, 0x3b, 0xfb,
/// 0xf2, 0x4e, 0x39, 0x38,
/// ];
/// let mh = Multihash::from_bytes(&digest_bytes).unwrap();
/// assert_eq!(mh.code(), Sha3_256);
/// assert_eq!(mh.size(), 32);
/// assert_eq!(mh.digest(), &digest_bytes[2..]);
/// ```
#[cfg_attr(feature = "serde-codec", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde-codec", derive(serde::Serialize))]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)]
pub struct Multihash<const S: usize> {
/// The code of the Multihash.
code: u64,
/// The actual size of the digest in bytes (not the allocated size).
size: u8,
/// The digest.
#[cfg_attr(feature = "serde-codec", serde(with = "BigArray"))]
digest: [u8; S],
}
impl<const S: usize> Default for Multihash<S> {
fn default() -> Self {
Self {
code: 0,
size: 0,
digest: [0; S],
}
}
}
impl<const S: usize> Multihash<S> {
/// Wraps the digest in a multihash.
pub const fn wrap(code: u64, input_digest: &[u8]) -> Result<Self, Error> {
if input_digest.len() > S {
return Err(Error::InvalidSize(input_digest.len() as _));
}
let size = input_digest.len();
let mut digest = [0; S];
let mut i = 0;
while i < size {
digest[i] = input_digest[i];
i += 1;
}
Ok(Self {
code,
size: size as u8,
digest,
})
}
/// Returns the code of the multihash.
pub const fn code(&self) -> u64 {
self.code
}
/// Returns the size of the digest.
pub const fn size(&self) -> u8 {
self.size
}
/// Returns the digest.
pub fn digest(&self) -> &[u8] {
&self.digest[..self.size as usize]
}
/// Reads a multihash from a byte stream.
pub fn read<R: io::Read>(r: R) -> Result<Self, Error>
where
Self: Sized,
{
let (code, size, digest) = read_multihash(r)?;
Ok(Self { code, size, digest })
}
/// Parses a multihash from a bytes.
///
/// You need to make sure the passed in bytes have the correct length. The digest length
/// needs to match the `size` value of the multihash.
pub fn from_bytes(mut bytes: &[u8]) -> Result<Self, Error>
where
Self: Sized,
{
let result = Self::read(&mut bytes)?;
// There were more bytes supplied than read
if!bytes.is_empty() |
Ok(result)
}
/// Writes a multihash to a byte stream.
pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> {
write_multihash(w, self.code(), self.size(), self.digest())
}
#[cfg(feature = "alloc")]
/// Returns the bytes of a multihash.
pub fn to_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::with_capacity(self.size().into());
self.write(&mut bytes)
.expect("writing to a vec should never fail");
bytes
}
/// Truncates the multihash to the given size. It's up to the caller to ensure that the new size
/// is secure (cryptographically) to use.
///
/// If the new size is larger than the current size, this method does nothing.
///
/// ```
/// use multihash::{Code, MultihashDigest};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!").truncate(20);
/// ```
pub fn truncate(&self, size: u8) -> Self {
let mut mh = *self;
mh.size = mh.size.min(size);
mh
}
/// Resizes the backing multihash buffer. This function fails if the hash digest is larger than
/// the target size.
///
/// ```
/// use multihash::{Code, MultihashDigest, MultihashGeneric};
///
/// let hash = Code::Sha3_256.digest(b"Hello world!");
/// let large_hash: MultihashGeneric<32> = hash.resize().unwrap();
/// ```
pub fn resize<const R: usize>(&self) -> Result<Multihash<R>, Error> {
let size = self.size as usize;
if size > R {
return Err(Error::InvalidSize(self.size as u64));
}
let mut mh = Multihash {
code: self.code,
size: self.size,
digest: [0; R],
};
mh.digest[..size].copy_from_slice(&self.digest[..size]);
Ok(mh)
}
}
// Don't hash the whole allocated space, but just the actual digest
#[allow(clippy::derive_hash_xor_eq)]
impl<const S: usize> core::hash::Hash for Multihash<S> {
fn hash<T: core::hash::Hasher>(&self, state: &mut T) {
self.code.hash(state);
self.digest().hash(state);
}
}
#[cfg(feature = "alloc")]
impl<const S: usize> From<Multihash<S>> for Vec<u8> {
fn from(multihash: Multihash<S>) -> Self {
multihash.to_bytes()
}
}
impl<const A: usize, const B: usize> PartialEq<Multihash<B>> for Multihash<A> {
fn eq(&self, other: &Multihash<B>) -> bool {
// NOTE: there's no need to explicitly check the sizes, that's implicit in the digest.
self.code == other.code && self.digest() == other.digest()
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Encode for Multihash<S> {
fn encode_to<EncOut: parity_scale_codec::Output +?Sized>(&self, dest: &mut EncOut) {
self.code.encode_to(dest);
self.size.encode_to(dest);
// **NOTE** We write the digest directly to dest, since we have known the size of digest.
//
// We do not choose to encode &[u8] directly, because it will add extra bytes (the compact length of digest).
// For a valid multihash, the length of digest must equal to `size`.
// Therefore, we can only read raw bytes whose length is equal to `size` when decoding.
dest.write(self.digest());
}
}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::EncodeLike for Multihash<S> {}
#[cfg(feature = "scale-codec")]
impl<const S: usize> parity_scale_codec::Decode for Multihash<S> {
fn decode<DecIn: parity_scale_codec::Input>(
input: &mut DecIn,
) -> Result<Self, parity_scale_codec::Error> {
let mut mh = Multihash {
code: parity_scale_codec::Decode::decode(input)?,
size: parity_scale_codec::Decode::decode(input)?,
digest: [0; S],
};
if mh.size as usize > S {
return Err(parity_scale_codec::Error::from("invalid size"));
}
// For a valid multihash, the length of digest must equal to the size.
input.read(&mut mh.digest[..mh.size as usize])?;
Ok(mh)
}
}
/// Writes the multihash to a byte stream.
pub fn write_multihash<W>(mut w: W, code: u64, size: u8, digest: &[u8]) -> Result<(), Error>
where
W: io::Write,
{
let mut code_buf = varint_encode::u64_buffer();
let code = varint_encode::u64(code, &mut code_buf);
let mut size_buf = varint_encode::u8_buffer();
let size = varint_encode::u8(size, &mut size_buf);
w.write_all(code)?;
w.write_all(size)?;
w.write_all(digest)?;
Ok(())
}
/// Reads a multihash from a byte stream that contains a full multihash (code, size and the digest)
///
/// Returns the code, size and the digest. The size is the actual size and not the
/// maximum/allocated size of the digest.
///
/// Currently the maximum size for a digest is 255 bytes.
pub fn read_multihash<R, const S: usize>(mut r: R) -> Result<(u64, u8, [u8; S]), Error>
where
R: io::Read,
{
let code = read_u64(&mut r)?;
let size = read_u64(&mut r)?;
if size > S as u64 || size > u8::MAX as u64 {
return Err(Error::InvalidSize(size));
}
let mut digest = [0; S];
r.read_exact(&mut digest[..size as usize])?;
Ok((code, size as u8, digest))
}
#[cfg(feature = "std")]
pub(crate) use unsigned_varint::io::read_u64;
/// Reads 64 bits from a byte array into a u64
/// Adapted from unsigned-varint's generated read_u64 function at
/// https://github.com/paritytech/unsigned-varint/blob/master/src/io.rs
#[cfg(not(feature = "std"))]
pub(crate) fn read_u64<R: io::Read>(mut r: R) -> Result<u64, Error> {
use unsigned_varint::decode;
let mut b = varint_encode::u64_buffer();
for i in 0..b.len() {
let n = r.read(&mut (b[i..i + 1]))?;
if n == 0 {
return Err(Error::Varint(decode::Error::Insufficient));
} else if decode::is_last(b[i]) {
return Ok(decode::u64(&b[..=i]).unwrap().0);
}
}
Err(Error::Varint(decode::Error::Overflow))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::multihash_impl::Code;
#[test]
fn roundtrip() {
let hash = Code::Sha2_256.digest(b"hello world");
let mut buf = [0u8; 35];
hash.write(&mut buf[..]).unwrap();
let hash2 = Multihash::<32>::read(&buf[..]).unwrap();
assert_eq!(hash, hash2);
}
#[test]
fn test_truncate_down() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(20);
assert_eq!(small.size(), 20);
}
#[test]
fn test_truncate_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let small = hash.truncate(100);
assert_eq!(small.size(), 32);
}
#[test]
fn test_resize_fits() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<32> = hash.resize().unwrap();
}
#[test]
fn test_resize_up() {
let hash = Code::Sha2_256.digest(b"hello world");
let _: Multihash<100> = hash.resize().unwrap();
}
#[test]
fn test_resize_truncate() {
let hash = Code::Sha2_256.digest(b"hello world");
hash.resize::<20>().unwrap_err();
}
#[test]
#[cfg(feature = "scale-codec")]
fn test_scale() {
use parity_scale_codec::{Decode, Encode};
let mh1 = Code::Sha2_256.digest(b"hello world");
// println!("mh1: code = {}, size = {}, digest = {:?}", mh1.code(), mh1.size(), mh1.digest());
let mh1_bytes = mh1.encode();
// println!("Multihash<32>: {}", hex::encode(&mh1_bytes));
let mh2: Multihash<32> = Decode::decode(&mut &mh1_bytes[..]).unwrap();
assert_eq!(mh1, mh2);
let mh3: Multihash<64> = Code::Sha2_256.digest(b"hello world");
// println!("mh3: code = {}, size = {}, digest = {:?}", mh3.code(), mh3.size(), mh3.digest());
let mh3_bytes = mh3.encode();
// println!("Multihash<64>: {}", hex::encode(&mh3_bytes));
let mh4: Multihash<64> = Decode::decode(&mut &mh3_bytes[..]).unwrap();
assert_eq!(mh3, mh4);
assert_eq!(mh1_bytes, mh3_bytes);
}
#[test]
#[cfg(feature = "serde-codec")]
fn test_serde() {
let mh = Multihash::<32>::default();
let bytes = serde_json::to_string(&mh).unwrap();
let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap();
assert_eq!(mh, mh2);
}
#[test]
fn test_eq_sizes() {
let mh1 = Multihash::<32>::default();
let mh2 = Multihash::<64>::default();
assert_eq!(mh1, mh2);
}
}
| {
return Err(Error::InvalidSize(bytes.len().try_into().expect(
"Currently the maximum size is 255, therefore always fits into usize",
)));
} | conditional_block |
clear_bits_geq.rs | use word::{Word, ToWord, UnsignedWord};
/// Clears all bits of `x` at position >= `bit`.
///
/// # Panics
///
/// If `bit >= bit_size()`.
///
/// # Intrinsics:
/// - BMI 2.0: bzhi.
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8);
/// assert_eq!(clear_bits_geq(0b1111_0010u8, 5u8), 0b0001_0010u8);
/// ```
#[inline]
pub fn clear_bits_geq<T: Word, U: UnsignedWord>(x: T, bit: U) -> T {
debug_assert!(T::bit_size() > bit.to());
x.bzhi(bit.to())
}
/// Method version of [`clear_bits_geq`](fn.clear_bits_geq.html).
pub trait ClearBitsGeq {
#[inline]
fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self;
} | impl<T: Word> ClearBitsGeq for T {
#[inline]
fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self {
clear_bits_geq(self, n)
}
} | random_line_split |
|
clear_bits_geq.rs | use word::{Word, ToWord, UnsignedWord};
/// Clears all bits of `x` at position >= `bit`.
///
/// # Panics
///
/// If `bit >= bit_size()`.
///
/// # Intrinsics:
/// - BMI 2.0: bzhi.
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8);
/// assert_eq!(clear_bits_geq(0b1111_0010u8, 5u8), 0b0001_0010u8);
/// ```
#[inline]
pub fn clear_bits_geq<T: Word, U: UnsignedWord>(x: T, bit: U) -> T {
debug_assert!(T::bit_size() > bit.to());
x.bzhi(bit.to())
}
/// Method version of [`clear_bits_geq`](fn.clear_bits_geq.html).
pub trait ClearBitsGeq {
#[inline]
fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self;
}
impl<T: Word> ClearBitsGeq for T {
#[inline]
fn | <U: UnsignedWord>(self, n: U) -> Self {
clear_bits_geq(self, n)
}
}
| clear_bits_geq | identifier_name |
clear_bits_geq.rs | use word::{Word, ToWord, UnsignedWord};
/// Clears all bits of `x` at position >= `bit`.
///
/// # Panics
///
/// If `bit >= bit_size()`.
///
/// # Intrinsics:
/// - BMI 2.0: bzhi.
///
/// # Examples
///
/// ```
/// use bitwise::word::*;
///
/// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8);
/// assert_eq!(clear_bits_geq(0b1111_0010u8, 5u8), 0b0001_0010u8);
/// ```
#[inline]
pub fn clear_bits_geq<T: Word, U: UnsignedWord>(x: T, bit: U) -> T {
debug_assert!(T::bit_size() > bit.to());
x.bzhi(bit.to())
}
/// Method version of [`clear_bits_geq`](fn.clear_bits_geq.html).
pub trait ClearBitsGeq {
#[inline]
fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self;
}
impl<T: Word> ClearBitsGeq for T {
#[inline]
fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self |
}
| {
clear_bits_geq(self, n)
} | identifier_body |
alarm_mutex.rs | use std::io::prelude::*;
use std::time::{Instant, Duration};
use std::cmp::Ord;
use std::thread;
use std::sync::{Mutex, Arc};
struct Alarm {
seconds: Duration,
time: Instant,
message: String,
}
impl Alarm {
fn new(s: u64, m: String) -> Self {
let s = Duration::from_secs(s);
Alarm {
seconds: s,
time: Instant::now() + s,
message: m,
}
}
}
type AlarmList = Arc<Mutex<Vec<Alarm>>>;
fn start_alarm_thread(alarm_list: AlarmList) {
thread::spawn(move || {
loop {
let alarm = alarm_list.lock().unwrap().pop();
match alarm {
Some(a) => {
let now = Instant::now();
if a.time <= now {
thread::yield_now();
} else {
thread::sleep(a.time.duration_since(now));
}
println!("({}) \"{}\"", a.seconds.as_secs(), a.message);
},
None => thread::sleep(Duration::from_secs(1))
}
}
});
}
fn main() {
let alarms = Arc::new(Mutex::new(Vec::<Alarm>::new()));
start_alarm_thread(alarms.clone());
loop {
let mut line = String::new();
print!("Alarm> ");
match std::io::stdout().flush() {
Ok(()) => {},
Err(error) => panic!(format!("error while flushing stdout: {}", error)),
}
match std::io::stdin().read_line(&mut line) {
Ok(_) => {},
Err(error) => panic!(format!("error while reading line: {}", error)),
}
let (seconds, message) = line.split_at(line.find(" ").expect("Bad command"));
let message = message.trim().to_owned();
let seconds = match seconds.parse::<u64>() {
Ok(s) => s,
Err(error) => panic!(format!("failed to parse seconds: {}", error)),
};
match alarms.lock() { | }
}
} | Ok(mut alarm_vec) => {
alarm_vec.push(Alarm::new(seconds, message));
alarm_vec.sort_by(|a, b| b.time.cmp(&a.time));
},
Err(e) => panic!(format!("failed to lock mutex: {}", e)), | random_line_split |
alarm_mutex.rs | use std::io::prelude::*;
use std::time::{Instant, Duration};
use std::cmp::Ord;
use std::thread;
use std::sync::{Mutex, Arc};
struct Alarm {
seconds: Duration,
time: Instant,
message: String,
}
impl Alarm {
fn new(s: u64, m: String) -> Self {
let s = Duration::from_secs(s);
Alarm {
seconds: s,
time: Instant::now() + s,
message: m,
}
}
}
type AlarmList = Arc<Mutex<Vec<Alarm>>>;
fn start_alarm_thread(alarm_list: AlarmList) |
fn main() {
let alarms = Arc::new(Mutex::new(Vec::<Alarm>::new()));
start_alarm_thread(alarms.clone());
loop {
let mut line = String::new();
print!("Alarm> ");
match std::io::stdout().flush() {
Ok(()) => {},
Err(error) => panic!(format!("error while flushing stdout: {}", error)),
}
match std::io::stdin().read_line(&mut line) {
Ok(_) => {},
Err(error) => panic!(format!("error while reading line: {}", error)),
}
let (seconds, message) = line.split_at(line.find(" ").expect("Bad command"));
let message = message.trim().to_owned();
let seconds = match seconds.parse::<u64>() {
Ok(s) => s,
Err(error) => panic!(format!("failed to parse seconds: {}", error)),
};
match alarms.lock() {
Ok(mut alarm_vec) => {
alarm_vec.push(Alarm::new(seconds, message));
alarm_vec.sort_by(|a, b| b.time.cmp(&a.time));
},
Err(e) => panic!(format!("failed to lock mutex: {}", e)),
}
}
}
| {
thread::spawn(move || {
loop {
let alarm = alarm_list.lock().unwrap().pop();
match alarm {
Some(a) => {
let now = Instant::now();
if a.time <= now {
thread::yield_now();
} else {
thread::sleep(a.time.duration_since(now));
}
println!("({}) \"{}\"", a.seconds.as_secs(), a.message);
},
None => thread::sleep(Duration::from_secs(1))
}
}
});
} | identifier_body |
alarm_mutex.rs | use std::io::prelude::*;
use std::time::{Instant, Duration};
use std::cmp::Ord;
use std::thread;
use std::sync::{Mutex, Arc};
struct Alarm {
seconds: Duration,
time: Instant,
message: String,
}
impl Alarm {
fn | (s: u64, m: String) -> Self {
let s = Duration::from_secs(s);
Alarm {
seconds: s,
time: Instant::now() + s,
message: m,
}
}
}
type AlarmList = Arc<Mutex<Vec<Alarm>>>;
fn start_alarm_thread(alarm_list: AlarmList) {
thread::spawn(move || {
loop {
let alarm = alarm_list.lock().unwrap().pop();
match alarm {
Some(a) => {
let now = Instant::now();
if a.time <= now {
thread::yield_now();
} else {
thread::sleep(a.time.duration_since(now));
}
println!("({}) \"{}\"", a.seconds.as_secs(), a.message);
},
None => thread::sleep(Duration::from_secs(1))
}
}
});
}
fn main() {
let alarms = Arc::new(Mutex::new(Vec::<Alarm>::new()));
start_alarm_thread(alarms.clone());
loop {
let mut line = String::new();
print!("Alarm> ");
match std::io::stdout().flush() {
Ok(()) => {},
Err(error) => panic!(format!("error while flushing stdout: {}", error)),
}
match std::io::stdin().read_line(&mut line) {
Ok(_) => {},
Err(error) => panic!(format!("error while reading line: {}", error)),
}
let (seconds, message) = line.split_at(line.find(" ").expect("Bad command"));
let message = message.trim().to_owned();
let seconds = match seconds.parse::<u64>() {
Ok(s) => s,
Err(error) => panic!(format!("failed to parse seconds: {}", error)),
};
match alarms.lock() {
Ok(mut alarm_vec) => {
alarm_vec.push(Alarm::new(seconds, message));
alarm_vec.sort_by(|a, b| b.time.cmp(&a.time));
},
Err(e) => panic!(format!("failed to lock mutex: {}", e)),
}
}
}
| new | identifier_name |
color.rs | //! Color
use image::Rgb;
use math::Vec3f;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum Color {
Black,
White,
Red, | Cyan,
Magenta,
Yellow,
Azure,
Orange,
Gray,
Brightorange,
DarkGreen,
SkyBlue,
Brown,
DarkBrown,
CornflowerBlue,
Rgb(Vec3f),
}
impl Color {
pub fn vec3f(&self) -> Vec3f {
match *self {
Color::Black => Vec3f { x: 0.0, y: 0.0, z: 0.0},
Color::White => Vec3f { x: 1.0, y: 1.0, z: 1.0},
Color::Red => Vec3f { x: 1.0, y: 0.0, z: 0.0},
Color::Green => Vec3f { x: 0.0, y: 1.0, z: 0.0},
Color::Blue => Vec3f { x: 0.0, y: 0.0, z: 1.0},
Color::Cyan => Vec3f { x: 0.0, y: 1.0, z: 1.0 },
Color::Magenta => Vec3f { x: 1.0, y: 0.0, z: 1.0 },
Color::Yellow => Vec3f { x: 1.0, y: 1.0, z: 0.0 },
Color::Azure => Vec3f { x: 0.0, y: 0.5, z: 1.0 },
Color::Orange => Vec3f { x: 1.0, y: 0.5, z: 0.0 },
Color::Gray => Vec3f { x: 0.5, y: 0.5, z: 0.5 },
Color::Brightorange => Vec3f { x: 1.0, y: 0.8, z: 0.0 },
Color::DarkGreen => Vec3f { x: 0.0, y: 0.5, z: 0.0 },
Color::SkyBlue => Vec3f { x: 0.530, y: 0.808, z: 0.922 },
Color::Brown => Vec3f { x: 0.596, y: 0.463, z: 0.329 },
Color::DarkBrown => Vec3f { x: 0.396, y: 0.263, z: 0.129 },
Color::CornflowerBlue => Vec3f { x: 0.392, y: 0.584, z: 0.929 },
Color::Rgb(v) => v,
}
}
pub fn rgb(&self) -> Rgb<u8> {
let vec3f = self.vec3f();
let r = (vec3f.x * 255.0).round().clamp(0.0, 255.0) as u8;
let g = (vec3f.y * 255.0).round().clamp(0.0, 255.0) as u8;
let b = (vec3f.z * 255.0).round().clamp(0.0, 255.0) as u8;
Rgb { data: [r, g, b] }
}
}
impl Default for Color {
fn default() -> Self {
Color::Black
}
} | Green,
Blue, | random_line_split |
color.rs | //! Color
use image::Rgb;
use math::Vec3f;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum Color {
Black,
White,
Red,
Green,
Blue,
Cyan,
Magenta,
Yellow,
Azure,
Orange,
Gray,
Brightorange,
DarkGreen,
SkyBlue,
Brown,
DarkBrown,
CornflowerBlue,
Rgb(Vec3f),
}
impl Color {
pub fn vec3f(&self) -> Vec3f {
match *self {
Color::Black => Vec3f { x: 0.0, y: 0.0, z: 0.0},
Color::White => Vec3f { x: 1.0, y: 1.0, z: 1.0},
Color::Red => Vec3f { x: 1.0, y: 0.0, z: 0.0},
Color::Green => Vec3f { x: 0.0, y: 1.0, z: 0.0},
Color::Blue => Vec3f { x: 0.0, y: 0.0, z: 1.0},
Color::Cyan => Vec3f { x: 0.0, y: 1.0, z: 1.0 },
Color::Magenta => Vec3f { x: 1.0, y: 0.0, z: 1.0 },
Color::Yellow => Vec3f { x: 1.0, y: 1.0, z: 0.0 },
Color::Azure => Vec3f { x: 0.0, y: 0.5, z: 1.0 },
Color::Orange => Vec3f { x: 1.0, y: 0.5, z: 0.0 },
Color::Gray => Vec3f { x: 0.5, y: 0.5, z: 0.5 },
Color::Brightorange => Vec3f { x: 1.0, y: 0.8, z: 0.0 },
Color::DarkGreen => Vec3f { x: 0.0, y: 0.5, z: 0.0 },
Color::SkyBlue => Vec3f { x: 0.530, y: 0.808, z: 0.922 },
Color::Brown => Vec3f { x: 0.596, y: 0.463, z: 0.329 },
Color::DarkBrown => Vec3f { x: 0.396, y: 0.263, z: 0.129 },
Color::CornflowerBlue => Vec3f { x: 0.392, y: 0.584, z: 0.929 },
Color::Rgb(v) => v,
}
}
pub fn rgb(&self) -> Rgb<u8> {
let vec3f = self.vec3f();
let r = (vec3f.x * 255.0).round().clamp(0.0, 255.0) as u8;
let g = (vec3f.y * 255.0).round().clamp(0.0, 255.0) as u8;
let b = (vec3f.z * 255.0).round().clamp(0.0, 255.0) as u8;
Rgb { data: [r, g, b] }
}
}
impl Default for Color {
fn default() -> Self |
}
| {
Color::Black
} | identifier_body |
color.rs | //! Color
use image::Rgb;
use math::Vec3f;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum | {
Black,
White,
Red,
Green,
Blue,
Cyan,
Magenta,
Yellow,
Azure,
Orange,
Gray,
Brightorange,
DarkGreen,
SkyBlue,
Brown,
DarkBrown,
CornflowerBlue,
Rgb(Vec3f),
}
impl Color {
pub fn vec3f(&self) -> Vec3f {
match *self {
Color::Black => Vec3f { x: 0.0, y: 0.0, z: 0.0},
Color::White => Vec3f { x: 1.0, y: 1.0, z: 1.0},
Color::Red => Vec3f { x: 1.0, y: 0.0, z: 0.0},
Color::Green => Vec3f { x: 0.0, y: 1.0, z: 0.0},
Color::Blue => Vec3f { x: 0.0, y: 0.0, z: 1.0},
Color::Cyan => Vec3f { x: 0.0, y: 1.0, z: 1.0 },
Color::Magenta => Vec3f { x: 1.0, y: 0.0, z: 1.0 },
Color::Yellow => Vec3f { x: 1.0, y: 1.0, z: 0.0 },
Color::Azure => Vec3f { x: 0.0, y: 0.5, z: 1.0 },
Color::Orange => Vec3f { x: 1.0, y: 0.5, z: 0.0 },
Color::Gray => Vec3f { x: 0.5, y: 0.5, z: 0.5 },
Color::Brightorange => Vec3f { x: 1.0, y: 0.8, z: 0.0 },
Color::DarkGreen => Vec3f { x: 0.0, y: 0.5, z: 0.0 },
Color::SkyBlue => Vec3f { x: 0.530, y: 0.808, z: 0.922 },
Color::Brown => Vec3f { x: 0.596, y: 0.463, z: 0.329 },
Color::DarkBrown => Vec3f { x: 0.396, y: 0.263, z: 0.129 },
Color::CornflowerBlue => Vec3f { x: 0.392, y: 0.584, z: 0.929 },
Color::Rgb(v) => v,
}
}
pub fn rgb(&self) -> Rgb<u8> {
let vec3f = self.vec3f();
let r = (vec3f.x * 255.0).round().clamp(0.0, 255.0) as u8;
let g = (vec3f.y * 255.0).round().clamp(0.0, 255.0) as u8;
let b = (vec3f.z * 255.0).round().clamp(0.0, 255.0) as u8;
Rgb { data: [r, g, b] }
}
}
impl Default for Color {
fn default() -> Self {
Color::Black
}
}
| Color | identifier_name |
adapters.rs | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use std::thread;
use std::io;
use chain::{self, ChainAdapter};
use core::core::{self, Output};
use core::core::hash::{Hash, Hashed};
use core::core::target::Difficulty;
use p2p::{self, NetAdapter, Server, PeerStore, PeerData, State};
use pool;
use secp::pedersen::Commitment;
use util::OneTime;
use store;
use sync;
use core::global::{MiningParameterMode,MINING_PARAMETER_MODE};
/// Implementation of the NetAdapter for the blockchain. Gets notified when new
/// blocks and transactions are received and forwards to the chain and pool
/// implementations.
pub struct NetToChainAdapter {
chain: Arc<chain::Chain>,
peer_store: Arc<PeerStore>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
syncer: OneTime<Arc<sync::Syncer>>,
}
impl NetAdapter for NetToChainAdapter {
fn total_difficulty(&self) -> Difficulty {
self.chain.total_difficulty()
}
fn transaction_received(&self, tx: core::Transaction) -> Result<(), p2p::Error> {
let source = pool::TxSource {
debug_name: "p2p".to_string(),
identifier: "?.?.?.?".to_string(),
};
if let Err(e) = self.tx_pool.write().unwrap().add_to_memory_pool(source, tx) {
error!("Transaction rejected: {:?}", e);
return Err(p2p::Error::Invalid);
}
Ok(())
}
fn block_received(&self, b: core::Block) -> Result<(), p2p::Error> {
let bhash = b.hash();
debug!("Received block {} from network, going to process.", bhash);
// pushing the new block through the chain pipeline
let res = self.chain.process_block(b, self.chain_opts());
if let Err(e) = res {
debug!("Block {} refused by chain: {:?}", bhash, e);
return Err(p2p::Error::Invalid);
}
if self.syncer.borrow().syncing() {
self.syncer.borrow().block_received(bhash);
}
Ok(())
}
fn headers_received(&self, bhs: Vec<core::BlockHeader>) -> Result<(), p2p::Error> {
// try to add each header to our header chain
let mut added_hs = vec![];
for bh in bhs {
let res = self.chain.process_block_header(&bh, self.chain_opts());
match res {
Ok(_) => {
added_hs.push(bh.hash());
}
Err(chain::Error::Unfit(s)) => {
info!("Received unfit block header {} at {}: {}.",
bh.hash(),
bh.height,
s);
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid Time").into());
}
Err(chain::Error::StoreErr(e)) => {
error!("Store error processing block header {}: {:?}", bh.hash(), e);
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid Header Format").into());
}
Err(e) => {
info!("Invalid block header {}: {:?}.", bh.hash(), e);
return Err(p2p::Error::Invalid);
}
}
}
info!("Added {} headers to the header chain.", added_hs.len());
if self.syncer.borrow().syncing() {
self.syncer.borrow().headers_received(added_hs);
}
Ok(())
}
fn locate_headers(&self, locator: Vec<Hash>) -> Option<Vec<core::BlockHeader>> {
if locator.len() == 0 {
return None;
}
// go through the locator vector and check if we know any of these headers
let known = self.chain.get_block_header(&locator[0]);
let header = match known {
Ok(header) => header,
Err(chain::Error::StoreErr(store::Error::NotFoundErr)) => {
return self.locate_headers(locator[1..].to_vec());
}
Err(e) => {
error!("Could not build header locator: {:?}", e);
return None;
}
};
// looks like we know one, getting as many following headers as allowed
let hh = header.height;
let mut headers = vec![];
for h in (hh + 1)..(hh + (p2p::MAX_BLOCK_HEADERS as u64)) {
let header = self.chain.get_header_by_height(h);
match header {
Ok(head) => headers.push(head),
Err(chain::Error::StoreErr(store::Error::NotFoundErr)) => break,
Err(e) => {
error!("Could not build header locator: {:?}", e);
return None;
}
}
}
Some(headers)
}
/// Gets a full block by its hash.
fn get_block(&self, h: Hash) -> Option<core::Block> {
let b = self.chain.get_block(&h);
match b {
Ok(b) => Some(b),
_ => None,
}
}
/// Find good peers we know with the provided capability and return their
/// addresses.
fn find_peer_addrs(&self, capab: p2p::Capabilities) -> Option<Vec<SocketAddr>> {
let peers = self.peer_store.find_peers(State::Healthy, capab, p2p::MAX_PEER_ADDRS as usize);
debug!("Got {} peer addrs to send.", peers.len());
if peers.len() == 0 { None } else { Some(map_vec!(peers, |p| p.addr)) }
}
/// A list of peers has been received from one of our peers.
fn | (&self, peer_addrs: Vec<SocketAddr>) -> Result<(), p2p::Error> {
debug!("Received {} peer addrs, saving.", peer_addrs.len());
for pa in peer_addrs {
if let Ok(e) = self.peer_store.exists_peer(pa) {
if e {
continue;
}
}
let peer = PeerData {
addr: pa,
capabilities: p2p::UNKNOWN,
user_agent: "".to_string(),
flags: State::Healthy,
};
if let Err(e) = self.peer_store.save_peer(&peer) {
error!("Could not save received peer address: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Could not save recieved peer address").into())
}
}
Ok(())
}
/// Network successfully connected to a peer.
fn peer_connected(&self, pi: &p2p::PeerInfo) {
debug!("Saving newly connected peer {}.", pi.addr);
let peer = PeerData {
addr: pi.addr,
capabilities: pi.capabilities,
user_agent: pi.user_agent.clone(),
flags: State::Healthy,
};
if let Err(e) = self.peer_store.save_peer(&peer) {
error!("Could not save connected peer: {:?}", e);
}
}
}
impl NetToChainAdapter {
pub fn new(chain_ref: Arc<chain::Chain>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
peer_store: Arc<PeerStore>)
-> NetToChainAdapter {
NetToChainAdapter {
chain: chain_ref,
peer_store: peer_store,
tx_pool: tx_pool,
syncer: OneTime::new(),
}
}
/// Start syncing the chain by instantiating and running the Syncer in the
/// background (a new thread is created).
pub fn start_sync(&self, sync: sync::Syncer) {
let arc_sync = Arc::new(sync);
self.syncer.init(arc_sync.clone());
let spawn_result = thread::Builder::new().name("syncer".to_string()).spawn(move || {
let sync_run_result = arc_sync.run();
match sync_run_result {
Ok(_) => {}
Err(_) => {}
}
});
match spawn_result {
Ok(_) => {}
Err(_) => {}
}
}
/// Prepare options for the chain pipeline
fn chain_opts(&self) -> chain::Options {
let opts = if self.syncer.borrow().syncing() {
chain::SYNC
} else {
chain::NONE
};
let param_ref=MINING_PARAMETER_MODE.read().unwrap();
let opts = match *param_ref {
MiningParameterMode::AutomatedTesting => opts | chain::EASY_POW,
MiningParameterMode::UserTesting => opts | chain::EASY_POW,
MiningParameterMode::Production => opts,
};
opts
}
}
/// Implementation of the ChainAdapter for the network. Gets notified when the
/// blockchain accepted a new block, asking the pool to update its state and
/// the network to broadcast the block
pub struct ChainToPoolAndNetAdapter {
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
p2p: OneTime<Arc<Server>>,
}
impl ChainAdapter for ChainToPoolAndNetAdapter {
fn block_accepted(&self, b: &core::Block) {
{
if let Err(e) = self.tx_pool.write().unwrap().reconcile_block(b) {
error!("Pool could not update itself at block {}: {:?}",
b.hash(),
e);
}
}
self.p2p.borrow().broadcast_block(b);
}
}
impl ChainToPoolAndNetAdapter {
pub fn new(tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>)
-> ChainToPoolAndNetAdapter {
ChainToPoolAndNetAdapter {
tx_pool: tx_pool,
p2p: OneTime::new(),
}
}
pub fn init(&self, p2p: Arc<Server>) {
self.p2p.init(p2p);
}
}
/// Implements the view of the blockchain required by the TransactionPool to
/// operate. Mostly needed to break any direct lifecycle or implementation
/// dependency between the pool and the chain.
#[derive(Clone)]
pub struct PoolToChainAdapter {
chain: OneTime<Arc<chain::Chain>>,
}
impl PoolToChainAdapter {
/// Create a new pool adapter
pub fn new() -> PoolToChainAdapter {
PoolToChainAdapter { chain: OneTime::new() }
}
pub fn set_chain(&self, chain_ref: Arc<chain::Chain>) {
self.chain.init(chain_ref);
}
}
impl pool::BlockChain for PoolToChainAdapter {
fn get_unspent(&self, output_ref: &Commitment) -> Option<Output> {
self.chain.borrow().get_unspent(output_ref)
}
}
| peer_addrs_received | identifier_name |
adapters.rs | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use std::thread;
use std::io;
use chain::{self, ChainAdapter};
use core::core::{self, Output};
use core::core::hash::{Hash, Hashed};
use core::core::target::Difficulty;
use p2p::{self, NetAdapter, Server, PeerStore, PeerData, State};
use pool;
use secp::pedersen::Commitment;
use util::OneTime;
use store;
use sync;
use core::global::{MiningParameterMode,MINING_PARAMETER_MODE};
/// Implementation of the NetAdapter for the blockchain. Gets notified when new
/// blocks and transactions are received and forwards to the chain and pool
/// implementations.
pub struct NetToChainAdapter {
chain: Arc<chain::Chain>, | peer_store: Arc<PeerStore>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
syncer: OneTime<Arc<sync::Syncer>>,
}
impl NetAdapter for NetToChainAdapter {
fn total_difficulty(&self) -> Difficulty {
self.chain.total_difficulty()
}
fn transaction_received(&self, tx: core::Transaction) -> Result<(), p2p::Error> {
let source = pool::TxSource {
debug_name: "p2p".to_string(),
identifier: "?.?.?.?".to_string(),
};
if let Err(e) = self.tx_pool.write().unwrap().add_to_memory_pool(source, tx) {
error!("Transaction rejected: {:?}", e);
return Err(p2p::Error::Invalid);
}
Ok(())
}
fn block_received(&self, b: core::Block) -> Result<(), p2p::Error> {
let bhash = b.hash();
debug!("Received block {} from network, going to process.", bhash);
// pushing the new block through the chain pipeline
let res = self.chain.process_block(b, self.chain_opts());
if let Err(e) = res {
debug!("Block {} refused by chain: {:?}", bhash, e);
return Err(p2p::Error::Invalid);
}
if self.syncer.borrow().syncing() {
self.syncer.borrow().block_received(bhash);
}
Ok(())
}
fn headers_received(&self, bhs: Vec<core::BlockHeader>) -> Result<(), p2p::Error> {
// try to add each header to our header chain
let mut added_hs = vec![];
for bh in bhs {
let res = self.chain.process_block_header(&bh, self.chain_opts());
match res {
Ok(_) => {
added_hs.push(bh.hash());
}
Err(chain::Error::Unfit(s)) => {
info!("Received unfit block header {} at {}: {}.",
bh.hash(),
bh.height,
s);
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid Time").into());
}
Err(chain::Error::StoreErr(e)) => {
error!("Store error processing block header {}: {:?}", bh.hash(), e);
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid Header Format").into());
}
Err(e) => {
info!("Invalid block header {}: {:?}.", bh.hash(), e);
return Err(p2p::Error::Invalid);
}
}
}
info!("Added {} headers to the header chain.", added_hs.len());
if self.syncer.borrow().syncing() {
self.syncer.borrow().headers_received(added_hs);
}
Ok(())
}
fn locate_headers(&self, locator: Vec<Hash>) -> Option<Vec<core::BlockHeader>> {
if locator.len() == 0 {
return None;
}
// go through the locator vector and check if we know any of these headers
let known = self.chain.get_block_header(&locator[0]);
let header = match known {
Ok(header) => header,
Err(chain::Error::StoreErr(store::Error::NotFoundErr)) => {
return self.locate_headers(locator[1..].to_vec());
}
Err(e) => {
error!("Could not build header locator: {:?}", e);
return None;
}
};
// looks like we know one, getting as many following headers as allowed
let hh = header.height;
let mut headers = vec![];
for h in (hh + 1)..(hh + (p2p::MAX_BLOCK_HEADERS as u64)) {
let header = self.chain.get_header_by_height(h);
match header {
Ok(head) => headers.push(head),
Err(chain::Error::StoreErr(store::Error::NotFoundErr)) => break,
Err(e) => {
error!("Could not build header locator: {:?}", e);
return None;
}
}
}
Some(headers)
}
/// Gets a full block by its hash.
fn get_block(&self, h: Hash) -> Option<core::Block> {
let b = self.chain.get_block(&h);
match b {
Ok(b) => Some(b),
_ => None,
}
}
/// Find good peers we know with the provided capability and return their
/// addresses.
fn find_peer_addrs(&self, capab: p2p::Capabilities) -> Option<Vec<SocketAddr>> {
let peers = self.peer_store.find_peers(State::Healthy, capab, p2p::MAX_PEER_ADDRS as usize);
debug!("Got {} peer addrs to send.", peers.len());
if peers.len() == 0 { None } else { Some(map_vec!(peers, |p| p.addr)) }
}
/// A list of peers has been received from one of our peers.
fn peer_addrs_received(&self, peer_addrs: Vec<SocketAddr>) -> Result<(), p2p::Error> {
debug!("Received {} peer addrs, saving.", peer_addrs.len());
for pa in peer_addrs {
if let Ok(e) = self.peer_store.exists_peer(pa) {
if e {
continue;
}
}
let peer = PeerData {
addr: pa,
capabilities: p2p::UNKNOWN,
user_agent: "".to_string(),
flags: State::Healthy,
};
if let Err(e) = self.peer_store.save_peer(&peer) {
error!("Could not save received peer address: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Could not save recieved peer address").into())
}
}
Ok(())
}
/// Network successfully connected to a peer.
fn peer_connected(&self, pi: &p2p::PeerInfo) {
debug!("Saving newly connected peer {}.", pi.addr);
let peer = PeerData {
addr: pi.addr,
capabilities: pi.capabilities,
user_agent: pi.user_agent.clone(),
flags: State::Healthy,
};
if let Err(e) = self.peer_store.save_peer(&peer) {
error!("Could not save connected peer: {:?}", e);
}
}
}
impl NetToChainAdapter {
pub fn new(chain_ref: Arc<chain::Chain>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
peer_store: Arc<PeerStore>)
-> NetToChainAdapter {
NetToChainAdapter {
chain: chain_ref,
peer_store: peer_store,
tx_pool: tx_pool,
syncer: OneTime::new(),
}
}
/// Start syncing the chain by instantiating and running the Syncer in the
/// background (a new thread is created).
pub fn start_sync(&self, sync: sync::Syncer) {
let arc_sync = Arc::new(sync);
self.syncer.init(arc_sync.clone());
let spawn_result = thread::Builder::new().name("syncer".to_string()).spawn(move || {
let sync_run_result = arc_sync.run();
match sync_run_result {
Ok(_) => {}
Err(_) => {}
}
});
match spawn_result {
Ok(_) => {}
Err(_) => {}
}
}
/// Prepare options for the chain pipeline
fn chain_opts(&self) -> chain::Options {
let opts = if self.syncer.borrow().syncing() {
chain::SYNC
} else {
chain::NONE
};
let param_ref=MINING_PARAMETER_MODE.read().unwrap();
let opts = match *param_ref {
MiningParameterMode::AutomatedTesting => opts | chain::EASY_POW,
MiningParameterMode::UserTesting => opts | chain::EASY_POW,
MiningParameterMode::Production => opts,
};
opts
}
}
/// Implementation of the ChainAdapter for the network. Gets notified when the
/// blockchain accepted a new block, asking the pool to update its state and
/// the network to broadcast the block
pub struct ChainToPoolAndNetAdapter {
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
p2p: OneTime<Arc<Server>>,
}
impl ChainAdapter for ChainToPoolAndNetAdapter {
fn block_accepted(&self, b: &core::Block) {
{
if let Err(e) = self.tx_pool.write().unwrap().reconcile_block(b) {
error!("Pool could not update itself at block {}: {:?}",
b.hash(),
e);
}
}
self.p2p.borrow().broadcast_block(b);
}
}
impl ChainToPoolAndNetAdapter {
pub fn new(tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>)
-> ChainToPoolAndNetAdapter {
ChainToPoolAndNetAdapter {
tx_pool: tx_pool,
p2p: OneTime::new(),
}
}
pub fn init(&self, p2p: Arc<Server>) {
self.p2p.init(p2p);
}
}
/// Implements the view of the blockchain required by the TransactionPool to
/// operate. Mostly needed to break any direct lifecycle or implementation
/// dependency between the pool and the chain.
#[derive(Clone)]
pub struct PoolToChainAdapter {
chain: OneTime<Arc<chain::Chain>>,
}
impl PoolToChainAdapter {
/// Create a new pool adapter
pub fn new() -> PoolToChainAdapter {
PoolToChainAdapter { chain: OneTime::new() }
}
pub fn set_chain(&self, chain_ref: Arc<chain::Chain>) {
self.chain.init(chain_ref);
}
}
impl pool::BlockChain for PoolToChainAdapter {
fn get_unspent(&self, output_ref: &Commitment) -> Option<Output> {
self.chain.borrow().get_unspent(output_ref)
}
} | random_line_split |
|
adapters.rs | // Copyright 2016 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::net::SocketAddr;
use std::sync::{Arc, RwLock};
use std::thread;
use std::io;
use chain::{self, ChainAdapter};
use core::core::{self, Output};
use core::core::hash::{Hash, Hashed};
use core::core::target::Difficulty;
use p2p::{self, NetAdapter, Server, PeerStore, PeerData, State};
use pool;
use secp::pedersen::Commitment;
use util::OneTime;
use store;
use sync;
use core::global::{MiningParameterMode,MINING_PARAMETER_MODE};
/// Implementation of the NetAdapter for the blockchain. Gets notified when new
/// blocks and transactions are received and forwards to the chain and pool
/// implementations.
pub struct NetToChainAdapter {
chain: Arc<chain::Chain>,
peer_store: Arc<PeerStore>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
syncer: OneTime<Arc<sync::Syncer>>,
}
impl NetAdapter for NetToChainAdapter {
fn total_difficulty(&self) -> Difficulty {
self.chain.total_difficulty()
}
fn transaction_received(&self, tx: core::Transaction) -> Result<(), p2p::Error> {
let source = pool::TxSource {
debug_name: "p2p".to_string(),
identifier: "?.?.?.?".to_string(),
};
if let Err(e) = self.tx_pool.write().unwrap().add_to_memory_pool(source, tx) {
error!("Transaction rejected: {:?}", e);
return Err(p2p::Error::Invalid);
}
Ok(())
}
fn block_received(&self, b: core::Block) -> Result<(), p2p::Error> |
fn headers_received(&self, bhs: Vec<core::BlockHeader>) -> Result<(), p2p::Error> {
// try to add each header to our header chain
let mut added_hs = vec![];
for bh in bhs {
let res = self.chain.process_block_header(&bh, self.chain_opts());
match res {
Ok(_) => {
added_hs.push(bh.hash());
}
Err(chain::Error::Unfit(s)) => {
info!("Received unfit block header {} at {}: {}.",
bh.hash(),
bh.height,
s);
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid Time").into());
}
Err(chain::Error::StoreErr(e)) => {
error!("Store error processing block header {}: {:?}", bh.hash(), e);
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Invalid Header Format").into());
}
Err(e) => {
info!("Invalid block header {}: {:?}.", bh.hash(), e);
return Err(p2p::Error::Invalid);
}
}
}
info!("Added {} headers to the header chain.", added_hs.len());
if self.syncer.borrow().syncing() {
self.syncer.borrow().headers_received(added_hs);
}
Ok(())
}
fn locate_headers(&self, locator: Vec<Hash>) -> Option<Vec<core::BlockHeader>> {
if locator.len() == 0 {
return None;
}
// go through the locator vector and check if we know any of these headers
let known = self.chain.get_block_header(&locator[0]);
let header = match known {
Ok(header) => header,
Err(chain::Error::StoreErr(store::Error::NotFoundErr)) => {
return self.locate_headers(locator[1..].to_vec());
}
Err(e) => {
error!("Could not build header locator: {:?}", e);
return None;
}
};
// looks like we know one, getting as many following headers as allowed
let hh = header.height;
let mut headers = vec![];
for h in (hh + 1)..(hh + (p2p::MAX_BLOCK_HEADERS as u64)) {
let header = self.chain.get_header_by_height(h);
match header {
Ok(head) => headers.push(head),
Err(chain::Error::StoreErr(store::Error::NotFoundErr)) => break,
Err(e) => {
error!("Could not build header locator: {:?}", e);
return None;
}
}
}
Some(headers)
}
/// Gets a full block by its hash.
fn get_block(&self, h: Hash) -> Option<core::Block> {
let b = self.chain.get_block(&h);
match b {
Ok(b) => Some(b),
_ => None,
}
}
/// Find good peers we know with the provided capability and return their
/// addresses.
fn find_peer_addrs(&self, capab: p2p::Capabilities) -> Option<Vec<SocketAddr>> {
let peers = self.peer_store.find_peers(State::Healthy, capab, p2p::MAX_PEER_ADDRS as usize);
debug!("Got {} peer addrs to send.", peers.len());
if peers.len() == 0 { None } else { Some(map_vec!(peers, |p| p.addr)) }
}
/// A list of peers has been received from one of our peers.
fn peer_addrs_received(&self, peer_addrs: Vec<SocketAddr>) -> Result<(), p2p::Error> {
debug!("Received {} peer addrs, saving.", peer_addrs.len());
for pa in peer_addrs {
if let Ok(e) = self.peer_store.exists_peer(pa) {
if e {
continue;
}
}
let peer = PeerData {
addr: pa,
capabilities: p2p::UNKNOWN,
user_agent: "".to_string(),
flags: State::Healthy,
};
if let Err(e) = self.peer_store.save_peer(&peer) {
error!("Could not save received peer address: {:?}", e);
return Err(io::Error::new(io::ErrorKind::InvalidData, "Could not save recieved peer address").into())
}
}
Ok(())
}
/// Network successfully connected to a peer.
fn peer_connected(&self, pi: &p2p::PeerInfo) {
debug!("Saving newly connected peer {}.", pi.addr);
let peer = PeerData {
addr: pi.addr,
capabilities: pi.capabilities,
user_agent: pi.user_agent.clone(),
flags: State::Healthy,
};
if let Err(e) = self.peer_store.save_peer(&peer) {
error!("Could not save connected peer: {:?}", e);
}
}
}
impl NetToChainAdapter {
pub fn new(chain_ref: Arc<chain::Chain>,
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
peer_store: Arc<PeerStore>)
-> NetToChainAdapter {
NetToChainAdapter {
chain: chain_ref,
peer_store: peer_store,
tx_pool: tx_pool,
syncer: OneTime::new(),
}
}
/// Start syncing the chain by instantiating and running the Syncer in the
/// background (a new thread is created).
pub fn start_sync(&self, sync: sync::Syncer) {
let arc_sync = Arc::new(sync);
self.syncer.init(arc_sync.clone());
let spawn_result = thread::Builder::new().name("syncer".to_string()).spawn(move || {
let sync_run_result = arc_sync.run();
match sync_run_result {
Ok(_) => {}
Err(_) => {}
}
});
match spawn_result {
Ok(_) => {}
Err(_) => {}
}
}
/// Prepare options for the chain pipeline
fn chain_opts(&self) -> chain::Options {
let opts = if self.syncer.borrow().syncing() {
chain::SYNC
} else {
chain::NONE
};
let param_ref=MINING_PARAMETER_MODE.read().unwrap();
let opts = match *param_ref {
MiningParameterMode::AutomatedTesting => opts | chain::EASY_POW,
MiningParameterMode::UserTesting => opts | chain::EASY_POW,
MiningParameterMode::Production => opts,
};
opts
}
}
/// Implementation of the ChainAdapter for the network. Gets notified when the
/// blockchain accepted a new block, asking the pool to update its state and
/// the network to broadcast the block
pub struct ChainToPoolAndNetAdapter {
tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>,
p2p: OneTime<Arc<Server>>,
}
impl ChainAdapter for ChainToPoolAndNetAdapter {
fn block_accepted(&self, b: &core::Block) {
{
if let Err(e) = self.tx_pool.write().unwrap().reconcile_block(b) {
error!("Pool could not update itself at block {}: {:?}",
b.hash(),
e);
}
}
self.p2p.borrow().broadcast_block(b);
}
}
impl ChainToPoolAndNetAdapter {
pub fn new(tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>)
-> ChainToPoolAndNetAdapter {
ChainToPoolAndNetAdapter {
tx_pool: tx_pool,
p2p: OneTime::new(),
}
}
pub fn init(&self, p2p: Arc<Server>) {
self.p2p.init(p2p);
}
}
/// Implements the view of the blockchain required by the TransactionPool to
/// operate. Mostly needed to break any direct lifecycle or implementation
/// dependency between the pool and the chain.
#[derive(Clone)]
pub struct PoolToChainAdapter {
chain: OneTime<Arc<chain::Chain>>,
}
impl PoolToChainAdapter {
/// Create a new pool adapter
pub fn new() -> PoolToChainAdapter {
PoolToChainAdapter { chain: OneTime::new() }
}
pub fn set_chain(&self, chain_ref: Arc<chain::Chain>) {
self.chain.init(chain_ref);
}
}
impl pool::BlockChain for PoolToChainAdapter {
fn get_unspent(&self, output_ref: &Commitment) -> Option<Output> {
self.chain.borrow().get_unspent(output_ref)
}
}
| {
let bhash = b.hash();
debug!("Received block {} from network, going to process.", bhash);
// pushing the new block through the chain pipeline
let res = self.chain.process_block(b, self.chain_opts());
if let Err(e) = res {
debug!("Block {} refused by chain: {:?}", bhash, e);
return Err(p2p::Error::Invalid);
}
if self.syncer.borrow().syncing() {
self.syncer.borrow().block_received(bhash);
}
Ok(())
} | identifier_body |
image.rs | use std::io::{ Result, Write};
use core::color::Color;
/// Types that can be converted to a [u8; 4] RGBA.
trait ToRGBA255 {
fn rgba255(&self) -> [u8; 4];
}
impl ToRGBA255 for Color {
fn rgba255(&self) -> [u8; 4] {
let f = |x: f32| (x * 255.0) as u8;
[ f(self.channels()[0]),
f(self.channels()[1]),
f(self.channels()[2]),
f(self.channels()[3]) ]
}
}
// ------------------------
// Image
// ------------------------
pub struct Image {
_data: Vec<Color>,
_width: usize,
_height: usize,
}
impl Image {
pub fn new(w: usize, h: usize) -> Image {
Image {
_data: vec![Color::default(); w * h],
_width: w,
_height: h
}
}
#[inline]
pub fn width(&self) -> usize { self._width }
#[inline]
pub fn height(&self) -> usize { self._height }
pub fn writeppm<T>(&self, out: &mut T) -> Result<()>
where T: Write {
//
try!(write!(out, "P6 {} {} 255 ", self._width, self._height));
for color in &self._data {
let channels = &color.rgba255()[0..3];
try!(out.write_all(&channels));
} | Ok(())
}
pub fn set(&mut self, x: usize, y: usize, c: &Color) {
self._data[x + (y * self._width)] = *c;
}
}
// ------------------------
// Spectrum
// ------------------------ | random_line_split |
|
image.rs | use std::io::{ Result, Write};
use core::color::Color;
/// Types that can be converted to a [u8; 4] RGBA.
trait ToRGBA255 {
fn rgba255(&self) -> [u8; 4];
}
impl ToRGBA255 for Color {
fn rgba255(&self) -> [u8; 4] {
let f = |x: f32| (x * 255.0) as u8;
[ f(self.channels()[0]),
f(self.channels()[1]),
f(self.channels()[2]),
f(self.channels()[3]) ]
}
}
// ------------------------
// Image
// ------------------------
pub struct Image {
_data: Vec<Color>,
_width: usize,
_height: usize,
}
impl Image {
pub fn new(w: usize, h: usize) -> Image {
Image {
_data: vec![Color::default(); w * h],
_width: w,
_height: h
}
}
#[inline]
pub fn width(&self) -> usize { self._width }
#[inline]
pub fn height(&self) -> usize { self._height }
pub fn | <T>(&self, out: &mut T) -> Result<()>
where T: Write {
//
try!(write!(out, "P6 {} {} 255 ", self._width, self._height));
for color in &self._data {
let channels = &color.rgba255()[0..3];
try!(out.write_all(&channels));
}
Ok(())
}
pub fn set(&mut self, x: usize, y: usize, c: &Color) {
self._data[x + (y * self._width)] = *c;
}
}
// ------------------------
// Spectrum
// ------------------------
| writeppm | identifier_name |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn | () {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
/// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in 1i32..bound {
if x % i == 0 {
factors.push(i);
factors.push(x / i);
}
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| main | identifier_name |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
} | /// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in 1i32..bound {
if x % i == 0 {
factors.push(i);
factors.push(x / i);
}
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
} | random_line_split |
|
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
/// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in 1i32..bound {
if x % i == 0 |
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| {
factors.push(i);
factors.push(x / i);
} | conditional_block |
factor_int.rs | // http://rosettacode.org/wiki/Factors_of_an_integer
fn main() |
/// Compute the factors of an integer
/// This method uses a simple check on each value between 1 and sqrt(x) to find
/// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in 1i32..bound {
if x % i == 0 {
factors.push(i);
factors.push(x / i);
}
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
} | identifier_body |
origin.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 std::sync::Arc;
use url::{Host, Url};
use url::Origin as UrlOrigin;
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
#[derive(HeapSizeOf, JSTraceable)]
pub struct Origin {
#[ignore_heap_size_of = "Arc<T> has unclear ownership semantics"]
inner: Arc<UrlOrigin>,
}
impl Origin {
/// Create a new origin comprising a unique, opaque identifier.
pub fn opaque_identifier() -> Origin {
Origin {
inner: Arc::new(UrlOrigin::new_opaque()),
}
}
/// Create a new origin for the given URL.
pub fn new(url: &Url) -> Origin {
Origin {
inner: Arc::new(url.origin()),
}
}
/// Does this origin represent a host/scheme/port tuple?
pub fn is_scheme_host_port_tuple(&self) -> bool {
self.inner.is_tuple()
}
/// Return the host associated with this origin.
pub fn host(&self) -> Option<&Host<String>> {
match *self.inner {
UrlOrigin::Tuple(_, ref host, _) => Some(host),
UrlOrigin::Opaque(..) => None,
}
}
/// https://html.spec.whatwg.org/multipage/#same-origin
pub fn same_origin(&self, other: &Origin) -> bool {
self.inner == other.inner
}
pub fn copy(&self) -> Origin {
Origin {
inner: Arc::new((*self.inner).clone()),
}
}
pub fn | (&self) -> Origin {
Origin {
inner: self.inner.clone(),
}
}
}
| alias | identifier_name |
origin.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 std::sync::Arc;
use url::{Host, Url};
use url::Origin as UrlOrigin;
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
#[derive(HeapSizeOf, JSTraceable)]
pub struct Origin {
#[ignore_heap_size_of = "Arc<T> has unclear ownership semantics"]
inner: Arc<UrlOrigin>,
}
impl Origin {
/// Create a new origin comprising a unique, opaque identifier.
pub fn opaque_identifier() -> Origin {
Origin {
inner: Arc::new(UrlOrigin::new_opaque()),
}
}
/// Create a new origin for the given URL.
pub fn new(url: &Url) -> Origin {
Origin {
inner: Arc::new(url.origin()),
}
}
/// Does this origin represent a host/scheme/port tuple?
pub fn is_scheme_host_port_tuple(&self) -> bool {
self.inner.is_tuple()
}
/// Return the host associated with this origin.
pub fn host(&self) -> Option<&Host<String>> |
/// https://html.spec.whatwg.org/multipage/#same-origin
pub fn same_origin(&self, other: &Origin) -> bool {
self.inner == other.inner
}
pub fn copy(&self) -> Origin {
Origin {
inner: Arc::new((*self.inner).clone()),
}
}
pub fn alias(&self) -> Origin {
Origin {
inner: self.inner.clone(),
}
}
}
| {
match *self.inner {
UrlOrigin::Tuple(_, ref host, _) => Some(host),
UrlOrigin::Opaque(..) => None,
}
} | identifier_body |
origin.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 std::sync::Arc;
use url::{Host, Url};
use url::Origin as UrlOrigin;
/// A representation of an [origin](https://html.spec.whatwg.org/multipage/#origin-2).
#[derive(HeapSizeOf, JSTraceable)]
pub struct Origin {
#[ignore_heap_size_of = "Arc<T> has unclear ownership semantics"]
inner: Arc<UrlOrigin>,
}
impl Origin {
/// Create a new origin comprising a unique, opaque identifier.
pub fn opaque_identifier() -> Origin {
Origin {
inner: Arc::new(UrlOrigin::new_opaque()),
}
}
/// Create a new origin for the given URL.
pub fn new(url: &Url) -> Origin {
Origin {
inner: Arc::new(url.origin()),
}
}
/// Does this origin represent a host/scheme/port tuple?
pub fn is_scheme_host_port_tuple(&self) -> bool {
self.inner.is_tuple()
}
/// Return the host associated with this origin.
pub fn host(&self) -> Option<&Host<String>> {
match *self.inner {
UrlOrigin::Tuple(_, ref host, _) => Some(host),
UrlOrigin::Opaque(..) => None,
}
}
/// https://html.spec.whatwg.org/multipage/#same-origin
pub fn same_origin(&self, other: &Origin) -> bool {
self.inner == other.inner
}
pub fn copy(&self) -> Origin {
Origin {
inner: Arc::new((*self.inner).clone()),
}
}
pub fn alias(&self) -> Origin {
Origin {
inner: self.inner.clone(),
} | } | } | random_line_split |
vec.rs | use std::vec::IntoIter;
use std::marker::PhantomData;
use super::{Set, SetManager};
use super::sort::SortManager;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
IndexOutOfRange { index: usize, total: usize },
}
pub struct VecSetIter<T, E> {
iter: Option<IntoIter<T>>,
_marker: PhantomData<E>,
}
impl<T, E> Iterator for VecSetIter<T, E> {
type Item = Result<T, E>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(mut iter) = self.iter.take() {
match iter.next() {
None => None,
Some(value) => {
self.iter = Some(iter);
Some(Ok(value))
}
}
} else {
None
}
}
}
impl<T> Set for Vec<T> where T: Sized {
type T = T;
type E = Error;
type I = VecSetIter<Self::T, Self::E>;
fn size(&self) -> usize {
self.len()
}
fn get(&self, index: usize) -> Result<&Self::T, Self::E> {
let slice: &[T] = self;
slice.get(index).ok_or(Error::IndexOutOfRange { index: index, total: self.len(), })
}
fn add(&mut self, item: Self::T) -> Result<(), Self::E> {
self.push(item);
Ok(())
}
fn into_iter(self) -> Self::I {
VecSetIter {
iter: Some(IntoIterator::into_iter(self)),
_marker: PhantomData,
}
}
}
pub struct Manager<T> {
_marker: PhantomData<T>,
}
impl<T> Manager<T> {
pub fn new() -> Manager<T> {
Manager {
_marker: PhantomData,
}
}
}
impl<T> SetManager for Manager<T> {
type S = Vec<T>;
type E = ();
fn make_set(&mut self, size_hint: Option<usize>) -> Result<Self::S, Self::E> {
Ok(match size_hint {
Some(hint) => Vec::with_capacity(hint),
None => Vec::new(),
})
}
fn reserve(&mut self, set: &mut Self::S, additional: usize) -> Result<(), Self::E> {
Ok(set.reserve(additional))
}
}
impl SortManager for Manager<usize> {
type S = Vec<usize>;
type E = ();
fn sort<SF>(&mut self, set: &mut Self::S, pred: SF) -> Result<(), Self::E> where SF: Fn(usize, usize) -> bool {
use std::cmp::Ordering;
set.sort_by(|&a, &b| if pred(a, b) {
Ordering::Less
} else {
Ordering::Greater
});
Ok(())
} | }
#[cfg(test)]
mod tests {
use super::{Error, Manager};
use super::super::{Set, SetManager};
fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> {
assert_eq!(set.size(), 0);
assert_eq!(set.add(0), Ok(()));
assert_eq!(set.size(), 1);
assert_eq!(set.add(1), Ok(()));
assert_eq!(set.size(), 2);
assert_eq!(set.get(0), Ok(&0));
assert_eq!(set.get(1), Ok(&1));
assert_eq!(set.get(2), Err(Error::IndexOutOfRange { index: 2, total: 2, }));
assert_eq!(set.into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1]);
}
#[test]
fn basic() {
run_basic(Manager::new().make_set(None).unwrap());
}
} | random_line_split |
|
vec.rs | use std::vec::IntoIter;
use std::marker::PhantomData;
use super::{Set, SetManager};
use super::sort::SortManager;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
IndexOutOfRange { index: usize, total: usize },
}
pub struct VecSetIter<T, E> {
iter: Option<IntoIter<T>>,
_marker: PhantomData<E>,
}
impl<T, E> Iterator for VecSetIter<T, E> {
type Item = Result<T, E>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(mut iter) = self.iter.take() {
match iter.next() {
None => None,
Some(value) => {
self.iter = Some(iter);
Some(Ok(value))
}
}
} else {
None
}
}
}
impl<T> Set for Vec<T> where T: Sized {
type T = T;
type E = Error;
type I = VecSetIter<Self::T, Self::E>;
fn size(&self) -> usize {
self.len()
}
fn get(&self, index: usize) -> Result<&Self::T, Self::E> {
let slice: &[T] = self;
slice.get(index).ok_or(Error::IndexOutOfRange { index: index, total: self.len(), })
}
fn add(&mut self, item: Self::T) -> Result<(), Self::E> {
self.push(item);
Ok(())
}
fn into_iter(self) -> Self::I {
VecSetIter {
iter: Some(IntoIterator::into_iter(self)),
_marker: PhantomData,
}
}
}
pub struct | <T> {
_marker: PhantomData<T>,
}
impl<T> Manager<T> {
pub fn new() -> Manager<T> {
Manager {
_marker: PhantomData,
}
}
}
impl<T> SetManager for Manager<T> {
type S = Vec<T>;
type E = ();
fn make_set(&mut self, size_hint: Option<usize>) -> Result<Self::S, Self::E> {
Ok(match size_hint {
Some(hint) => Vec::with_capacity(hint),
None => Vec::new(),
})
}
fn reserve(&mut self, set: &mut Self::S, additional: usize) -> Result<(), Self::E> {
Ok(set.reserve(additional))
}
}
impl SortManager for Manager<usize> {
type S = Vec<usize>;
type E = ();
fn sort<SF>(&mut self, set: &mut Self::S, pred: SF) -> Result<(), Self::E> where SF: Fn(usize, usize) -> bool {
use std::cmp::Ordering;
set.sort_by(|&a, &b| if pred(a, b) {
Ordering::Less
} else {
Ordering::Greater
});
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Error, Manager};
use super::super::{Set, SetManager};
fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> {
assert_eq!(set.size(), 0);
assert_eq!(set.add(0), Ok(()));
assert_eq!(set.size(), 1);
assert_eq!(set.add(1), Ok(()));
assert_eq!(set.size(), 2);
assert_eq!(set.get(0), Ok(&0));
assert_eq!(set.get(1), Ok(&1));
assert_eq!(set.get(2), Err(Error::IndexOutOfRange { index: 2, total: 2, }));
assert_eq!(set.into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1]);
}
#[test]
fn basic() {
run_basic(Manager::new().make_set(None).unwrap());
}
}
| Manager | identifier_name |
vec.rs | use std::vec::IntoIter;
use std::marker::PhantomData;
use super::{Set, SetManager};
use super::sort::SortManager;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
IndexOutOfRange { index: usize, total: usize },
}
pub struct VecSetIter<T, E> {
iter: Option<IntoIter<T>>,
_marker: PhantomData<E>,
}
impl<T, E> Iterator for VecSetIter<T, E> {
type Item = Result<T, E>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(mut iter) = self.iter.take() {
match iter.next() {
None => None,
Some(value) => {
self.iter = Some(iter);
Some(Ok(value))
}
}
} else {
None
}
}
}
impl<T> Set for Vec<T> where T: Sized {
type T = T;
type E = Error;
type I = VecSetIter<Self::T, Self::E>;
fn size(&self) -> usize {
self.len()
}
fn get(&self, index: usize) -> Result<&Self::T, Self::E> {
let slice: &[T] = self;
slice.get(index).ok_or(Error::IndexOutOfRange { index: index, total: self.len(), })
}
fn add(&mut self, item: Self::T) -> Result<(), Self::E> {
self.push(item);
Ok(())
}
fn into_iter(self) -> Self::I {
VecSetIter {
iter: Some(IntoIterator::into_iter(self)),
_marker: PhantomData,
}
}
}
pub struct Manager<T> {
_marker: PhantomData<T>,
}
impl<T> Manager<T> {
pub fn new() -> Manager<T> {
Manager {
_marker: PhantomData,
}
}
}
impl<T> SetManager for Manager<T> {
type S = Vec<T>;
type E = ();
fn make_set(&mut self, size_hint: Option<usize>) -> Result<Self::S, Self::E> {
Ok(match size_hint {
Some(hint) => Vec::with_capacity(hint),
None => Vec::new(),
})
}
fn reserve(&mut self, set: &mut Self::S, additional: usize) -> Result<(), Self::E> {
Ok(set.reserve(additional))
}
}
impl SortManager for Manager<usize> {
type S = Vec<usize>;
type E = ();
fn sort<SF>(&mut self, set: &mut Self::S, pred: SF) -> Result<(), Self::E> where SF: Fn(usize, usize) -> bool {
use std::cmp::Ordering;
set.sort_by(|&a, &b| if pred(a, b) | else {
Ordering::Greater
});
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{Error, Manager};
use super::super::{Set, SetManager};
fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> {
assert_eq!(set.size(), 0);
assert_eq!(set.add(0), Ok(()));
assert_eq!(set.size(), 1);
assert_eq!(set.add(1), Ok(()));
assert_eq!(set.size(), 2);
assert_eq!(set.get(0), Ok(&0));
assert_eq!(set.get(1), Ok(&1));
assert_eq!(set.get(2), Err(Error::IndexOutOfRange { index: 2, total: 2, }));
assert_eq!(set.into_iter().map(|r| r.unwrap()).collect::<Vec<_>>(), vec![0, 1]);
}
#[test]
fn basic() {
run_basic(Manager::new().make_set(None).unwrap());
}
}
| {
Ordering::Less
} | conditional_block |
pinsrb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pinsrb_1() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EBP)), operand3: Some(Literal8(106)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 245, 106], OperandSize::Dword)
}
fn pinsrb_2() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledDisplaced(ESI, Two, 1749524261, Some(OperandSize::Byte), None)), operand3: Some(Literal8(109)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 44, 117, 37, 159, 71, 104, 109], OperandSize::Dword)
}
fn pinsrb_3() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(Direct(EDI)), operand3: Some(Literal8(12)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 239, 12], OperandSize::Qword)
}
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 4, 189, 39, 125, 163, 75, 38], OperandSize::Qword)
}
| pinsrb_4 | identifier_name |
pinsrb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pinsrb_1() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EBP)), operand3: Some(Literal8(106)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 245, 106], OperandSize::Dword)
}
fn pinsrb_2() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledDisplaced(ESI, Two, 1749524261, Some(OperandSize::Byte), None)), operand3: Some(Literal8(109)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 44, 117, 37, 159, 71, 104, 109], OperandSize::Dword)
}
fn pinsrb_3() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(Direct(EDI)), operand3: Some(Literal8(12)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 239, 12], OperandSize::Qword)
}
fn pinsrb_4() { | } | run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 4, 189, 39, 125, 163, 75, 38], OperandSize::Qword) | random_line_split |
pinsrb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn pinsrb_1() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EBP)), operand3: Some(Literal8(106)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 245, 106], OperandSize::Dword)
}
fn pinsrb_2() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledDisplaced(ESI, Two, 1749524261, Some(OperandSize::Byte), None)), operand3: Some(Literal8(109)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 44, 117, 37, 159, 71, 104, 109], OperandSize::Dword)
}
fn pinsrb_3() |
fn pinsrb_4() {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 4, 189, 39, 125, 163, 75, 38], OperandSize::Qword)
}
| {
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(Direct(EDI)), operand3: Some(Literal8(12)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 239, 12], OperandSize::Qword)
} | identifier_body |
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![allow(non_camel_case_types)]
use clidispatch::io::IO;
use cpython::*;
use cpython_ext::wrap_pyio;
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "commands"].join(".");
let m = PyModule::new(py, &name)?;
m.add(
py,
"run",
py_fn!(
py,
run_py(
args: Vec<String>,
fin: PyObject,
fout: PyObject,
ferr: Option<PyObject> = None
)
),
)?;
Ok(m)
}
fn | (
_py: Python,
args: Vec<String>,
fin: PyObject,
fout: PyObject,
ferr: Option<PyObject>,
) -> PyResult<i32> {
let fin = wrap_pyio(fin);
let fout = wrap_pyio(fout);
let ferr = ferr.map(wrap_pyio);
let mut io = IO::new(fin, fout, ferr);
Ok(hgcommands::run_command(args, &mut io))
}
| run_py | identifier_name |
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![allow(non_camel_case_types)]
use clidispatch::io::IO;
use cpython::*;
use cpython_ext::wrap_pyio;
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
let name = [package, "commands"].join(".");
let m = PyModule::new(py, &name)?;
m.add(
py,
"run",
py_fn!(
py,
run_py(
args: Vec<String>,
fin: PyObject,
fout: PyObject,
ferr: Option<PyObject> = None
)
),
)?;
Ok(m)
}
fn run_py(
_py: Python,
args: Vec<String>,
fin: PyObject,
fout: PyObject,
ferr: Option<PyObject>,
) -> PyResult<i32> | {
let fin = wrap_pyio(fin);
let fout = wrap_pyio(fout);
let ferr = ferr.map(wrap_pyio);
let mut io = IO::new(fin, fout, ferr);
Ok(hgcommands::run_command(args, &mut io))
} | identifier_body |
|
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![allow(non_camel_case_types)]
| let name = [package, "commands"].join(".");
let m = PyModule::new(py, &name)?;
m.add(
py,
"run",
py_fn!(
py,
run_py(
args: Vec<String>,
fin: PyObject,
fout: PyObject,
ferr: Option<PyObject> = None
)
),
)?;
Ok(m)
}
fn run_py(
_py: Python,
args: Vec<String>,
fin: PyObject,
fout: PyObject,
ferr: Option<PyObject>,
) -> PyResult<i32> {
let fin = wrap_pyio(fin);
let fout = wrap_pyio(fout);
let ferr = ferr.map(wrap_pyio);
let mut io = IO::new(fin, fout, ferr);
Ok(hgcommands::run_command(args, &mut io))
} | use clidispatch::io::IO;
use cpython::*;
use cpython_ext::wrap_pyio;
pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> { | random_line_split |
dom_html_paragraph_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use DOMElement;
use DOMEventTarget;
use DOMHTMLElement;
use DOMNode;
use DOMObject;
use glib::GString;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_sys;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use webkit2_webextension_sys;
glib_wrapper! {
pub struct DOMHTMLParagraphElement(Object<webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, webkit2_webextension_sys::WebKitDOMHTMLParagraphElementClass, DOMHTMLParagraphElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_type(),
}
}
pub const NONE_DOMHTML_PARAGRAPH_ELEMENT: Option<&DOMHTMLParagraphElement> = None;
pub trait DOMHTMLParagraphElementExt:'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_align(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_align(&self, value: &str);
fn connect_property_align_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLParagraphElement>> DOMHTMLParagraphElementExt for O {
fn get_align(&self) -> Option<GString> {
unsafe {
from_glib_full(webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_align(self.as_ref().to_glib_none().0))
}
}
fn set_align(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_paragraph_element_set_align(self.as_ref().to_glib_none().0, value.to_glib_none().0);
}
}
fn connect_property_align_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) +'static>(this: *mut webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer)
where P: IsA<DOMHTMLParagraphElement>
{
let f: &F = &*(f as *const F);
f(&DOMHTMLParagraphElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::align\0".as_ptr() as *const _,
Some(transmute(notify_align_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
impl fmt::Display for DOMHTMLParagraphElement {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMHTMLParagraphElement")
}
}
| fmt | identifier_name |
dom_html_paragraph_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use DOMElement;
use DOMEventTarget;
use DOMHTMLElement;
use DOMNode;
use DOMObject;
use glib::GString;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_sys;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use webkit2_webextension_sys;
glib_wrapper! {
pub struct DOMHTMLParagraphElement(Object<webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, webkit2_webextension_sys::WebKitDOMHTMLParagraphElementClass, DOMHTMLParagraphElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_type(),
}
}
pub const NONE_DOMHTML_PARAGRAPH_ELEMENT: Option<&DOMHTMLParagraphElement> = None;
pub trait DOMHTMLParagraphElementExt:'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_align(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_align(&self, value: &str);
fn connect_property_align_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLParagraphElement>> DOMHTMLParagraphElementExt for O {
fn get_align(&self) -> Option<GString> |
fn set_align(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_paragraph_element_set_align(self.as_ref().to_glib_none().0, value.to_glib_none().0);
}
}
fn connect_property_align_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) +'static>(this: *mut webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer)
where P: IsA<DOMHTMLParagraphElement>
{
let f: &F = &*(f as *const F);
f(&DOMHTMLParagraphElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::align\0".as_ptr() as *const _,
Some(transmute(notify_align_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
impl fmt::Display for DOMHTMLParagraphElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMHTMLParagraphElement")
}
}
| {
unsafe {
from_glib_full(webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_align(self.as_ref().to_glib_none().0))
}
} | identifier_body |
dom_html_paragraph_element.rs | // This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use DOMElement;
use DOMEventTarget;
use DOMHTMLElement;
use DOMNode;
use DOMObject;
use glib::GString;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_sys;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
use webkit2_webextension_sys;
glib_wrapper! {
pub struct DOMHTMLParagraphElement(Object<webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, webkit2_webextension_sys::WebKitDOMHTMLParagraphElementClass, DOMHTMLParagraphElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
get_type => || webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_type(),
}
}
pub const NONE_DOMHTML_PARAGRAPH_ELEMENT: Option<&DOMHTMLParagraphElement> = None;
pub trait DOMHTMLParagraphElementExt:'static {
#[cfg_attr(feature = "v2_22", deprecated)]
fn get_align(&self) -> Option<GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
fn set_align(&self, value: &str);
fn connect_property_align_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMHTMLParagraphElement>> DOMHTMLParagraphElementExt for O {
fn get_align(&self) -> Option<GString> {
unsafe {
from_glib_full(webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_align(self.as_ref().to_glib_none().0))
}
}
fn set_align(&self, value: &str) {
unsafe {
webkit2_webextension_sys::webkit_dom_html_paragraph_element_set_align(self.as_ref().to_glib_none().0, value.to_glib_none().0);
}
}
| unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) +'static>(this: *mut webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer)
where P: IsA<DOMHTMLParagraphElement>
{
let f: &F = &*(f as *const F);
f(&DOMHTMLParagraphElement::from_glib_borrow(this).unsafe_cast())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::align\0".as_ptr() as *const _,
Some(transmute(notify_align_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
impl fmt::Display for DOMHTMLParagraphElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMHTMLParagraphElement")
}
} | fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { | random_line_split |
pick_from_list.rs | use std::{io,fs};
use std::io::{Read, Write, BufReader, BufRead};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::str::FromStr;
use std::env;
fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> {
let process = try!(cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn());
{
let mut process_in = process.stdin.unwrap();
for item in items {
try!(process_in.write_all((item.as_ref().replace("\n", "") + "\n").as_bytes()))
}
}
let mut result = String::new();
try!(process.stdout.unwrap().read_to_string(&mut result));
Ok(result.replace("\n", ""))
}
fn read_parse<T>(tty: &mut File, prompt: &str, min: T, max: T) -> io::Result<T> where T: FromStr + Ord {
try!(tty.write_all(prompt.as_bytes()));
let mut reader = BufReader::new(tty);
let mut result = String::new();
try!(reader.read_line(&mut result));
match result.replace("\n", "").parse::<T>() {
Ok(x) => if x >= min && x <= max { Ok(x) } else { read_parse(reader.into_inner(), prompt, min, max) },
_ => read_parse(reader.into_inner(), prompt, min, max)
}
}
fn pick_from_list_internal<T: AsRef<str>>(items: &[T], prompt: &str) -> io::Result<String> {
let mut tty = try!(OpenOptions::new().read(true).write(true).open("/dev/tty"));
let pad_len = ((items.len() as f32).log10().floor() + 1.0) as usize;
for (i, item) in items.iter().enumerate() {
try!(tty.write_all(format!("{1:0$}. {2}\n", pad_len, i + 1, item.as_ref().replace("\n", "")).as_bytes()))
}
let idx = try!(read_parse::<usize>(&mut tty, prompt, 1, items.len())) - 1;
Ok(items[idx].as_ref().to_string())
}
/// Asks the user to select an item from a list.
///
/// If `cmd` is `Some`, an external menu program will be used.
/// Otherwise, a built-in simple number-based command-line menu (on `/dev/tty`) will be used, with a `prompt`.
///
/// Note: an external program might return something that's not in the list!
pub fn pick_from_list<T: AsRef<str>>(cmd: Option<&mut Command>, items: &[T], prompt: &str) -> io::Result<String> {
match cmd {
Some(command) => pick_from_list_external(command, items),
None => pick_from_list_internal(items, prompt), | }
}
/// Asks the user to select a file from the filesystem, starting at directory `path`.
///
/// Requires a function that produces the command as `cmd`, because commands aren't cloneable.
pub fn pick_file<C>(cmd: C, path: PathBuf) -> io::Result<PathBuf> where C: Fn() -> Option<Command> {
let mut curpath = path;
loop {
let mut items = try!(fs::read_dir(curpath.clone())).map(|e| {
e.ok().and_then(|ee| ee.file_name().to_str().map(|eee| eee.to_string())).unwrap_or("***PATH ENCODING ERROR***".to_string())
}).collect::<Vec<_>>();
items.insert(0, "..".to_string());
items.insert(0, ".".to_string());
let pick = try!(pick_from_list(cmd().as_mut(), &items[..], curpath.to_str().unwrap_or("***PATH ENCODING ERROR***")));
let newpath = try!(curpath.join(pick).canonicalize());
if let Ok(metadata) = newpath.metadata() {
if metadata.is_dir() {
curpath = newpath;
} else {
return Ok(newpath);
}
}
}
}
/// Returns the user's preferred menu program from the `MENU` environment variable if it exists.
///
/// Use `.as_mut()` on the returned value to turn in into an `Option<&mut Command>`.
pub fn default_menu_cmd() -> Option<Command> {
env::var_os("MENU").map(|s| Command::new(s))
} | random_line_split |
|
pick_from_list.rs | use std::{io,fs};
use std::io::{Read, Write, BufReader, BufRead};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::str::FromStr;
use std::env;
fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> {
let process = try!(cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn());
{
let mut process_in = process.stdin.unwrap();
for item in items {
try!(process_in.write_all((item.as_ref().replace("\n", "") + "\n").as_bytes()))
}
}
let mut result = String::new();
try!(process.stdout.unwrap().read_to_string(&mut result));
Ok(result.replace("\n", ""))
}
fn read_parse<T>(tty: &mut File, prompt: &str, min: T, max: T) -> io::Result<T> where T: FromStr + Ord {
try!(tty.write_all(prompt.as_bytes()));
let mut reader = BufReader::new(tty);
let mut result = String::new();
try!(reader.read_line(&mut result));
match result.replace("\n", "").parse::<T>() {
Ok(x) => if x >= min && x <= max { Ok(x) } else { read_parse(reader.into_inner(), prompt, min, max) },
_ => read_parse(reader.into_inner(), prompt, min, max)
}
}
fn pick_from_list_internal<T: AsRef<str>>(items: &[T], prompt: &str) -> io::Result<String> {
let mut tty = try!(OpenOptions::new().read(true).write(true).open("/dev/tty"));
let pad_len = ((items.len() as f32).log10().floor() + 1.0) as usize;
for (i, item) in items.iter().enumerate() {
try!(tty.write_all(format!("{1:0$}. {2}\n", pad_len, i + 1, item.as_ref().replace("\n", "")).as_bytes()))
}
let idx = try!(read_parse::<usize>(&mut tty, prompt, 1, items.len())) - 1;
Ok(items[idx].as_ref().to_string())
}
/// Asks the user to select an item from a list.
///
/// If `cmd` is `Some`, an external menu program will be used.
/// Otherwise, a built-in simple number-based command-line menu (on `/dev/tty`) will be used, with a `prompt`.
///
/// Note: an external program might return something that's not in the list!
pub fn pick_from_list<T: AsRef<str>>(cmd: Option<&mut Command>, items: &[T], prompt: &str) -> io::Result<String> {
match cmd {
Some(command) => pick_from_list_external(command, items),
None => pick_from_list_internal(items, prompt),
}
}
/// Asks the user to select a file from the filesystem, starting at directory `path`.
///
/// Requires a function that produces the command as `cmd`, because commands aren't cloneable.
pub fn pick_file<C>(cmd: C, path: PathBuf) -> io::Result<PathBuf> where C: Fn() -> Option<Command> {
let mut curpath = path;
loop {
let mut items = try!(fs::read_dir(curpath.clone())).map(|e| {
e.ok().and_then(|ee| ee.file_name().to_str().map(|eee| eee.to_string())).unwrap_or("***PATH ENCODING ERROR***".to_string())
}).collect::<Vec<_>>();
items.insert(0, "..".to_string());
items.insert(0, ".".to_string());
let pick = try!(pick_from_list(cmd().as_mut(), &items[..], curpath.to_str().unwrap_or("***PATH ENCODING ERROR***")));
let newpath = try!(curpath.join(pick).canonicalize());
if let Ok(metadata) = newpath.metadata() {
if metadata.is_dir() | else {
return Ok(newpath);
}
}
}
}
/// Returns the user's preferred menu program from the `MENU` environment variable if it exists.
///
/// Use `.as_mut()` on the returned value to turn in into an `Option<&mut Command>`.
pub fn default_menu_cmd() -> Option<Command> {
env::var_os("MENU").map(|s| Command::new(s))
}
| {
curpath = newpath;
} | conditional_block |
pick_from_list.rs | use std::{io,fs};
use std::io::{Read, Write, BufReader, BufRead};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::str::FromStr;
use std::env;
fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> {
let process = try!(cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn());
{
let mut process_in = process.stdin.unwrap();
for item in items {
try!(process_in.write_all((item.as_ref().replace("\n", "") + "\n").as_bytes()))
}
}
let mut result = String::new();
try!(process.stdout.unwrap().read_to_string(&mut result));
Ok(result.replace("\n", ""))
}
fn read_parse<T>(tty: &mut File, prompt: &str, min: T, max: T) -> io::Result<T> where T: FromStr + Ord {
try!(tty.write_all(prompt.as_bytes()));
let mut reader = BufReader::new(tty);
let mut result = String::new();
try!(reader.read_line(&mut result));
match result.replace("\n", "").parse::<T>() {
Ok(x) => if x >= min && x <= max { Ok(x) } else { read_parse(reader.into_inner(), prompt, min, max) },
_ => read_parse(reader.into_inner(), prompt, min, max)
}
}
fn pick_from_list_internal<T: AsRef<str>>(items: &[T], prompt: &str) -> io::Result<String> {
let mut tty = try!(OpenOptions::new().read(true).write(true).open("/dev/tty"));
let pad_len = ((items.len() as f32).log10().floor() + 1.0) as usize;
for (i, item) in items.iter().enumerate() {
try!(tty.write_all(format!("{1:0$}. {2}\n", pad_len, i + 1, item.as_ref().replace("\n", "")).as_bytes()))
}
let idx = try!(read_parse::<usize>(&mut tty, prompt, 1, items.len())) - 1;
Ok(items[idx].as_ref().to_string())
}
/// Asks the user to select an item from a list.
///
/// If `cmd` is `Some`, an external menu program will be used.
/// Otherwise, a built-in simple number-based command-line menu (on `/dev/tty`) will be used, with a `prompt`.
///
/// Note: an external program might return something that's not in the list!
pub fn pick_from_list<T: AsRef<str>>(cmd: Option<&mut Command>, items: &[T], prompt: &str) -> io::Result<String> {
match cmd {
Some(command) => pick_from_list_external(command, items),
None => pick_from_list_internal(items, prompt),
}
}
/// Asks the user to select a file from the filesystem, starting at directory `path`.
///
/// Requires a function that produces the command as `cmd`, because commands aren't cloneable.
pub fn pick_file<C>(cmd: C, path: PathBuf) -> io::Result<PathBuf> where C: Fn() -> Option<Command> {
let mut curpath = path;
loop {
let mut items = try!(fs::read_dir(curpath.clone())).map(|e| {
e.ok().and_then(|ee| ee.file_name().to_str().map(|eee| eee.to_string())).unwrap_or("***PATH ENCODING ERROR***".to_string())
}).collect::<Vec<_>>();
items.insert(0, "..".to_string());
items.insert(0, ".".to_string());
let pick = try!(pick_from_list(cmd().as_mut(), &items[..], curpath.to_str().unwrap_or("***PATH ENCODING ERROR***")));
let newpath = try!(curpath.join(pick).canonicalize());
if let Ok(metadata) = newpath.metadata() {
if metadata.is_dir() {
curpath = newpath;
} else {
return Ok(newpath);
}
}
}
}
/// Returns the user's preferred menu program from the `MENU` environment variable if it exists.
///
/// Use `.as_mut()` on the returned value to turn in into an `Option<&mut Command>`.
pub fn default_menu_cmd() -> Option<Command> | {
env::var_os("MENU").map(|s| Command::new(s))
} | identifier_body |
|
pick_from_list.rs | use std::{io,fs};
use std::io::{Read, Write, BufReader, BufRead};
use std::fs::{File, OpenOptions};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::str::FromStr;
use std::env;
fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> {
let process = try!(cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).spawn());
{
let mut process_in = process.stdin.unwrap();
for item in items {
try!(process_in.write_all((item.as_ref().replace("\n", "") + "\n").as_bytes()))
}
}
let mut result = String::new();
try!(process.stdout.unwrap().read_to_string(&mut result));
Ok(result.replace("\n", ""))
}
fn read_parse<T>(tty: &mut File, prompt: &str, min: T, max: T) -> io::Result<T> where T: FromStr + Ord {
try!(tty.write_all(prompt.as_bytes()));
let mut reader = BufReader::new(tty);
let mut result = String::new();
try!(reader.read_line(&mut result));
match result.replace("\n", "").parse::<T>() {
Ok(x) => if x >= min && x <= max { Ok(x) } else { read_parse(reader.into_inner(), prompt, min, max) },
_ => read_parse(reader.into_inner(), prompt, min, max)
}
}
fn | <T: AsRef<str>>(items: &[T], prompt: &str) -> io::Result<String> {
let mut tty = try!(OpenOptions::new().read(true).write(true).open("/dev/tty"));
let pad_len = ((items.len() as f32).log10().floor() + 1.0) as usize;
for (i, item) in items.iter().enumerate() {
try!(tty.write_all(format!("{1:0$}. {2}\n", pad_len, i + 1, item.as_ref().replace("\n", "")).as_bytes()))
}
let idx = try!(read_parse::<usize>(&mut tty, prompt, 1, items.len())) - 1;
Ok(items[idx].as_ref().to_string())
}
/// Asks the user to select an item from a list.
///
/// If `cmd` is `Some`, an external menu program will be used.
/// Otherwise, a built-in simple number-based command-line menu (on `/dev/tty`) will be used, with a `prompt`.
///
/// Note: an external program might return something that's not in the list!
pub fn pick_from_list<T: AsRef<str>>(cmd: Option<&mut Command>, items: &[T], prompt: &str) -> io::Result<String> {
match cmd {
Some(command) => pick_from_list_external(command, items),
None => pick_from_list_internal(items, prompt),
}
}
/// Asks the user to select a file from the filesystem, starting at directory `path`.
///
/// Requires a function that produces the command as `cmd`, because commands aren't cloneable.
pub fn pick_file<C>(cmd: C, path: PathBuf) -> io::Result<PathBuf> where C: Fn() -> Option<Command> {
let mut curpath = path;
loop {
let mut items = try!(fs::read_dir(curpath.clone())).map(|e| {
e.ok().and_then(|ee| ee.file_name().to_str().map(|eee| eee.to_string())).unwrap_or("***PATH ENCODING ERROR***".to_string())
}).collect::<Vec<_>>();
items.insert(0, "..".to_string());
items.insert(0, ".".to_string());
let pick = try!(pick_from_list(cmd().as_mut(), &items[..], curpath.to_str().unwrap_or("***PATH ENCODING ERROR***")));
let newpath = try!(curpath.join(pick).canonicalize());
if let Ok(metadata) = newpath.metadata() {
if metadata.is_dir() {
curpath = newpath;
} else {
return Ok(newpath);
}
}
}
}
/// Returns the user's preferred menu program from the `MENU` environment variable if it exists.
///
/// Use `.as_mut()` on the returned value to turn in into an `Option<&mut Command>`.
pub fn default_menu_cmd() -> Option<Command> {
env::var_os("MENU").map(|s| Command::new(s))
}
| pick_from_list_internal | identifier_name |
whitespace.rs | use nom::multispace;
named!(comment<&str, &str>, delimited!(
tag!("/*"),
take_until!("*/"),
tag!("*/")
));
named!(space_or_comment<&str, &str>, alt!(
multispace | comment
));
named!(pub space<&str, ()>, fold_many1!(
space_or_comment,
(),
|_, _| ()
));
named!(pub opt_space<&str, ()>, fold_many0!(
space_or_comment,
(),
|_, _| ()
));
/// Transforms a parser to automatically consume whitespace and comments
/// between each token.
macro_rules! wsc(
($i:expr, $($args:tt)*) => ({
use $crate::whitespace::opt_space;
sep!($i, opt_space, $($args)*)
})
);
#[cfg(test)]
mod tests {
use whitespace::opt_space;
fn is_good(c: char) -> bool {
c.is_alphanumeric() || c == '/' || c == '*'
}
#[test]
fn test_wsc() |
#[test]
fn test_opt_space() {
named!(test_parser<&str, &str>, do_parse!(
tag!("(")
>>
opt_space
>>
res: take_while!(is_good)
>>
opt_space
>>
tag!(")")
>>
(res)
));
let input1 = "( a )";
assert_done!(test_parser(input1));
let input2 = "(a)";
assert_done!(test_parser(input2));
}
}
| {
named!(test_parser<&str, Vec<&str>>, wsc!(many0!(
take_while!(is_good)
)));
let input = "a /* b */ c / * d /**/ e ";
assert_done!(test_parser(input), vec!["a", "c", "/", "*", "d", "e"]);
} | identifier_body |
whitespace.rs | use nom::multispace;
named!(comment<&str, &str>, delimited!(
tag!("/*"),
take_until!("*/"),
tag!("*/")
));
named!(space_or_comment<&str, &str>, alt!(
multispace | comment
));
named!(pub space<&str, ()>, fold_many1!(
space_or_comment,
(),
|_, _| ()
));
named!(pub opt_space<&str, ()>, fold_many0!(
space_or_comment,
(),
|_, _| ()
));
/// Transforms a parser to automatically consume whitespace and comments
/// between each token.
macro_rules! wsc(
($i:expr, $($args:tt)*) => ({
use $crate::whitespace::opt_space;
sep!($i, opt_space, $($args)*)
})
);
#[cfg(test)]
mod tests {
use whitespace::opt_space;
fn is_good(c: char) -> bool {
c.is_alphanumeric() || c == '/' || c == '*'
}
#[test]
fn test_wsc() {
named!(test_parser<&str, Vec<&str>>, wsc!(many0!(
take_while!(is_good)
)));
let input = "a /* b */ c / * d /**/ e ";
assert_done!(test_parser(input), vec!["a", "c", "/", "*", "d", "e"]);
}
#[test]
fn | () {
named!(test_parser<&str, &str>, do_parse!(
tag!("(")
>>
opt_space
>>
res: take_while!(is_good)
>>
opt_space
>>
tag!(")")
>>
(res)
));
let input1 = "( a )";
assert_done!(test_parser(input1));
let input2 = "(a)";
assert_done!(test_parser(input2));
}
}
| test_opt_space | identifier_name |
whitespace.rs | use nom::multispace;
named!(comment<&str, &str>, delimited!(
tag!("/*"),
take_until!("*/"),
tag!("*/")
));
named!(space_or_comment<&str, &str>, alt!(
multispace | comment |
named!(pub space<&str, ()>, fold_many1!(
space_or_comment,
(),
|_, _| ()
));
named!(pub opt_space<&str, ()>, fold_many0!(
space_or_comment,
(),
|_, _| ()
));
/// Transforms a parser to automatically consume whitespace and comments
/// between each token.
macro_rules! wsc(
($i:expr, $($args:tt)*) => ({
use $crate::whitespace::opt_space;
sep!($i, opt_space, $($args)*)
})
);
#[cfg(test)]
mod tests {
use whitespace::opt_space;
fn is_good(c: char) -> bool {
c.is_alphanumeric() || c == '/' || c == '*'
}
#[test]
fn test_wsc() {
named!(test_parser<&str, Vec<&str>>, wsc!(many0!(
take_while!(is_good)
)));
let input = "a /* b */ c / * d /**/ e ";
assert_done!(test_parser(input), vec!["a", "c", "/", "*", "d", "e"]);
}
#[test]
fn test_opt_space() {
named!(test_parser<&str, &str>, do_parse!(
tag!("(")
>>
opt_space
>>
res: take_while!(is_good)
>>
opt_space
>>
tag!(")")
>>
(res)
));
let input1 = "( a )";
assert_done!(test_parser(input1));
let input2 = "(a)";
assert_done!(test_parser(input2));
}
} | )); | random_line_split |
main.rs | #[macro_use]
extern crate clap;
extern crate sdl2;
mod yuv;
mod sdlui;
use std::process::exit;
use sdlui::{Channel, SdlUi, ViewFrame};
pub fn main() | });
let height: u32 = matches
.value_of("HEIGHT")
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid height: {}", e);
exit(1)
});
let multiplier: u32 = matches
.value_of("MULTIPLIER")
.unwrap_or("5")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid multiplier: {}", e);
exit(1)
});
let view: ViewFrame = matches
.value_of("VIEW")
.unwrap_or("a")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid frame: {}", e);
exit(1)
});
let channel: Channel = matches
.value_of("CHANNEL")
.unwrap_or("c")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid channel: {}", e);
exit(1)
});
let file_a = matches.value_of("FILEA").unwrap();
let file_b = matches.value_of("FILEB").unwrap();
let mut ui_handle = SdlUi::new(width, height, file_a, file_b).unwrap_or_else(|e| {
eprintln!("{}", e);
exit(1)
});
ui_handle.set_diff_multiplier(multiplier);
ui_handle.set_view(view);
ui_handle.set_channel(channel);
ui_handle.run();
}
| {
let matches = clap_app!(yuvdiff =>
(version: "0.1")
(about: "Diff YUV files")
(@arg WIDTH: -w --width +takes_value +required "Width")
(@arg HEIGHT: -h --height +takes_value +required "Height")
(@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)")
(@arg VIEW: -v --view +takes_value "View (a, b, d)")
(@arg FILEA: +required "YUV file A")
(@arg FILEB: +required "YUV file B")
(@arg MULTIPLIER: -m --multiplier +takes_value "Diff multiplier (default: 5)")
).get_matches();
let width: u32 = matches
.value_of("WIDTH")
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid width: {}", e);
exit(1) | identifier_body |
main.rs | #[macro_use]
extern crate clap;
extern crate sdl2;
mod yuv;
mod sdlui;
use std::process::exit;
use sdlui::{Channel, SdlUi, ViewFrame};
pub fn main() {
let matches = clap_app!(yuvdiff =>
(version: "0.1")
(about: "Diff YUV files")
(@arg WIDTH: -w --width +takes_value +required "Width")
(@arg HEIGHT: -h --height +takes_value +required "Height")
(@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)")
(@arg VIEW: -v --view +takes_value "View (a, b, d)")
(@arg FILEA: +required "YUV file A")
(@arg FILEB: +required "YUV file B")
(@arg MULTIPLIER: -m --multiplier +takes_value "Diff multiplier (default: 5)")
).get_matches();
let width: u32 = matches
.value_of("WIDTH")
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid width: {}", e);
exit(1)
});
let height: u32 = matches
.value_of("HEIGHT")
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid height: {}", e); | .unwrap_or("5")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid multiplier: {}", e);
exit(1)
});
let view: ViewFrame = matches
.value_of("VIEW")
.unwrap_or("a")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid frame: {}", e);
exit(1)
});
let channel: Channel = matches
.value_of("CHANNEL")
.unwrap_or("c")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid channel: {}", e);
exit(1)
});
let file_a = matches.value_of("FILEA").unwrap();
let file_b = matches.value_of("FILEB").unwrap();
let mut ui_handle = SdlUi::new(width, height, file_a, file_b).unwrap_or_else(|e| {
eprintln!("{}", e);
exit(1)
});
ui_handle.set_diff_multiplier(multiplier);
ui_handle.set_view(view);
ui_handle.set_channel(channel);
ui_handle.run();
} | exit(1)
});
let multiplier: u32 = matches
.value_of("MULTIPLIER") | random_line_split |
main.rs | #[macro_use]
extern crate clap;
extern crate sdl2;
mod yuv;
mod sdlui;
use std::process::exit;
use sdlui::{Channel, SdlUi, ViewFrame};
pub fn | () {
let matches = clap_app!(yuvdiff =>
(version: "0.1")
(about: "Diff YUV files")
(@arg WIDTH: -w --width +takes_value +required "Width")
(@arg HEIGHT: -h --height +takes_value +required "Height")
(@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)")
(@arg VIEW: -v --view +takes_value "View (a, b, d)")
(@arg FILEA: +required "YUV file A")
(@arg FILEB: +required "YUV file B")
(@arg MULTIPLIER: -m --multiplier +takes_value "Diff multiplier (default: 5)")
).get_matches();
let width: u32 = matches
.value_of("WIDTH")
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid width: {}", e);
exit(1)
});
let height: u32 = matches
.value_of("HEIGHT")
.unwrap()
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid height: {}", e);
exit(1)
});
let multiplier: u32 = matches
.value_of("MULTIPLIER")
.unwrap_or("5")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid multiplier: {}", e);
exit(1)
});
let view: ViewFrame = matches
.value_of("VIEW")
.unwrap_or("a")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid frame: {}", e);
exit(1)
});
let channel: Channel = matches
.value_of("CHANNEL")
.unwrap_or("c")
.parse()
.unwrap_or_else(|e| {
eprintln!("Invalid channel: {}", e);
exit(1)
});
let file_a = matches.value_of("FILEA").unwrap();
let file_b = matches.value_of("FILEB").unwrap();
let mut ui_handle = SdlUi::new(width, height, file_a, file_b).unwrap_or_else(|e| {
eprintln!("{}", e);
exit(1)
});
ui_handle.set_diff_multiplier(multiplier);
ui_handle.set_view(view);
ui_handle.set_channel(channel);
ui_handle.run();
}
| main | identifier_name |
parser.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/. */
//! The context within which CSS code is parsed.
use context::QuirksMode;
use cssparser::{Parser, SourceLocation, UnicodeRange};
use error_reporting::{ParseErrorReporter, ContextualParseError};
use style_traits::{OneOrMoreSeparated, ParseError, ParsingMode, Separator};
#[cfg(feature = "gecko")]
use style_traits::{PARSING_MODE_DEFAULT, PARSING_MODE_ALLOW_UNITLESS_LENGTH, PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES};
use stylesheets::{CssRuleType, Origin, UrlExtraData, Namespaces};
/// Asserts that all ParsingMode flags have a matching ParsingMode value in gecko.
#[cfg(feature = "gecko")]
#[inline]
pub fn assert_parsing_mode_match() {
use gecko_bindings::structs;
macro_rules! check_parsing_modes {
( $( $a:ident => $b:ident ),*, ) => {
if cfg!(debug_assertions) {
let mut modes = ParsingMode::all();
$(
assert_eq!(structs::$a as usize, $b.bits() as usize, stringify!($b));
modes.remove($b);
)*
assert_eq!(modes, ParsingMode::empty(), "all ParsingMode bits should have an assertion");
}
}
}
check_parsing_modes! {
ParsingMode_Default => PARSING_MODE_DEFAULT,
ParsingMode_AllowUnitlessLength => PARSING_MODE_ALLOW_UNITLESS_LENGTH,
ParsingMode_AllowAllNumericValues => PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES,
}
}
/// The data that the parser needs from outside in order to parse a stylesheet.
pub struct ParserContext<'a> {
/// The `Origin` of the stylesheet, whether it's a user, author or
/// user-agent stylesheet.
pub stylesheet_origin: Origin,
/// The extra data we need for resolving url values.
pub url_data: &'a UrlExtraData,
/// An error reporter to report syntax errors.
pub error_reporter: &'a ParseErrorReporter,
/// The current rule type, if any.
pub rule_type: Option<CssRuleType>,
/// Line number offsets for inline stylesheets
pub line_number_offset: u64,
/// The mode to use when parsing.
pub parsing_mode: ParsingMode,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// The currently active namespaces.
pub namespaces: Option<&'a Namespaces>,
}
impl<'a> ParserContext<'a> {
/// Create a parser context.
pub fn new(stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode)
-> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: rule_type,
line_number_offset: 0u64,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Create a parser context for on-the-fly parsing in CSSOM
pub fn new_for_cssom(
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
Self::new(Origin::Author, url_data, error_reporter, rule_type, parsing_mode, quirks_mode)
}
/// Create a parser context based on a previous context, but with a modified rule type.
pub fn new_with_rule_type(
context: &'a ParserContext,
rule_type: Option<CssRuleType>
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: context.stylesheet_origin,
url_data: context.url_data,
error_reporter: context.error_reporter,
rule_type: rule_type,
line_number_offset: context.line_number_offset,
parsing_mode: context.parsing_mode,
quirks_mode: context.quirks_mode,
namespaces: context.namespaces,
}
}
/// Create a parser context for inline CSS which accepts additional line offset argument.
pub fn new_with_line_number_offset(
stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
line_number_offset: u64,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: None,
line_number_offset: line_number_offset,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Get the rule type, which assumes that one is available.
pub fn rule_type(&self) -> CssRuleType {
self.rule_type.expect("Rule type expected, but none was found.")
}
/// Record a CSS parse error with this context’s error reporting.
pub fn log_css_error(&self, location: SourceLocation, error: ContextualParseError) {
let location = SourceLocation {
line: location.line + self.line_number_offset as u32,
column: location.column,
};
self.error_reporter.report_error(self.url_data, location, error)
}
}
// XXXManishearth Replace all specified value parse impls with impls of this
// trait. This will make it easy to write more generic values in the future.
/// A trait to abstract parsing of a specified value given a `ParserContext` and
/// CSS input.
pub trait Parse : Sized {
/// Parse a value of this type.
///
/// Returns an error on failure.
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>>;
}
impl<T> Parse for Vec<T>
where
T: Parse + OneOrMoreSeparated,
<T as OneOrMoreSeparated>::S: Separator,
{
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
<T as OneOrMoreSeparated>::S::parse(input, |i| T::parse(context, i))
} | UnicodeRange::parse(input).map_err(|e| e.into())
}
} | }
impl Parse for UnicodeRange {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> { | random_line_split |
parser.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/. */
//! The context within which CSS code is parsed.
use context::QuirksMode;
use cssparser::{Parser, SourceLocation, UnicodeRange};
use error_reporting::{ParseErrorReporter, ContextualParseError};
use style_traits::{OneOrMoreSeparated, ParseError, ParsingMode, Separator};
#[cfg(feature = "gecko")]
use style_traits::{PARSING_MODE_DEFAULT, PARSING_MODE_ALLOW_UNITLESS_LENGTH, PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES};
use stylesheets::{CssRuleType, Origin, UrlExtraData, Namespaces};
/// Asserts that all ParsingMode flags have a matching ParsingMode value in gecko.
#[cfg(feature = "gecko")]
#[inline]
pub fn assert_parsing_mode_match() {
use gecko_bindings::structs;
macro_rules! check_parsing_modes {
( $( $a:ident => $b:ident ),*, ) => {
if cfg!(debug_assertions) {
let mut modes = ParsingMode::all();
$(
assert_eq!(structs::$a as usize, $b.bits() as usize, stringify!($b));
modes.remove($b);
)*
assert_eq!(modes, ParsingMode::empty(), "all ParsingMode bits should have an assertion");
}
}
}
check_parsing_modes! {
ParsingMode_Default => PARSING_MODE_DEFAULT,
ParsingMode_AllowUnitlessLength => PARSING_MODE_ALLOW_UNITLESS_LENGTH,
ParsingMode_AllowAllNumericValues => PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES,
}
}
/// The data that the parser needs from outside in order to parse a stylesheet.
pub struct ParserContext<'a> {
/// The `Origin` of the stylesheet, whether it's a user, author or
/// user-agent stylesheet.
pub stylesheet_origin: Origin,
/// The extra data we need for resolving url values.
pub url_data: &'a UrlExtraData,
/// An error reporter to report syntax errors.
pub error_reporter: &'a ParseErrorReporter,
/// The current rule type, if any.
pub rule_type: Option<CssRuleType>,
/// Line number offsets for inline stylesheets
pub line_number_offset: u64,
/// The mode to use when parsing.
pub parsing_mode: ParsingMode,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// The currently active namespaces.
pub namespaces: Option<&'a Namespaces>,
}
impl<'a> ParserContext<'a> {
/// Create a parser context.
pub fn new(stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode)
-> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: rule_type,
line_number_offset: 0u64,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Create a parser context for on-the-fly parsing in CSSOM
pub fn new_for_cssom(
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
Self::new(Origin::Author, url_data, error_reporter, rule_type, parsing_mode, quirks_mode)
}
/// Create a parser context based on a previous context, but with a modified rule type.
pub fn new_with_rule_type(
context: &'a ParserContext,
rule_type: Option<CssRuleType>
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: context.stylesheet_origin,
url_data: context.url_data,
error_reporter: context.error_reporter,
rule_type: rule_type,
line_number_offset: context.line_number_offset,
parsing_mode: context.parsing_mode,
quirks_mode: context.quirks_mode,
namespaces: context.namespaces,
}
}
/// Create a parser context for inline CSS which accepts additional line offset argument.
pub fn new_with_line_number_offset(
stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
line_number_offset: u64,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: None,
line_number_offset: line_number_offset,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Get the rule type, which assumes that one is available.
pub fn rule_type(&self) -> CssRuleType {
self.rule_type.expect("Rule type expected, but none was found.")
}
/// Record a CSS parse error with this context’s error reporting.
pub fn log_css_error(&self, location: SourceLocation, error: ContextualParseError) {
let location = SourceLocation {
line: location.line + self.line_number_offset as u32,
column: location.column,
};
self.error_reporter.report_error(self.url_data, location, error)
}
}
// XXXManishearth Replace all specified value parse impls with impls of this
// trait. This will make it easy to write more generic values in the future.
/// A trait to abstract parsing of a specified value given a `ParserContext` and
/// CSS input.
pub trait Parse : Sized {
/// Parse a value of this type.
///
/// Returns an error on failure.
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>>;
}
impl<T> Parse for Vec<T>
where
T: Parse + OneOrMoreSeparated,
<T as OneOrMoreSeparated>::S: Separator,
{
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
|
impl Parse for UnicodeRange {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
UnicodeRange::parse(input).map_err(|e| e.into())
}
}
| <T as OneOrMoreSeparated>::S::parse(input, |i| T::parse(context, i))
}
} | identifier_body |
parser.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/. */
//! The context within which CSS code is parsed.
use context::QuirksMode;
use cssparser::{Parser, SourceLocation, UnicodeRange};
use error_reporting::{ParseErrorReporter, ContextualParseError};
use style_traits::{OneOrMoreSeparated, ParseError, ParsingMode, Separator};
#[cfg(feature = "gecko")]
use style_traits::{PARSING_MODE_DEFAULT, PARSING_MODE_ALLOW_UNITLESS_LENGTH, PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES};
use stylesheets::{CssRuleType, Origin, UrlExtraData, Namespaces};
/// Asserts that all ParsingMode flags have a matching ParsingMode value in gecko.
#[cfg(feature = "gecko")]
#[inline]
pub fn assert_parsing_mode_match() {
use gecko_bindings::structs;
macro_rules! check_parsing_modes {
( $( $a:ident => $b:ident ),*, ) => {
if cfg!(debug_assertions) {
let mut modes = ParsingMode::all();
$(
assert_eq!(structs::$a as usize, $b.bits() as usize, stringify!($b));
modes.remove($b);
)*
assert_eq!(modes, ParsingMode::empty(), "all ParsingMode bits should have an assertion");
}
}
}
check_parsing_modes! {
ParsingMode_Default => PARSING_MODE_DEFAULT,
ParsingMode_AllowUnitlessLength => PARSING_MODE_ALLOW_UNITLESS_LENGTH,
ParsingMode_AllowAllNumericValues => PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES,
}
}
/// The data that the parser needs from outside in order to parse a stylesheet.
pub struct ParserContext<'a> {
/// The `Origin` of the stylesheet, whether it's a user, author or
/// user-agent stylesheet.
pub stylesheet_origin: Origin,
/// The extra data we need for resolving url values.
pub url_data: &'a UrlExtraData,
/// An error reporter to report syntax errors.
pub error_reporter: &'a ParseErrorReporter,
/// The current rule type, if any.
pub rule_type: Option<CssRuleType>,
/// Line number offsets for inline stylesheets
pub line_number_offset: u64,
/// The mode to use when parsing.
pub parsing_mode: ParsingMode,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// The currently active namespaces.
pub namespaces: Option<&'a Namespaces>,
}
impl<'a> ParserContext<'a> {
/// Create a parser context.
pub fn new(stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode)
-> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: rule_type,
line_number_offset: 0u64,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Create a parser context for on-the-fly parsing in CSSOM
pub fn new_for_cssom(
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
Self::new(Origin::Author, url_data, error_reporter, rule_type, parsing_mode, quirks_mode)
}
/// Create a parser context based on a previous context, but with a modified rule type.
pub fn new_with_rule_type(
context: &'a ParserContext,
rule_type: Option<CssRuleType>
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: context.stylesheet_origin,
url_data: context.url_data,
error_reporter: context.error_reporter,
rule_type: rule_type,
line_number_offset: context.line_number_offset,
parsing_mode: context.parsing_mode,
quirks_mode: context.quirks_mode,
namespaces: context.namespaces,
}
}
/// Create a parser context for inline CSS which accepts additional line offset argument.
pub fn | (
stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
line_number_offset: u64,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: None,
line_number_offset: line_number_offset,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Get the rule type, which assumes that one is available.
pub fn rule_type(&self) -> CssRuleType {
self.rule_type.expect("Rule type expected, but none was found.")
}
/// Record a CSS parse error with this context’s error reporting.
pub fn log_css_error(&self, location: SourceLocation, error: ContextualParseError) {
let location = SourceLocation {
line: location.line + self.line_number_offset as u32,
column: location.column,
};
self.error_reporter.report_error(self.url_data, location, error)
}
}
// XXXManishearth Replace all specified value parse impls with impls of this
// trait. This will make it easy to write more generic values in the future.
/// A trait to abstract parsing of a specified value given a `ParserContext` and
/// CSS input.
pub trait Parse : Sized {
/// Parse a value of this type.
///
/// Returns an error on failure.
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>>;
}
impl<T> Parse for Vec<T>
where
T: Parse + OneOrMoreSeparated,
<T as OneOrMoreSeparated>::S: Separator,
{
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
<T as OneOrMoreSeparated>::S::parse(input, |i| T::parse(context, i))
}
}
impl Parse for UnicodeRange {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
UnicodeRange::parse(input).map_err(|e| e.into())
}
}
| new_with_line_number_offset | identifier_name |
any_ambiguous_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [
AnyAmbiguousAliases::NONE,
AnyAmbiguousAliases::M1,
AnyAmbiguousAliases::M2,
AnyAmbiguousAliases::M3,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct AnyAmbiguousAliases(pub u8);
#[allow(non_upper_case_globals)]
impl AnyAmbiguousAliases {
pub const NONE: Self = Self(0);
pub const M1: Self = Self(1);
pub const M2: Self = Self(2);
pub const M3: Self = Self(3);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 3;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::M1,
Self::M2,
Self::M3,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M1 => Some("M1"),
Self::M2 => Some("M2"),
Self::M3 => Some("M3"),
_ => None,
}
}
}
impl std::fmt::Debug for AnyAmbiguousAliases {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyAmbiguousAliases {
type Output = AnyAmbiguousAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
}
}
impl flatbuffers::EndianScalar for AnyAmbiguousAliases {
#[inline]
fn to_little_endian(self) -> Self {
let b = u8::to_le(self.0);
Self(b)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self {
let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for AnyAmbiguousAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {}
pub struct AnyAmbiguousAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum AnyAmbiguousAliasesT {
NONE,
M1(Box<MonsterT>),
M2(Box<MonsterT>),
M3(Box<MonsterT>),
}
impl Default for AnyAmbiguousAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyAmbiguousAliasesT {
pub fn | (&self) -> AnyAmbiguousAliases {
match self {
Self::NONE => AnyAmbiguousAliases::NONE,
Self::M1(_) => AnyAmbiguousAliases::M1,
Self::M2(_) => AnyAmbiguousAliases::M2,
Self::M3(_) => AnyAmbiguousAliases::M3,
}
}
pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::M1(v) => Some(v.pack(fbb).as_union_value()),
Self::M2(v) => Some(v.pack(fbb).as_union_value()),
Self::M3(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m1(&mut self) -> Option<Box<MonsterT>> {
if let Self::M1(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M1(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m1(&self) -> Option<&MonsterT> {
if let Self::M1(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M1(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m2(&mut self) -> Option<Box<MonsterT>> {
if let Self::M2(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M2(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m2(&self) -> Option<&MonsterT> {
if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m3(&mut self) -> Option<Box<MonsterT>> {
if let Self::M3(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M3(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m3(&self) -> Option<&MonsterT> {
if let Self::M3(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M3(v) = self { Some(v.as_mut()) } else { None }
}
}
| any_ambiguous_aliases_type | identifier_name |
any_ambiguous_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
#[allow(non_camel_case_types)]
pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [
AnyAmbiguousAliases::NONE,
AnyAmbiguousAliases::M1,
AnyAmbiguousAliases::M2,
AnyAmbiguousAliases::M3,
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct AnyAmbiguousAliases(pub u8);
#[allow(non_upper_case_globals)]
impl AnyAmbiguousAliases {
pub const NONE: Self = Self(0);
pub const M1: Self = Self(1);
pub const M2: Self = Self(2);
pub const M3: Self = Self(3);
pub const ENUM_MIN: u8 = 0;
pub const ENUM_MAX: u8 = 3;
pub const ENUM_VALUES: &'static [Self] = &[
Self::NONE,
Self::M1,
Self::M2,
Self::M3,
];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M1 => Some("M1"),
Self::M2 => Some("M2"),
Self::M3 => Some("M3"),
_ => None,
}
}
}
impl std::fmt::Debug for AnyAmbiguousAliases {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if let Some(name) = self.variant_name() {
f.write_str(name)
} else {
f.write_fmt(format_args!("<UNKNOWN {:?}>", self.0))
}
}
}
impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases {
type Inner = Self;
#[inline]
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyAmbiguousAliases {
type Output = AnyAmbiguousAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::emplace_scalar::<u8>(dst, self.0); }
}
}
impl flatbuffers::EndianScalar for AnyAmbiguousAliases {
#[inline]
fn to_little_endian(self) -> Self {
let b = u8::to_le(self.0);
Self(b)
}
#[inline]
#[allow(clippy::wrong_self_convention)]
fn from_little_endian(self) -> Self {
let b = u8::from_le(self.0);
Self(b)
}
}
impl<'a> flatbuffers::Verifiable for AnyAmbiguousAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {} | pub enum AnyAmbiguousAliasesT {
NONE,
M1(Box<MonsterT>),
M2(Box<MonsterT>),
M3(Box<MonsterT>),
}
impl Default for AnyAmbiguousAliasesT {
fn default() -> Self {
Self::NONE
}
}
impl AnyAmbiguousAliasesT {
pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases {
match self {
Self::NONE => AnyAmbiguousAliases::NONE,
Self::M1(_) => AnyAmbiguousAliases::M1,
Self::M2(_) => AnyAmbiguousAliases::M2,
Self::M3(_) => AnyAmbiguousAliases::M3,
}
}
pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<flatbuffers::WIPOffset<flatbuffers::UnionWIPOffset>> {
match self {
Self::NONE => None,
Self::M1(v) => Some(v.pack(fbb).as_union_value()),
Self::M2(v) => Some(v.pack(fbb).as_union_value()),
Self::M3(v) => Some(v.pack(fbb).as_union_value()),
}
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m1(&mut self) -> Option<Box<MonsterT>> {
if let Self::M1(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M1(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m1(&self) -> Option<&MonsterT> {
if let Self::M1(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M1(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m2(&mut self) -> Option<Box<MonsterT>> {
if let Self::M2(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M2(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m2(&self) -> Option<&MonsterT> {
if let Self::M2(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M2(v) = self { Some(v.as_mut()) } else { None }
}
/// If the union variant matches, return the owned MonsterT, setting the union to NONE.
pub fn take_m3(&mut self) -> Option<Box<MonsterT>> {
if let Self::M3(_) = self {
let v = std::mem::replace(self, Self::NONE);
if let Self::M3(w) = v {
Some(w)
} else {
unreachable!()
}
} else {
None
}
}
/// If the union variant matches, return a reference to the MonsterT.
pub fn as_m3(&self) -> Option<&MonsterT> {
if let Self::M3(v) = self { Some(v.as_ref()) } else { None }
}
/// If the union variant matches, return a mutable reference to the MonsterT.
pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> {
if let Self::M3(v) = self { Some(v.as_mut()) } else { None }
}
} | pub struct AnyAmbiguousAliasesUnionTableOffset {}
#[allow(clippy::upper_case_acronyms)]
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)] | random_line_split |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("{}", opts.usage(&brief));
}
fn initialize_args() -> Options {
let mut opts = Options::new();
opts.optopt("O", "", "set optimization level", "[0-3]");
opts.optflag("h", "help", "print this help menu");
opts.optflag("", "ast", "print the ast");
return opts;
}
fn | () {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let opts = initialize_args();
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let print_ast = matches.opt_present("ast");
let filename = if!matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
let mut input = File::open(filename).unwrap();
let mut code = String::new();
input.read_to_string(&mut code).unwrap();
let ast = match parser::parse(code) {
Ok(t) => t,
Err(s) => {
println!("{}", s);
return;
}
};
if print_ast {
print!("{}", ast);
}
match typechecker::check(ast) {
Ok(_) => (),
Err(s) => {
println!("Typechecker error: {}", s);
return;
}
}
}
| main | identifier_name |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("{}", opts.usage(&brief));
}
fn initialize_args() -> Options {
let mut opts = Options::new();
opts.optopt("O", "", "set optimization level", "[0-3]");
opts.optflag("h", "help", "print this help menu");
opts.optflag("", "ast", "print the ast");
return opts;
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let opts = initialize_args();
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let print_ast = matches.opt_present("ast");
let filename = if!matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
let mut input = File::open(filename).unwrap();
let mut code = String::new();
input.read_to_string(&mut code).unwrap();
let ast = match parser::parse(code) {
Ok(t) => t,
Err(s) => { | };
if print_ast {
print!("{}", ast);
}
match typechecker::check(ast) {
Ok(_) => (),
Err(s) => {
println!("Typechecker error: {}", s);
return;
}
}
} | println!("{}", s);
return;
} | random_line_split |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("{}", opts.usage(&brief));
}
fn initialize_args() -> Options |
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let opts = initialize_args();
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let print_ast = matches.opt_present("ast");
let filename = if!matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
let mut input = File::open(filename).unwrap();
let mut code = String::new();
input.read_to_string(&mut code).unwrap();
let ast = match parser::parse(code) {
Ok(t) => t,
Err(s) => {
println!("{}", s);
return;
}
};
if print_ast {
print!("{}", ast);
}
match typechecker::check(ast) {
Ok(_) => (),
Err(s) => {
println!("Typechecker error: {}", s);
return;
}
}
}
| {
let mut opts = Options::new();
opts.optopt("O", "", "set optimization level", "[0-3]");
opts.optflag("h", "help", "print this help menu");
opts.optflag("", "ast", "print the ast");
return opts;
} | identifier_body |
main.rs | #[macro_use]
extern crate nom;
extern crate ansi_term;
extern crate getopts;
use getopts::Options;
use std::io::prelude::*;
use std::fs::File;
use std::env;
mod ast;
mod parser;
mod typechecker;
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} [options] FILE", program);
print!("{}", opts.usage(&brief));
}
fn initialize_args() -> Options {
let mut opts = Options::new();
opts.optopt("O", "", "set optimization level", "[0-3]");
opts.optflag("h", "help", "print this help menu");
opts.optflag("", "ast", "print the ast");
return opts;
}
fn main() {
let args: Vec<String> = env::args().collect();
let program = args[0].clone();
let opts = initialize_args();
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") |
let print_ast = matches.opt_present("ast");
let filename = if!matches.free.is_empty() {
matches.free[0].clone()
} else {
print_usage(&program, opts);
return;
};
let mut input = File::open(filename).unwrap();
let mut code = String::new();
input.read_to_string(&mut code).unwrap();
let ast = match parser::parse(code) {
Ok(t) => t,
Err(s) => {
println!("{}", s);
return;
}
};
if print_ast {
print!("{}", ast);
}
match typechecker::check(ast) {
Ok(_) => (),
Err(s) => {
println!("Typechecker error: {}", s);
return;
}
}
}
| {
print_usage(&program, opts);
return;
} | conditional_block |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn main() | Some(p) => cwd = p,
None => println!("Error: Can not get home directory!")
}
continue;
}
let path: Option<Path> = if args[0].starts_with("~") { // ~/projects
match env::home_dir() {
Some(e) => {
let dir = e.join(args[0].slice_from(2)); //[~/]
Some(dir)
}, //hacky but whatever
None => Path::new_opt(args[0])
}
} else if args[0].starts_with(".") ||!args[0].starts_with("/") { //./bin or../ash || cd src
Some(cwd.join(args[0]))
} else {
Path::new_opt(args[0])
};
match path {
Some(new) => {
match fs::stat(&new) {
Ok(stat) => {
if stat.kind == old_io::FileType::Directory {
cwd = new
}
},
Err(e) => println!("No such file or directory: \"{}\"", args[0])
}
}
None => println!("Failed to locate path")
}
}
"exit" => {
println!("Goodbye!");
break;
}
_ => {
let process = Command::new(cmd).cwd(&cwd).args(args).output();
match process {
Ok(output) => {
println!("{}", String::from_utf8_lossy(output.output.as_slice()));
},
Err(e) => {
println!("Error Occured: {}", e);
},
};
}
}
}
}
| {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your left shoes.");
let mut cwd = env::current_dir().unwrap();
loop {
print!("{}", ash::format::format(&cwd));
let rawinput = old_io::stdin().read_line().ok().expect("Error Occured");
let input = rawinput.as_slice().trim();
if input == "" { continue } //skip blank enters
let opts: Vec<&str> = input.split_str(" ").collect();
let (cmd, args) = (opts[0], opts.slice(1, opts.len()));
match cmd {
"cd" => {
//set the current directory
if args[0] == "~" {
//go home
match env::home_dir() { | identifier_body |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn main() {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your left shoes.");
let mut cwd = env::current_dir().unwrap();
loop {
print!("{}", ash::format::format(&cwd));
let rawinput = old_io::stdin().read_line().ok().expect("Error Occured");
let input = rawinput.as_slice().trim();
if input == "" { continue } //skip blank enters
let opts: Vec<&str> = input.split_str(" ").collect();
let (cmd, args) = (opts[0], opts.slice(1, opts.len()));
match cmd {
"cd" => {
//set the current directory
if args[0] == "~" {
//go home
match env::home_dir() {
Some(p) => cwd = p,
None => println!("Error: Can not get home directory!")
}
continue;
}
let path: Option<Path> = if args[0].starts_with("~") { // ~/projects
match env::home_dir() {
Some(e) => {
let dir = e.join(args[0].slice_from(2)); //[~/]
Some(dir)
}, //hacky but whatever
None => Path::new_opt(args[0])
}
} else if args[0].starts_with(".") ||!args[0].starts_with("/") { //./bin or../ash || cd src
Some(cwd.join(args[0]))
} else {
Path::new_opt(args[0])
};
match path {
Some(new) => {
match fs::stat(&new) {
Ok(stat) => {
if stat.kind == old_io::FileType::Directory |
},
Err(e) => println!("No such file or directory: \"{}\"", args[0])
}
}
None => println!("Failed to locate path")
}
}
"exit" => {
println!("Goodbye!");
break;
}
_ => {
let process = Command::new(cmd).cwd(&cwd).args(args).output();
match process {
Ok(output) => {
println!("{}", String::from_utf8_lossy(output.output.as_slice()));
},
Err(e) => {
println!("Error Occured: {}", e);
},
};
}
}
}
}
| {
cwd = new
} | conditional_block |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn | () {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your left shoes.");
let mut cwd = env::current_dir().unwrap();
loop {
print!("{}", ash::format::format(&cwd));
let rawinput = old_io::stdin().read_line().ok().expect("Error Occured");
let input = rawinput.as_slice().trim();
if input == "" { continue } //skip blank enters
let opts: Vec<&str> = input.split_str(" ").collect();
let (cmd, args) = (opts[0], opts.slice(1, opts.len()));
match cmd {
"cd" => {
//set the current directory
if args[0] == "~" {
//go home
match env::home_dir() {
Some(p) => cwd = p,
None => println!("Error: Can not get home directory!")
}
continue;
}
let path: Option<Path> = if args[0].starts_with("~") { // ~/projects
match env::home_dir() {
Some(e) => {
let dir = e.join(args[0].slice_from(2)); //[~/]
Some(dir)
}, //hacky but whatever
None => Path::new_opt(args[0])
}
} else if args[0].starts_with(".") ||!args[0].starts_with("/") { //./bin or../ash || cd src
Some(cwd.join(args[0]))
} else {
Path::new_opt(args[0])
};
match path {
Some(new) => {
match fs::stat(&new) {
Ok(stat) => {
if stat.kind == old_io::FileType::Directory {
cwd = new
}
},
Err(e) => println!("No such file or directory: \"{}\"", args[0])
}
}
None => println!("Failed to locate path")
}
}
"exit" => {
println!("Goodbye!");
break;
}
_ => {
let process = Command::new(cmd).cwd(&cwd).args(args).output();
match process {
Ok(output) => {
println!("{}", String::from_utf8_lossy(output.output.as_slice()));
},
Err(e) => {
println!("Error Occured: {}", e);
},
};
}
}
}
}
| main | identifier_name |
main.rs | #![feature(io)]
#![feature(os)]
#![feature(env)]
#![feature(path)]
#![feature(collections)]
use std::old_io;
use std::old_io::fs;
use std::old_io::process::{Command};
use std::old_path::Path;
use std::env;
mod ash;
fn main() {
println!("ash: A shell");
println!("Incredibly in beta");
println!("May eat your left shoes.");
let mut cwd = env::current_dir().unwrap();
loop {
print!("{}", ash::format::format(&cwd));
let rawinput = old_io::stdin().read_line().ok().expect("Error Occured");
let input = rawinput.as_slice().trim();
if input == "" { continue } //skip blank enters
let opts: Vec<&str> = input.split_str(" ").collect();
let (cmd, args) = (opts[0], opts.slice(1, opts.len()));
match cmd {
"cd" => {
//set the current directory
if args[0] == "~" { | continue;
}
let path: Option<Path> = if args[0].starts_with("~") { // ~/projects
match env::home_dir() {
Some(e) => {
let dir = e.join(args[0].slice_from(2)); //[~/]
Some(dir)
}, //hacky but whatever
None => Path::new_opt(args[0])
}
} else if args[0].starts_with(".") ||!args[0].starts_with("/") { //./bin or../ash || cd src
Some(cwd.join(args[0]))
} else {
Path::new_opt(args[0])
};
match path {
Some(new) => {
match fs::stat(&new) {
Ok(stat) => {
if stat.kind == old_io::FileType::Directory {
cwd = new
}
},
Err(e) => println!("No such file or directory: \"{}\"", args[0])
}
}
None => println!("Failed to locate path")
}
}
"exit" => {
println!("Goodbye!");
break;
}
_ => {
let process = Command::new(cmd).cwd(&cwd).args(args).output();
match process {
Ok(output) => {
println!("{}", String::from_utf8_lossy(output.output.as_slice()));
},
Err(e) => {
println!("Error Occured: {}", e);
},
};
}
}
}
} | //go home
match env::home_dir() {
Some(p) => cwd = p,
None => println!("Error: Can not get home directory!")
} | random_line_split |
reverse_graph.rs | use crate::core::{
property::{AddEdge, RemoveEdge},
Directed, Ensure, Graph, GraphDerefMut, GraphMut,
};
use delegate::delegate;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct ReverseGraph<C: Ensure>(C)
where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> ReverseGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
/// Creates the a reversed graph from the given graph.
pub fn new(c: C) -> Self
{
Self(c)
}
}
impl<C: Ensure> Graph for ReverseGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
type Directedness = Directed;
type EdgeWeight = <C::Graph as Graph>::EdgeWeight;
type Vertex = <C::Graph as Graph>::Vertex;
type VertexWeight = <C::Graph as Graph>::VertexWeight;
delegate! {
to self.0.graph() {
fn all_vertices_weighted<'a>(&'a self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a Self::VertexWeight)>>;
}
}
fn edges_between<'a: 'b, 'b>(
&'a self,
source: impl 'b + Borrow<Self::Vertex>,
sink: impl 'b + Borrow<Self::Vertex>,
) -> Box<dyn 'b + Iterator<Item = &'a Self::EdgeWeight>>
{
self.0.graph().edges_between(sink, source)
}
}
impl<C: Ensure + GraphDerefMut> GraphMut for ReverseGraph<C>
where
C::Graph: GraphMut<Directedness = Directed>,
{
delegate! {
to self.0.graph_mut() {
fn all_vertices_weighted_mut<'a>(&'a mut self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a mut Self::VertexWeight)>>;
}
}
fn edges_between_mut<'a: 'b, 'b>(
&'a mut self,
source: impl 'b + Borrow<Self::Vertex>,
sink: impl 'b + Borrow<Self::Vertex>,
) -> Box<dyn 'b + Iterator<Item = &'a mut Self::EdgeWeight>>
|
}
impl<C: Ensure + GraphDerefMut> AddEdge for ReverseGraph<C>
where
C::Graph: AddEdge<Directedness = Directed>,
{
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>
{
self.0.graph_mut().add_edge_weighted(sink, source, weight)
}
}
impl<C: Ensure + GraphDerefMut> RemoveEdge for ReverseGraph<C>
where
C::Graph: RemoveEdge<Directedness = Directed>,
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool,
{
self.0.graph_mut().remove_edge_where_weight(source, sink, f)
}
}
base_graph! {
use<C> ReverseGraph<C>: NewVertex, RemoveVertex, HasVertex
as (self.0): C
where
C: Ensure,
C::Graph: Graph<Directedness = Directed>
}
| {
Box::new(self.0.graph_mut().edges_between_mut(sink, source))
} | identifier_body |
reverse_graph.rs | use crate::core::{
property::{AddEdge, RemoveEdge},
Directed, Ensure, Graph, GraphDerefMut, GraphMut,
};
use delegate::delegate;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct ReverseGraph<C: Ensure>(C)
where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> ReverseGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
/// Creates the a reversed graph from the given graph.
pub fn new(c: C) -> Self
{
Self(c)
}
}
impl<C: Ensure> Graph for ReverseGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
type Directedness = Directed;
type EdgeWeight = <C::Graph as Graph>::EdgeWeight;
type Vertex = <C::Graph as Graph>::Vertex;
type VertexWeight = <C::Graph as Graph>::VertexWeight;
delegate! {
to self.0.graph() {
fn all_vertices_weighted<'a>(&'a self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a Self::VertexWeight)>>;
}
}
fn edges_between<'a: 'b, 'b>(
&'a self,
source: impl 'b + Borrow<Self::Vertex>,
sink: impl 'b + Borrow<Self::Vertex>,
) -> Box<dyn 'b + Iterator<Item = &'a Self::EdgeWeight>>
{
self.0.graph().edges_between(sink, source) | C::Graph: GraphMut<Directedness = Directed>,
{
delegate! {
to self.0.graph_mut() {
fn all_vertices_weighted_mut<'a>(&'a mut self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a mut Self::VertexWeight)>>;
}
}
fn edges_between_mut<'a: 'b, 'b>(
&'a mut self,
source: impl 'b + Borrow<Self::Vertex>,
sink: impl 'b + Borrow<Self::Vertex>,
) -> Box<dyn 'b + Iterator<Item = &'a mut Self::EdgeWeight>>
{
Box::new(self.0.graph_mut().edges_between_mut(sink, source))
}
}
impl<C: Ensure + GraphDerefMut> AddEdge for ReverseGraph<C>
where
C::Graph: AddEdge<Directedness = Directed>,
{
fn add_edge_weighted(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>
{
self.0.graph_mut().add_edge_weighted(sink, source, weight)
}
}
impl<C: Ensure + GraphDerefMut> RemoveEdge for ReverseGraph<C>
where
C::Graph: RemoveEdge<Directedness = Directed>,
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool,
{
self.0.graph_mut().remove_edge_where_weight(source, sink, f)
}
}
base_graph! {
use<C> ReverseGraph<C>: NewVertex, RemoveVertex, HasVertex
as (self.0): C
where
C: Ensure,
C::Graph: Graph<Directedness = Directed>
} | }
}
impl<C: Ensure + GraphDerefMut> GraphMut for ReverseGraph<C>
where | random_line_split |
reverse_graph.rs | use crate::core::{
property::{AddEdge, RemoveEdge},
Directed, Ensure, Graph, GraphDerefMut, GraphMut,
};
use delegate::delegate;
use std::borrow::Borrow;
#[derive(Debug)]
pub struct ReverseGraph<C: Ensure>(C)
where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> ReverseGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
/// Creates the a reversed graph from the given graph.
pub fn new(c: C) -> Self
{
Self(c)
}
}
impl<C: Ensure> Graph for ReverseGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
type Directedness = Directed;
type EdgeWeight = <C::Graph as Graph>::EdgeWeight;
type Vertex = <C::Graph as Graph>::Vertex;
type VertexWeight = <C::Graph as Graph>::VertexWeight;
delegate! {
to self.0.graph() {
fn all_vertices_weighted<'a>(&'a self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a Self::VertexWeight)>>;
}
}
fn edges_between<'a: 'b, 'b>(
&'a self,
source: impl 'b + Borrow<Self::Vertex>,
sink: impl 'b + Borrow<Self::Vertex>,
) -> Box<dyn 'b + Iterator<Item = &'a Self::EdgeWeight>>
{
self.0.graph().edges_between(sink, source)
}
}
impl<C: Ensure + GraphDerefMut> GraphMut for ReverseGraph<C>
where
C::Graph: GraphMut<Directedness = Directed>,
{
delegate! {
to self.0.graph_mut() {
fn all_vertices_weighted_mut<'a>(&'a mut self) -> Box<dyn 'a + Iterator<Item=
(Self::Vertex, &'a mut Self::VertexWeight)>>;
}
}
fn edges_between_mut<'a: 'b, 'b>(
&'a mut self,
source: impl 'b + Borrow<Self::Vertex>,
sink: impl 'b + Borrow<Self::Vertex>,
) -> Box<dyn 'b + Iterator<Item = &'a mut Self::EdgeWeight>>
{
Box::new(self.0.graph_mut().edges_between_mut(sink, source))
}
}
impl<C: Ensure + GraphDerefMut> AddEdge for ReverseGraph<C>
where
C::Graph: AddEdge<Directedness = Directed>,
{
fn | (
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
weight: Self::EdgeWeight,
) -> Result<(), ()>
{
self.0.graph_mut().add_edge_weighted(sink, source, weight)
}
}
impl<C: Ensure + GraphDerefMut> RemoveEdge for ReverseGraph<C>
where
C::Graph: RemoveEdge<Directedness = Directed>,
{
fn remove_edge_where_weight<F>(
&mut self,
source: impl Borrow<Self::Vertex>,
sink: impl Borrow<Self::Vertex>,
f: F,
) -> Result<Self::EdgeWeight, ()>
where
F: Fn(&Self::EdgeWeight) -> bool,
{
self.0.graph_mut().remove_edge_where_weight(source, sink, f)
}
}
base_graph! {
use<C> ReverseGraph<C>: NewVertex, RemoveVertex, HasVertex
as (self.0): C
where
C: Ensure,
C::Graph: Graph<Directedness = Directed>
}
| add_edge_weighted | identifier_name |
physics.rs | use super::{Unit, ToUnit};
#[deriving(Eq, Ord)]
pub struct Vec2 {
pub x: Unit,
pub y: Unit,
}
impl Vec2 {
pub fn new<A: ToUnit, B: ToUnit>(x: A, y: B) -> Vec2 {
Vec2 {
x: x.to_unit(),
y: y.to_unit(),
}
}
pub fn norm(&self) -> Vec2 {
let len = self.length();
Vec2::new(self.x / len, self.y / len)
}
pub fn length(&self) -> Unit {
let x = self.x.val();
let y = self.y.val();
Unit((x * x + y * y).sqrt())
}
}
pub trait ToVec2 {
fn to_vec(&self) -> Vec2;
}
impl ToVec2 for Vec2 {
fn | (&self) -> Vec2 {
*self
}
}
impl Add<Vec2, Vec2> for Vec2 {
fn add(&self, rhs: &Vec2) -> Vec2 {
Vec2 {
x: self.x + rhs.x,
y: self.y + rhs.y,
}
}
}
impl<T: ToUnit> Mul<T, Vec2> for Vec2 {
fn mul(&self, rhs: &T) -> Vec2 {
let a = rhs.to_unit();
Vec2 {
x: self.x * a,
y: self.y * a,
}
}
}
/// x axis from left to right and y asix from top to bottom
pub struct AABB {
pub center: Vec2,
pub size: Vec2,
}
impl AABB {
pub fn new<A: ToUnit, B: ToUnit, C: ToUnit, D: ToUnit>(x: A, y: B, w: C, h: D) -> AABB {
AABB {
center: Vec2::new(x, y),
size: Vec2::new(w, h),
}
}
pub fn transform(&self, offset: Vec2) -> AABB {
AABB {
center: self.center + offset,
size: self.size,
}
}
pub fn is_collided_with(&self, other: &AABB) -> bool {
self.right() >= other.left() &&
self.left() <= other.right() &&
self.top() <= other.bottom() &&
self.bottom() >= other.top()
}
pub fn left(&self) -> Unit {
self.center.x - self.size.x / 2.0
}
pub fn right(&self) -> Unit {
self.center.x + self.size.x / 2.0
}
pub fn top(&self) -> Unit {
self.center.y - self.size.y / 2.0
}
pub fn bottom(&self) -> Unit {
self.center.y + self.size.y / 2.0
}
pub fn size(&self) -> Vec2 {
self.size
}
}
#[deriving(Eq, Ord)]
pub struct MS(pub uint);
impl MS {
pub fn val(&self) -> uint {
let MS(a) = *self;
a
}
}
impl ToUnit for MS {
fn to_unit(&self) -> Unit {
let MS(a) = *self;
Unit(a as f32)
}
}
impl Sub<MS, MS> for MS {
fn sub(&self, rhs: &MS) -> MS {
MS(self.val() - rhs.val())
}
}
impl Add<MS, MS> for MS {
fn add(&self, rhs: &MS) -> MS {
MS(self.val() + rhs.val())
}
}
| to_vec | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.