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 |
---|---|---|---|---|
util.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use anyhow::Result;
use libimagrt::runtime::Runtime;
use crate::reference::Config as RefConfig;
pub fn get_ref_config(rt: &Runtime, app_name: &'static str) -> Result<RefConfig>
|
{
use toml_query::read::TomlValueReadExt;
let setting_name = "ref.basepathes";
rt.config()
.ok_or_else(|| anyhow!("No configuration, cannot find collection name for {}", app_name))?
.read_deserialized::<RefConfig>(setting_name)?
.ok_or_else(|| anyhow!("Setting missing: {}", setting_name))
}
|
identifier_body
|
|
struct-destructuring-cross-crate.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.
// aux-build:struct_destructuring_cross_crate.rs
extern crate struct_destructuring_cross_crate;
pub fn main()
|
{
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
}
|
identifier_body
|
|
struct-destructuring-cross-crate.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.
// aux-build:struct_destructuring_cross_crate.rs
extern crate struct_destructuring_cross_crate;
pub fn
|
() {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
}
|
main
|
identifier_name
|
struct-destructuring-cross-crate.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:struct_destructuring_cross_crate.rs
extern crate struct_destructuring_cross_crate;
pub fn main() {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
}
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
random_line_split
|
issue-14919.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
trait Matcher {
fn next_match(&mut self) -> Option<(usize, usize)>;
}
struct CharPredMatcher<'a, 'b> {
str: &'a str,
pred: Box<FnMut(char) -> bool + 'b>,
}
impl<'a, 'b> Matcher for CharPredMatcher<'a, 'b> {
fn next_match(&mut self) -> Option<(usize, usize)> {
None
}
}
trait IntoMatcher<'a, T> {
fn into_matcher(self, &'a str) -> T;
}
impl<'a, 'b, F> IntoMatcher<'a, CharPredMatcher<'a, 'b>> for F where F: FnMut(char) -> bool + 'b {
fn into_matcher(self, s: &'a str) -> CharPredMatcher<'a, 'b> {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
CharPredMatcher {
str: s,
pred: Box::new(self),
}
}
}
struct MatchIndices<M> {
matcher: M
}
impl<M: Matcher> Iterator for MatchIndices<M> {
type Item = (usize, usize);
fn
|
(&mut self) -> Option<(usize, usize)> {
self.matcher.next_match()
}
}
fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndices<M> {
let string_matcher = from.into_matcher(s);
MatchIndices { matcher: string_matcher }
}
fn main() {
let s = "abcbdef";
match_indices(s, |c: char| c == 'b')
.collect::<Vec<(usize, usize)>>();
}
|
next
|
identifier_name
|
issue-14919.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
trait Matcher {
fn next_match(&mut self) -> Option<(usize, usize)>;
}
struct CharPredMatcher<'a, 'b> {
str: &'a str,
pred: Box<FnMut(char) -> bool + 'b>,
}
impl<'a, 'b> Matcher for CharPredMatcher<'a, 'b> {
fn next_match(&mut self) -> Option<(usize, usize)> {
None
}
}
trait IntoMatcher<'a, T> {
fn into_matcher(self, &'a str) -> T;
}
impl<'a, 'b, F> IntoMatcher<'a, CharPredMatcher<'a, 'b>> for F where F: FnMut(char) -> bool + 'b {
fn into_matcher(self, s: &'a str) -> CharPredMatcher<'a, 'b> {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
CharPredMatcher {
str: s,
pred: Box::new(self),
}
}
}
struct MatchIndices<M> {
matcher: M
}
impl<M: Matcher> Iterator for MatchIndices<M> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
self.matcher.next_match()
}
}
fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndices<M> {
let string_matcher = from.into_matcher(s);
MatchIndices { matcher: string_matcher }
}
fn main() {
let s = "abcbdef";
match_indices(s, |c: char| c == 'b')
.collect::<Vec<(usize, usize)>>();
}
|
// pretty-expanded FIXME #23616
|
random_line_split
|
issue-14919.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
trait Matcher {
fn next_match(&mut self) -> Option<(usize, usize)>;
}
struct CharPredMatcher<'a, 'b> {
str: &'a str,
pred: Box<FnMut(char) -> bool + 'b>,
}
impl<'a, 'b> Matcher for CharPredMatcher<'a, 'b> {
fn next_match(&mut self) -> Option<(usize, usize)> {
None
}
}
trait IntoMatcher<'a, T> {
fn into_matcher(self, &'a str) -> T;
}
impl<'a, 'b, F> IntoMatcher<'a, CharPredMatcher<'a, 'b>> for F where F: FnMut(char) -> bool + 'b {
fn into_matcher(self, s: &'a str) -> CharPredMatcher<'a, 'b> {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
CharPredMatcher {
str: s,
pred: Box::new(self),
}
}
}
struct MatchIndices<M> {
matcher: M
}
impl<M: Matcher> Iterator for MatchIndices<M> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
self.matcher.next_match()
}
}
fn match_indices<'a, M, T: IntoMatcher<'a, M>>(s: &'a str, from: T) -> MatchIndices<M>
|
fn main() {
let s = "abcbdef";
match_indices(s, |c: char| c == 'b')
.collect::<Vec<(usize, usize)>>();
}
|
{
let string_matcher = from.into_matcher(s);
MatchIndices { matcher: string_matcher }
}
|
identifier_body
|
triple_loop.rs
|
pub use matrix::{Scalar,Mat};
pub use composables::{GemmNode,AlgorithmStep};
pub use thread_comm::ThreadInfo;
pub struct TripleLoop{}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>>
GemmNode<T, At, Bt, Ct> for TripleLoop {
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) -> () {
for x in 0..c.width() {
for z in 0..a.width() {
for y in 0..c.height() {
let t = a.get(y,z) * b.get(z,x) + c.get(y,x);
c.set(y, x, t);
}
}
}
}
fn
|
() -> Self { TripleLoop{} }
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() }
}
|
new
|
identifier_name
|
triple_loop.rs
|
pub use matrix::{Scalar,Mat};
pub use composables::{GemmNode,AlgorithmStep};
pub use thread_comm::ThreadInfo;
pub struct TripleLoop{}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>>
GemmNode<T, At, Bt, Ct> for TripleLoop {
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) -> () {
for x in 0..c.width() {
for z in 0..a.width() {
for y in 0..c.height() {
let t = a.get(y,z) * b.get(z,x) + c.get(y,x);
|
fn new() -> Self { TripleLoop{} }
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() }
}
|
c.set(y, x, t);
}
}
}
}
|
random_line_split
|
triple_loop.rs
|
pub use matrix::{Scalar,Mat};
pub use composables::{GemmNode,AlgorithmStep};
pub use thread_comm::ThreadInfo;
pub struct TripleLoop{}
impl<T: Scalar, At: Mat<T>, Bt: Mat<T>, Ct: Mat<T>>
GemmNode<T, At, Bt, Ct> for TripleLoop {
unsafe fn run(&mut self, a: &mut At, b: &mut Bt, c: &mut Ct, _thr: &ThreadInfo<T>) -> () {
for x in 0..c.width() {
for z in 0..a.width() {
for y in 0..c.height() {
let t = a.get(y,z) * b.get(z,x) + c.get(y,x);
c.set(y, x, t);
}
}
}
}
fn new() -> Self
|
fn hierarchy_description() -> Vec<AlgorithmStep> { Vec::new() }
}
|
{ TripleLoop{} }
|
identifier_body
|
parser_testing.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{self, Ident};
use source_map::FilePathMapping;
use parse::{ParseSess, PResult, source_file_to_stream};
use parse::{lexer, new_parser_from_source_str};
use parse::parser::Parser;
use ptr::P;
use tokenstream::TokenStream;
use std::iter::Peekable;
use std::path::PathBuf;
/// Map a string to tts, using a made-up filename:
pub fn string_to_stream(source_str: String) -> TokenStream {
let ps = ParseSess::new(FilePathMapping::empty());
source_file_to_stream(&ps, ps.source_map()
.new_source_file(PathBuf::from("bogofile").into(), source_str), None)
}
/// Map string to parser (via tts)
pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str)
}
fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where
F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>,
{
let mut p = string_to_parser(&ps, s);
let x = panictry!(f(&mut p));
p.abort_if_errors();
x
}
/// Parse a string, return a crate.
pub fn string_to_crate (source_str : String) -> ast::Crate {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_crate_mod()
})
}
/// Parse a string, return an expr
pub fn string_to_expr (source_str : String) -> P<ast::Expr> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_expr()
})
}
/// Parse a string, return an item
pub fn string_to_item (source_str : String) -> Option<P<ast::Item>>
|
/// Parse a string, return a pat. Uses "irrefutable"... which doesn't
/// (currently) affect parsing.
pub fn string_to_pat(source_str: String) -> P<ast::Pat> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_pat(None)
})
}
/// Convert a vector of strings to a vector of Ident's
pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<Ident> {
ids.iter().map(|u| Ident::from_str(*u)).collect()
}
/// Does the given string match the pattern? whitespace in the first string
/// may be deleted or replaced with other whitespace to match the pattern.
/// This function is relatively Unicode-ignorant; fortunately, the careful design
/// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?).
pub fn matches_codepattern(a : &str, b : &str) -> bool {
let mut a_iter = a.chars().peekable();
let mut b_iter = b.chars().peekable();
loop {
let (a, b) = match (a_iter.peek(), b_iter.peek()) {
(None, None) => return true,
(None, _) => return false,
(Some(&a), None) => {
if is_pattern_whitespace(a) {
break // trailing whitespace check is out of loop for borrowck
} else {
return false
}
}
(Some(&a), Some(&b)) => (a, b)
};
if is_pattern_whitespace(a) && is_pattern_whitespace(b) {
// skip whitespace for a and b
scan_for_non_ws_or_end(&mut a_iter);
scan_for_non_ws_or_end(&mut b_iter);
} else if is_pattern_whitespace(a) {
// skip whitespace for a
scan_for_non_ws_or_end(&mut a_iter);
} else if a == b {
a_iter.next();
b_iter.next();
} else {
return false
}
}
// check if a has *only* trailing whitespace
a_iter.all(is_pattern_whitespace)
}
/// Advances the given peekable `Iterator` until it reaches a non-whitespace character
fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) {
while lexer::is_pattern_whitespace(iter.peek().cloned()) {
iter.next();
}
}
pub fn is_pattern_whitespace(c: char) -> bool {
lexer::is_pattern_whitespace(Some(c))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eqmodws() {
assert_eq!(matches_codepattern("",""),true);
assert_eq!(matches_codepattern("","a"),false);
assert_eq!(matches_codepattern("a",""),false);
assert_eq!(matches_codepattern("a","a"),true);
assert_eq!(matches_codepattern("a b","a \n\t\r b"),true);
assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true);
assert_eq!(matches_codepattern("a b","a \n\t\r b "),false);
assert_eq!(matches_codepattern("a b","a b"),true);
assert_eq!(matches_codepattern("ab","a b"),false);
assert_eq!(matches_codepattern("a b","ab"),true);
assert_eq!(matches_codepattern(" a b","ab"),true);
}
#[test]
fn pattern_whitespace() {
assert_eq!(matches_codepattern("","\x0C"), false);
assert_eq!(matches_codepattern("a b ","a \u{0085}\n\t\r b"),true);
assert_eq!(matches_codepattern("a b","a \u{0085}\n\t\r b "),false);
}
#[test]
fn non_pattern_whitespace() {
// These have the property 'White_Space' but not 'Pattern_White_Space'
assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
assert_eq!(matches_codepattern("\u{205F}a b","ab"), false);
assert_eq!(matches_codepattern("a \u{3000}b","ab"), false);
}
}
|
{
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_item()
})
}
|
identifier_body
|
parser_testing.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{self, Ident};
use source_map::FilePathMapping;
use parse::{ParseSess, PResult, source_file_to_stream};
use parse::{lexer, new_parser_from_source_str};
use parse::parser::Parser;
use ptr::P;
use tokenstream::TokenStream;
use std::iter::Peekable;
use std::path::PathBuf;
/// Map a string to tts, using a made-up filename:
pub fn string_to_stream(source_str: String) -> TokenStream {
let ps = ParseSess::new(FilePathMapping::empty());
source_file_to_stream(&ps, ps.source_map()
.new_source_file(PathBuf::from("bogofile").into(), source_str), None)
}
/// Map string to parser (via tts)
pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str)
}
fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where
F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>,
{
let mut p = string_to_parser(&ps, s);
let x = panictry!(f(&mut p));
p.abort_if_errors();
x
}
/// Parse a string, return a crate.
pub fn string_to_crate (source_str : String) -> ast::Crate {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_crate_mod()
})
}
/// Parse a string, return an expr
pub fn string_to_expr (source_str : String) -> P<ast::Expr> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_expr()
})
}
/// Parse a string, return an item
pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_item()
})
}
/// Parse a string, return a pat. Uses "irrefutable"... which doesn't
/// (currently) affect parsing.
pub fn string_to_pat(source_str: String) -> P<ast::Pat> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_pat(None)
})
}
/// Convert a vector of strings to a vector of Ident's
pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<Ident> {
ids.iter().map(|u| Ident::from_str(*u)).collect()
}
/// Does the given string match the pattern? whitespace in the first string
/// may be deleted or replaced with other whitespace to match the pattern.
/// This function is relatively Unicode-ignorant; fortunately, the careful design
/// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?).
pub fn matches_codepattern(a : &str, b : &str) -> bool {
let mut a_iter = a.chars().peekable();
let mut b_iter = b.chars().peekable();
loop {
let (a, b) = match (a_iter.peek(), b_iter.peek()) {
(None, None) => return true,
(None, _) => return false,
(Some(&a), None) => {
if is_pattern_whitespace(a) {
break // trailing whitespace check is out of loop for borrowck
} else {
return false
}
}
(Some(&a), Some(&b)) => (a, b)
};
if is_pattern_whitespace(a) && is_pattern_whitespace(b) {
// skip whitespace for a and b
scan_for_non_ws_or_end(&mut a_iter);
scan_for_non_ws_or_end(&mut b_iter);
} else if is_pattern_whitespace(a) {
// skip whitespace for a
scan_for_non_ws_or_end(&mut a_iter);
} else if a == b {
a_iter.next();
b_iter.next();
} else {
return false
}
}
// check if a has *only* trailing whitespace
a_iter.all(is_pattern_whitespace)
}
/// Advances the given peekable `Iterator` until it reaches a non-whitespace character
fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) {
while lexer::is_pattern_whitespace(iter.peek().cloned()) {
iter.next();
}
}
pub fn is_pattern_whitespace(c: char) -> bool {
lexer::is_pattern_whitespace(Some(c))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn
|
() {
assert_eq!(matches_codepattern("",""),true);
assert_eq!(matches_codepattern("","a"),false);
assert_eq!(matches_codepattern("a",""),false);
assert_eq!(matches_codepattern("a","a"),true);
assert_eq!(matches_codepattern("a b","a \n\t\r b"),true);
assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true);
assert_eq!(matches_codepattern("a b","a \n\t\r b "),false);
assert_eq!(matches_codepattern("a b","a b"),true);
assert_eq!(matches_codepattern("ab","a b"),false);
assert_eq!(matches_codepattern("a b","ab"),true);
assert_eq!(matches_codepattern(" a b","ab"),true);
}
#[test]
fn pattern_whitespace() {
assert_eq!(matches_codepattern("","\x0C"), false);
assert_eq!(matches_codepattern("a b ","a \u{0085}\n\t\r b"),true);
assert_eq!(matches_codepattern("a b","a \u{0085}\n\t\r b "),false);
}
#[test]
fn non_pattern_whitespace() {
// These have the property 'White_Space' but not 'Pattern_White_Space'
assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
assert_eq!(matches_codepattern("\u{205F}a b","ab"), false);
assert_eq!(matches_codepattern("a \u{3000}b","ab"), false);
}
}
|
eqmodws
|
identifier_name
|
parser_testing.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{self, Ident};
use source_map::FilePathMapping;
use parse::{ParseSess, PResult, source_file_to_stream};
use parse::{lexer, new_parser_from_source_str};
use parse::parser::Parser;
use ptr::P;
use tokenstream::TokenStream;
use std::iter::Peekable;
use std::path::PathBuf;
/// Map a string to tts, using a made-up filename:
pub fn string_to_stream(source_str: String) -> TokenStream {
let ps = ParseSess::new(FilePathMapping::empty());
source_file_to_stream(&ps, ps.source_map()
.new_source_file(PathBuf::from("bogofile").into(), source_str), None)
}
/// Map string to parser (via tts)
pub fn string_to_parser<'a>(ps: &'a ParseSess, source_str: String) -> Parser<'a> {
new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str)
}
fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T where
F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>,
{
let mut p = string_to_parser(&ps, s);
let x = panictry!(f(&mut p));
p.abort_if_errors();
x
}
/// Parse a string, return a crate.
pub fn string_to_crate (source_str : String) -> ast::Crate {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_crate_mod()
})
}
/// Parse a string, return an expr
pub fn string_to_expr (source_str : String) -> P<ast::Expr> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_expr()
})
}
/// Parse a string, return an item
pub fn string_to_item (source_str : String) -> Option<P<ast::Item>> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_item()
})
}
/// Parse a string, return a pat. Uses "irrefutable"... which doesn't
/// (currently) affect parsing.
pub fn string_to_pat(source_str: String) -> P<ast::Pat> {
let ps = ParseSess::new(FilePathMapping::empty());
with_error_checking_parse(source_str, &ps, |p| {
p.parse_pat(None)
})
}
/// Convert a vector of strings to a vector of Ident's
pub fn strs_to_idents(ids: Vec<&str> ) -> Vec<Ident> {
ids.iter().map(|u| Ident::from_str(*u)).collect()
}
/// Does the given string match the pattern? whitespace in the first string
/// may be deleted or replaced with other whitespace to match the pattern.
/// This function is relatively Unicode-ignorant; fortunately, the careful design
/// of UTF-8 mitigates this ignorance. It doesn't do NKF-normalization(?).
pub fn matches_codepattern(a : &str, b : &str) -> bool {
let mut a_iter = a.chars().peekable();
let mut b_iter = b.chars().peekable();
loop {
let (a, b) = match (a_iter.peek(), b_iter.peek()) {
(None, None) => return true,
(None, _) => return false,
(Some(&a), None) => {
if is_pattern_whitespace(a) {
break // trailing whitespace check is out of loop for borrowck
} else {
return false
}
}
(Some(&a), Some(&b)) => (a, b)
};
if is_pattern_whitespace(a) && is_pattern_whitespace(b) {
// skip whitespace for a and b
scan_for_non_ws_or_end(&mut a_iter);
scan_for_non_ws_or_end(&mut b_iter);
} else if is_pattern_whitespace(a) {
// skip whitespace for a
scan_for_non_ws_or_end(&mut a_iter);
} else if a == b {
a_iter.next();
|
return false
}
}
// check if a has *only* trailing whitespace
a_iter.all(is_pattern_whitespace)
}
/// Advances the given peekable `Iterator` until it reaches a non-whitespace character
fn scan_for_non_ws_or_end<I: Iterator<Item= char>>(iter: &mut Peekable<I>) {
while lexer::is_pattern_whitespace(iter.peek().cloned()) {
iter.next();
}
}
pub fn is_pattern_whitespace(c: char) -> bool {
lexer::is_pattern_whitespace(Some(c))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn eqmodws() {
assert_eq!(matches_codepattern("",""),true);
assert_eq!(matches_codepattern("","a"),false);
assert_eq!(matches_codepattern("a",""),false);
assert_eq!(matches_codepattern("a","a"),true);
assert_eq!(matches_codepattern("a b","a \n\t\r b"),true);
assert_eq!(matches_codepattern("a b ","a \n\t\r b"),true);
assert_eq!(matches_codepattern("a b","a \n\t\r b "),false);
assert_eq!(matches_codepattern("a b","a b"),true);
assert_eq!(matches_codepattern("ab","a b"),false);
assert_eq!(matches_codepattern("a b","ab"),true);
assert_eq!(matches_codepattern(" a b","ab"),true);
}
#[test]
fn pattern_whitespace() {
assert_eq!(matches_codepattern("","\x0C"), false);
assert_eq!(matches_codepattern("a b ","a \u{0085}\n\t\r b"),true);
assert_eq!(matches_codepattern("a b","a \u{0085}\n\t\r b "),false);
}
#[test]
fn non_pattern_whitespace() {
// These have the property 'White_Space' but not 'Pattern_White_Space'
assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
assert_eq!(matches_codepattern("a b","a\u{2002}b"), false);
assert_eq!(matches_codepattern("\u{205F}a b","ab"), false);
assert_eq!(matches_codepattern("a \u{3000}b","ab"), false);
}
}
|
b_iter.next();
} else {
|
random_line_split
|
xul.mako.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
// Non-standard properties that Gecko uses for XUL elements.
<% data.new_style_struct("XUL", inherited=False) %>
${helpers.single_keyword(
"-moz-box-align",
"stretch start center baseline end",
products="gecko",
gecko_ffi_name="mBoxAlign",
gecko_enum_prefix="StyleBoxAlign",
animation_value_type="discrete",
alias="-webkit-box-align",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-align)",
)}
${helpers.single_keyword(
"-moz-box-direction",
"normal reverse",
products="gecko",
gecko_ffi_name="mBoxDirection",
gecko_enum_prefix="StyleBoxDirection",
animation_value_type="discrete",
|
alias="-webkit-box-direction",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-direction)",
)}
${helpers.predefined_type(
"-moz-box-flex",
"NonNegativeNumber",
"From::from(0.)",
products="gecko",
gecko_ffi_name="mBoxFlex",
animation_value_type="NonNegativeNumber",
alias="-webkit-box-flex",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-flex)",
)}
${helpers.single_keyword(
"-moz-box-orient",
"horizontal vertical",
products="gecko",
gecko_ffi_name="mBoxOrient",
extra_gecko_aliases="inline-axis=horizontal block-axis=vertical",
gecko_enum_prefix="StyleBoxOrient",
animation_value_type="discrete",
alias="-webkit-box-orient",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-orient)",
)}
${helpers.single_keyword(
"-moz-box-pack",
"start center end justify",
products="gecko", gecko_ffi_name="mBoxPack",
gecko_enum_prefix="StyleBoxPack",
animation_value_type="discrete",
alias="-webkit-box-pack",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/box-pack)",
)}
${helpers.single_keyword(
"-moz-stack-sizing",
"stretch-to-fit ignore ignore-horizontal ignore-vertical",
products="gecko",
gecko_ffi_name="mStackSizing",
gecko_enum_prefix="StyleStackSizing",
animation_value_type="discrete",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-stack-sizing)",
)}
${helpers.predefined_type(
"-moz-box-ordinal-group",
"Integer",
"0",
parse_method="parse_non_negative",
products="gecko",
alias="-webkit-box-ordinal-group",
gecko_ffi_name="mBoxOrdinal",
animation_value_type="discrete",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-box-ordinal-group)",
)}
|
random_line_split
|
|
issue-3121.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.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
#[derive(Copy, Clone)]
enum side { mayo, catsup, vinegar }
#[derive(Copy, Clone)]
enum order { hamburger, fries(side), shake }
#[derive(Copy, Clone)]
enum meal { to_go(order), for_here(order) }
fn foo(m: Box<meal>, cond: bool) {
match *m {
meal::to_go(_) =>
|
meal::for_here(_) if cond => {}
meal::for_here(order::hamburger) => {}
meal::for_here(order::fries(_s)) => {}
meal::for_here(order::shake) => {}
}
}
pub fn main() {
foo(box meal::for_here(order::hamburger), true)
}
|
{ }
|
conditional_block
|
issue-3121.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.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
#[derive(Copy, Clone)]
enum side { mayo, catsup, vinegar }
#[derive(Copy, Clone)]
enum order { hamburger, fries(side), shake }
#[derive(Copy, Clone)]
enum meal { to_go(order), for_here(order) }
fn foo(m: Box<meal>, cond: bool) {
match *m {
meal::to_go(_) => { }
meal::for_here(_) if cond => {}
meal::for_here(order::hamburger) => {}
meal::for_here(order::fries(_s)) => {}
meal::for_here(order::shake) => {}
}
|
}
pub fn main() {
foo(box meal::for_here(order::hamburger), true)
}
|
random_line_split
|
|
issue-3121.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.
// pretty-expanded FIXME #23616
#![allow(unknown_features)]
#![feature(box_syntax)]
#[derive(Copy, Clone)]
enum side { mayo, catsup, vinegar }
#[derive(Copy, Clone)]
enum
|
{ hamburger, fries(side), shake }
#[derive(Copy, Clone)]
enum meal { to_go(order), for_here(order) }
fn foo(m: Box<meal>, cond: bool) {
match *m {
meal::to_go(_) => { }
meal::for_here(_) if cond => {}
meal::for_here(order::hamburger) => {}
meal::for_here(order::fries(_s)) => {}
meal::for_here(order::shake) => {}
}
}
pub fn main() {
foo(box meal::for_here(order::hamburger), true)
}
|
order
|
identifier_name
|
skia.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/.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use libc::*;
pub type SkiaSkNativeSharedGLContextRef = *mut c_void;
pub type SkiaGrContextRef = *mut c_void;
pub type SkiaGrGLSharedSurfaceRef = *mut c_void;
pub type SkiaGrGLNativeContextRef = *mut c_void;
#[link(name = "skia")]
extern {
pub fn SkiaSkNativeSharedGLContextCreate(aNativeContext: SkiaGrGLNativeContextRef, aWidth: i32, aHeight: i32) -> SkiaSkNativeSharedGLContextRef;
pub fn SkiaSkNativeSharedGLContextRetain(aGLContext: SkiaSkNativeSharedGLContextRef);
pub fn SkiaSkNativeSharedGLContextRelease(aGLContext: SkiaSkNativeSharedGLContextRef);
|
pub fn SkiaSkNativeSharedGLContextGetFBOID(aGLContext: SkiaSkNativeSharedGLContextRef) -> c_uint;
pub fn SkiaSkNativeSharedGLContextStealSurface(aGLContext: SkiaSkNativeSharedGLContextRef) -> SkiaGrGLSharedSurfaceRef;
pub fn SkiaSkNativeSharedGLContextGetGrContext(aGLContext: SkiaSkNativeSharedGLContextRef) -> SkiaGrContextRef;
pub fn SkiaSkNativeSharedGLContextMakeCurrent(aGLContext: SkiaSkNativeSharedGLContextRef);
pub fn SkiaSkNativeSharedGLContextFlush(aGLContext: SkiaSkNativeSharedGLContextRef);
}
|
random_line_split
|
|
op.rs
|
nop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
expr: &'tcx ast::Expr,
op: ast::BinOp,
lhs_expr: &'tcx ast::Expr,
rhs_expr: &'tcx ast::Expr)
{
let tcx = fcx.ccx.tcx;
check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
check_expr(fcx, rhs_expr);
let lhs_ty = structurally_resolved_type(fcx, lhs_expr.span, fcx.expr_ty(lhs_expr));
let rhs_ty = structurally_resolved_type(fcx, rhs_expr.span, fcx.expr_ty(rhs_expr));
if is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op) {
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
fcx.write_nil(expr.id);
} else {
// error types are considered "builtin"
assert!(!ty::type_is_error(lhs_ty) ||!ty::type_is_error(rhs_ty));
span_err!(tcx.sess, lhs_expr.span, E0368,
"binary assignment operation `{}=` cannot be applied to types `{}` and `{}`",
ast_util::binop_to_string(op.node),
lhs_ty,
rhs_ty);
fcx.write_error(expr.id);
}
let tcx = fcx.tcx();
if!ty::expr_is_lval(tcx, lhs_expr) {
span_err!(tcx.sess, lhs_expr.span, E0067, "illegal left-hand side expression");
}
fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
}
/// Check a potentially overloaded binary operator.
pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
op: ast::BinOp,
lhs_expr: &'tcx ast::Expr,
rhs_expr: &'tcx ast::Expr)
{
let tcx = fcx.ccx.tcx;
debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
expr.id,
expr,
op,
lhs_expr,
rhs_expr);
check_expr(fcx, lhs_expr);
let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
// Annoyingly, SIMD ops don't fit into the PartialEq/PartialOrd
// traits, because their return type is not bool. Perhaps this
// should change, but for now if LHS is SIMD we go down a
// different path that bypassess all traits.
if ty::type_is_simd(fcx.tcx(), lhs_ty) {
check_expr_coercable_to_type(fcx, rhs_expr, lhs_ty);
let rhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
let return_ty = enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
fcx.write_ty(expr.id, return_ty);
return;
}
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
// && and || are a simple case.
demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
check_expr_coercable_to_type(fcx, rhs_expr, ty::mk_bool(tcx));
fcx.write_ty(expr.id, ty::mk_bool(tcx));
}
_ => {
// Otherwise, we always treat operators as if they are
// overloaded. This is the way to be most flexible w/r/t
// types that get inferred.
let (rhs_ty, return_ty) =
check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
// Supply type inference hints if relevant. Probably these
// hints should be enforced during select as part of the
// `consider_unification_despite_ambiguity` routine, but this
// more convenient for now.
//
// The basic idea is to help type inference by taking
// advantage of things we know about how the impls for
// scalar types are arranged. This is important in a
// scenario like `1_u32 << 2`, because it lets us quickly
// deduce that the result type should be `u32`, even
// though we don't know yet what type 2 has and hence
// can't pin this down to a specific impl.
let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
if
!ty::type_is_ty_var(lhs_ty) &&
!ty::type_is_ty_var(rhs_ty) &&
is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op)
{
let builtin_return_ty =
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
demand::suptype(fcx, expr.span, builtin_return_ty, return_ty);
}
fcx.write_ty(expr.id, return_ty);
}
}
}
fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
lhs_expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx ast::Expr,
rhs_ty: Ty<'tcx>,
op: ast::BinOp)
-> Ty<'tcx>
{
debug_assert!(is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op));
let tcx = fcx.tcx();
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
demand::suptype(fcx, rhs_expr.span, ty::mk_bool(tcx), rhs_ty);
ty::mk_bool(tcx)
}
BinOpCategory::Shift => {
// For integers, the shift amount can be of any integral
// type. For simd, the type must match exactly.
if ty::type_is_simd(tcx, lhs_ty) {
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
}
// result type is same as LHS always
lhs_ty
}
BinOpCategory::Math |
BinOpCategory::Bitwise => {
// both LHS and RHS and result will have the same type
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
lhs_ty
}
BinOpCategory::Comparison => {
// both LHS and RHS and result will have the same type
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
// if this is simd, result is same as lhs, else bool
if ty::type_is_simd(tcx, lhs_ty) {
let unit_ty = ty::simd_type(tcx, lhs_ty);
debug!("enforce_builtin_binop_types: lhs_ty={:?} unit_ty={:?}",
lhs_ty,
unit_ty);
if!ty::type_is_integral(unit_ty) {
tcx.sess.span_err(
lhs_expr.span,
&format!("binary comparison operation `{}` not supported \
for floating point SIMD vector `{}`",
ast_util::binop_to_string(op.node),
lhs_ty));
tcx.types.err
} else {
lhs_ty
}
} else {
ty::mk_bool(tcx)
}
}
}
}
fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
lhs_expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx ast::Expr,
op: ast::BinOp)
-> (Ty<'tcx>, Ty<'tcx>)
{
debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
expr.id,
lhs_ty);
let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
// NB: As we have not yet type-checked the RHS, we don't have the
// type at hand. Make a variable to represent it. The whole reason
// for this indirection is so that, below, we can check the expr
// using this variable as the expected type, which sometimes lets
// us do better coercions than we would be able to do otherwise,
// particularly for things like `String + &String`.
let rhs_ty_var = fcx.infcx().next_ty_var();
let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
token::intern(name), trait_def_id,
lhs_expr) {
Ok(return_ty) => return_ty,
Err(()) => {
// error types are considered "builtin"
if!ty::type_is_error(lhs_ty) {
span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
"binary operation `{}` cannot be applied to type `{}`",
ast_util::binop_to_string(op.node),
lhs_ty);
}
fcx.tcx().types.err
}
};
// see `NB` above
check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
(rhs_ty_var, return_ty)
}
pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
op_str: &str,
mname: &str,
trait_did: Option<ast::DefId>,
ex: &'tcx ast::Expr,
operand_expr: &'tcx ast::Expr,
operand_ty: Ty<'tcx>,
op: ast::UnOp)
-> Ty<'tcx>
{
assert!(ast_util::is_by_value_unop(op));
match lookup_op_method(fcx, ex, operand_ty, vec![],
token::intern(mname), trait_did,
operand_expr) {
Ok(t) => t,
Err(()) => {
fcx.type_error_message(ex.span, |actual| {
format!("cannot apply unary operator `{}` to type `{}`",
op_str, actual)
}, operand_ty, None);
fcx.tcx().types.err
}
}
}
fn name_and_trait_def_id(fcx: &FnCtxt, op: ast::BinOp) -> (&'static str, Option<ast::DefId>) {
let lang = &fcx.tcx().lang_items;
match op.node {
ast::BiAdd => ("add", lang.add_trait()),
ast::BiSub => ("sub", lang.sub_trait()),
ast::BiMul => ("mul", lang.mul_trait()),
ast::BiDiv => ("div", lang.div_trait()),
ast::BiRem => ("rem", lang.rem_trait()),
ast::BiBitXor => ("bitxor", lang.bitxor_trait()),
ast::BiBitAnd => ("bitand", lang.bitand_trait()),
ast::BiBitOr => ("bitor", lang.bitor_trait()),
ast::BiShl => ("shl", lang.shl_trait()),
ast::BiShr => ("shr", lang.shr_trait()),
ast::BiLt => ("lt", lang.ord_trait()),
ast::BiLe => ("le", lang.ord_trait()),
ast::BiGe => ("ge", lang.ord_trait()),
ast::BiGt => ("gt", lang.ord_trait()),
ast::BiEq => ("eq", lang.eq_trait()),
ast::BiNe => ("ne", lang.eq_trait()),
ast::BiAnd | ast::BiOr => {
fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
}
}
}
fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
other_tys: Vec<Ty<'tcx>>,
opname: ast::Name,
trait_did: Option<ast::DefId>,
lhs_expr: &'a ast::Expr)
-> Result<Ty<'tcx>,()>
{
debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
expr,
lhs_ty,
opname,
trait_did,
lhs_expr);
let method = match trait_did {
Some(trait_did) => {
method::lookup_in_trait_adjusted(fcx,
expr.span,
Some(lhs_expr),
opname,
trait_did,
0,
false,
lhs_ty,
Some(other_tys))
}
None => None
};
match method {
Some(method) =>
|
None => {
Err(())
}
}
}
// Binary operator categories. These categories summarize the behavior
// with respect to the builtin operationrs supported.
enum BinOpCategory {
/// &&, || -- cannot be overridden
Shortcircuit,
/// <<, >> -- when shifting a single integer, rhs can be any
/// integer type. For simd, types must match.
Shift,
/// +, -, etc -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd
Math,
/// &, |, ^ -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd/bool
Bitwise,
/// ==,!=, etc -- takes equal types, produces bools, except for simd,
/// which produce the input type
Comparison,
}
impl BinOpCategory {
fn from(op: ast::BinOp) -> BinOpCategory {
match op.node {
ast::BiShl | ast::BiShr =>
BinOpCategory::Shift,
ast::BiAdd |
ast::BiSub |
ast::BiMul |
ast::BiDiv |
ast::BiRem =>
BinOpCategory::Math,
ast::BiBitXor |
ast::BiBitAnd |
ast::BiBitOr =>
BinOpCategory::Bitwise,
ast::BiEq |
ast::BiNe |
ast::BiLt |
ast::BiLe |
ast::BiGe |
ast::BiGt =>
BinOpCategory::Comparison,
ast::BiAnd |
ast::BiOr =>
BinOpCategory::Shortcircuit,
}
}
}
/// Returns true if this is a built-in arithmetic operation (e.g. u32
/// + u32, i16x4 == i16x4) and false if these types would have to be
/// overloaded to be legal. There are two reasons that we distinguish
/// builtin operations from overloaded ones (vs trying to drive
/// everything uniformly through the trait system and intrinsics or
/// something like that):
///
/// 1. Builtin operations can trivially be evaluated in constants.
/// 2. For comparison operators applied to SIMD types the result is
/// not of type `bool`. For example, `i16x4==i16x4` yields a
/// type like `i16x4`. This means that the overloaded trait
/// `PartialEq` is not applicable.
///
/// Reason #2 is the killer. I tried for a while to always use
/// overloaded logic and just check the types in constants/trans after
/// the fact, and it worked fine, except for SIMD types. -nmatsakis
fn is_builtin_binop<'tcx>(cx: &ty::ctxt<'tcx>,
lhs: Ty<'tcx>,
rhs: Ty<'tcx>,
op: ast::BinOp)
-> bool
{
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
true
}
BinOpCategory::Shift => {
ty::type_is_error(lhs) || ty
|
{
let method_ty = method.ty;
// HACK(eddyb) Fully qualified path to work around a resolve bug.
let method_call = ::middle::ty::MethodCall::expr(expr.id);
fcx.inh.method_map.borrow_mut().insert(method_call, method);
// extract return type for method; all late bound regions
// should have been instantiated by now
let ret_ty = ty::ty_fn_ret(method_ty);
Ok(ty::no_late_bound_regions(fcx.tcx(), &ret_ty).unwrap().unwrap())
}
|
conditional_block
|
op.rs
|
_binop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
expr: &'tcx ast::Expr,
op: ast::BinOp,
lhs_expr: &'tcx ast::Expr,
rhs_expr: &'tcx ast::Expr)
{
let tcx = fcx.ccx.tcx;
check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
check_expr(fcx, rhs_expr);
let lhs_ty = structurally_resolved_type(fcx, lhs_expr.span, fcx.expr_ty(lhs_expr));
let rhs_ty = structurally_resolved_type(fcx, rhs_expr.span, fcx.expr_ty(rhs_expr));
if is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op) {
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
fcx.write_nil(expr.id);
} else {
// error types are considered "builtin"
assert!(!ty::type_is_error(lhs_ty) ||!ty::type_is_error(rhs_ty));
span_err!(tcx.sess, lhs_expr.span, E0368,
"binary assignment operation `{}=` cannot be applied to types `{}` and `{}`",
ast_util::binop_to_string(op.node),
lhs_ty,
rhs_ty);
fcx.write_error(expr.id);
}
let tcx = fcx.tcx();
if!ty::expr_is_lval(tcx, lhs_expr) {
span_err!(tcx.sess, lhs_expr.span, E0067, "illegal left-hand side expression");
}
fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
}
/// Check a potentially overloaded binary operator.
pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
op: ast::BinOp,
lhs_expr: &'tcx ast::Expr,
rhs_expr: &'tcx ast::Expr)
{
let tcx = fcx.ccx.tcx;
debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
expr.id,
expr,
op,
lhs_expr,
rhs_expr);
check_expr(fcx, lhs_expr);
let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
// Annoyingly, SIMD ops don't fit into the PartialEq/PartialOrd
// traits, because their return type is not bool. Perhaps this
// should change, but for now if LHS is SIMD we go down a
// different path that bypassess all traits.
if ty::type_is_simd(fcx.tcx(), lhs_ty) {
check_expr_coercable_to_type(fcx, rhs_expr, lhs_ty);
let rhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
let return_ty = enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
fcx.write_ty(expr.id, return_ty);
return;
}
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
// && and || are a simple case.
demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
check_expr_coercable_to_type(fcx, rhs_expr, ty::mk_bool(tcx));
fcx.write_ty(expr.id, ty::mk_bool(tcx));
}
_ => {
// Otherwise, we always treat operators as if they are
// overloaded. This is the way to be most flexible w/r/t
// types that get inferred.
let (rhs_ty, return_ty) =
check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
// Supply type inference hints if relevant. Probably these
// hints should be enforced during select as part of the
// `consider_unification_despite_ambiguity` routine, but this
// more convenient for now.
//
// The basic idea is to help type inference by taking
// advantage of things we know about how the impls for
// scalar types are arranged. This is important in a
// scenario like `1_u32 << 2`, because it lets us quickly
// deduce that the result type should be `u32`, even
// though we don't know yet what type 2 has and hence
// can't pin this down to a specific impl.
let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
if
!ty::type_is_ty_var(lhs_ty) &&
!ty::type_is_ty_var(rhs_ty) &&
is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op)
{
let builtin_return_ty =
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
demand::suptype(fcx, expr.span, builtin_return_ty, return_ty);
}
fcx.write_ty(expr.id, return_ty);
}
}
}
fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
lhs_expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx ast::Expr,
rhs_ty: Ty<'tcx>,
op: ast::BinOp)
-> Ty<'tcx>
{
debug_assert!(is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op));
let tcx = fcx.tcx();
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
demand::suptype(fcx, rhs_expr.span, ty::mk_bool(tcx), rhs_ty);
ty::mk_bool(tcx)
}
BinOpCategory::Shift => {
// For integers, the shift amount can be of any integral
// type. For simd, the type must match exactly.
if ty::type_is_simd(tcx, lhs_ty) {
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
}
// result type is same as LHS always
lhs_ty
}
BinOpCategory::Math |
BinOpCategory::Bitwise => {
// both LHS and RHS and result will have the same type
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
lhs_ty
}
BinOpCategory::Comparison => {
// both LHS and RHS and result will have the same type
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
// if this is simd, result is same as lhs, else bool
if ty::type_is_simd(tcx, lhs_ty) {
let unit_ty = ty::simd_type(tcx, lhs_ty);
debug!("enforce_builtin_binop_types: lhs_ty={:?} unit_ty={:?}",
lhs_ty,
unit_ty);
if!ty::type_is_integral(unit_ty) {
tcx.sess.span_err(
lhs_expr.span,
&format!("binary comparison operation `{}` not supported \
for floating point SIMD vector `{}`",
ast_util::binop_to_string(op.node),
lhs_ty));
tcx.types.err
} else {
lhs_ty
}
} else {
ty::mk_bool(tcx)
}
}
}
}
fn check_overloaded_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
lhs_expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx ast::Expr,
op: ast::BinOp)
-> (Ty<'tcx>, Ty<'tcx>)
{
debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
expr.id,
lhs_ty);
let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
// NB: As we have not yet type-checked the RHS, we don't have the
// type at hand. Make a variable to represent it. The whole reason
// for this indirection is so that, below, we can check the expr
// using this variable as the expected type, which sometimes lets
// us do better coercions than we would be able to do otherwise,
// particularly for things like `String + &String`.
let rhs_ty_var = fcx.infcx().next_ty_var();
let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
token::intern(name), trait_def_id,
lhs_expr) {
Ok(return_ty) => return_ty,
Err(()) => {
// error types are considered "builtin"
if!ty::type_is_error(lhs_ty) {
span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
"binary operation `{}` cannot be applied to type `{}`",
ast_util::binop_to_string(op.node),
lhs_ty);
}
fcx.tcx().types.err
}
};
// see `NB` above
check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
(rhs_ty_var, return_ty)
}
pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
op_str: &str,
mname: &str,
trait_did: Option<ast::DefId>,
ex: &'tcx ast::Expr,
operand_expr: &'tcx ast::Expr,
operand_ty: Ty<'tcx>,
op: ast::UnOp)
-> Ty<'tcx>
{
assert!(ast_util::is_by_value_unop(op));
match lookup_op_method(fcx, ex, operand_ty, vec![],
token::intern(mname), trait_did,
operand_expr) {
Ok(t) => t,
Err(()) => {
fcx.type_error_message(ex.span, |actual| {
format!("cannot apply unary operator `{}` to type `{}`",
op_str, actual)
}, operand_ty, None);
fcx.tcx().types.err
}
}
}
fn name_and_trait_def_id(fcx: &FnCtxt, op: ast::BinOp) -> (&'static str, Option<ast::DefId>) {
let lang = &fcx.tcx().lang_items;
match op.node {
ast::BiAdd => ("add", lang.add_trait()),
ast::BiSub => ("sub", lang.sub_trait()),
ast::BiMul => ("mul", lang.mul_trait()),
ast::BiDiv => ("div", lang.div_trait()),
ast::BiRem => ("rem", lang.rem_trait()),
ast::BiBitXor => ("bitxor", lang.bitxor_trait()),
ast::BiBitAnd => ("bitand", lang.bitand_trait()),
ast::BiBitOr => ("bitor", lang.bitor_trait()),
ast::BiShl => ("shl", lang.shl_trait()),
ast::BiShr => ("shr", lang.shr_trait()),
ast::BiLt => ("lt", lang.ord_trait()),
ast::BiLe => ("le", lang.ord_trait()),
ast::BiGe => ("ge", lang.ord_trait()),
ast::BiGt => ("gt", lang.ord_trait()),
ast::BiEq => ("eq", lang.eq_trait()),
ast::BiNe => ("ne", lang.eq_trait()),
ast::BiAnd | ast::BiOr => {
fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
}
}
}
fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
other_tys: Vec<Ty<'tcx>>,
opname: ast::Name,
trait_did: Option<ast::DefId>,
lhs_expr: &'a ast::Expr)
-> Result<Ty<'tcx>,()>
{
debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
expr,
lhs_ty,
opname,
trait_did,
lhs_expr);
let method = match trait_did {
Some(trait_did) => {
method::lookup_in_trait_adjusted(fcx,
expr.span,
Some(lhs_expr),
opname,
trait_did,
0,
false,
lhs_ty,
Some(other_tys))
}
None => None
};
match method {
Some(method) => {
let method_ty = method.ty;
// HACK(eddyb) Fully qualified path to work around a resolve bug.
let method_call = ::middle::ty::MethodCall::expr(expr.id);
fcx.inh.method_map.borrow_mut().insert(method_call, method);
// extract return type for method; all late bound regions
// should have been instantiated by now
let ret_ty = ty::ty_fn_ret(method_ty);
Ok(ty::no_late_bound_regions(fcx.tcx(), &ret_ty).unwrap().unwrap())
}
None => {
Err(())
}
}
}
// Binary operator categories. These categories summarize the behavior
// with respect to the builtin operationrs supported.
enum BinOpCategory {
/// &&, || -- cannot be overridden
Shortcircuit,
/// <<, >> -- when shifting a single integer, rhs can be any
/// integer type. For simd, types must match.
Shift,
/// +, -, etc -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd
Math,
/// &, |, ^ -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd/bool
Bitwise,
/// ==,!=, etc -- takes equal types, produces bools, except for simd,
/// which produce the input type
Comparison,
}
impl BinOpCategory {
fn from(op: ast::BinOp) -> BinOpCategory {
match op.node {
ast::BiShl | ast::BiShr =>
BinOpCategory::Shift,
ast::BiAdd |
ast::BiSub |
ast::BiMul |
ast::BiDiv |
ast::BiRem =>
BinOpCategory::Math,
ast::BiBitXor |
ast::BiBitAnd |
ast::BiBitOr =>
BinOpCategory::Bitwise,
ast::BiEq |
ast::BiNe |
ast::BiLt |
ast::BiLe |
ast::BiGe |
ast::BiGt =>
BinOpCategory::Comparison,
ast::BiAnd |
ast::BiOr =>
BinOpCategory::Shortcircuit,
}
}
}
/// Returns true if this is a built-in arithmetic operation (e.g. u32
/// + u32, i16x4 == i16x4) and false if these types would have to be
/// overloaded to be legal. There are two reasons that we distinguish
/// builtin operations from overloaded ones (vs trying to drive
|
/// 1. Builtin operations can trivially be evaluated in constants.
/// 2. For comparison operators applied to SIMD types the result is
/// not of type `bool`. For example, `i16x4==i16x4` yields a
/// type like `i16x4`. This means that the overloaded trait
/// `PartialEq` is not applicable.
///
/// Reason #2 is the killer. I tried for a while to always use
/// overloaded logic and just check the types in constants/trans after
/// the fact, and it worked fine, except for SIMD types. -nmatsakis
fn is_builtin_binop<'tcx>(cx: &ty::ctxt<'tcx>,
lhs: Ty<'tcx>,
rhs: Ty<'tcx>,
op: ast::BinOp)
-> bool
{
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
true
}
BinOpCategory::Shift => {
ty::type_is_error(lhs) || ty::
|
/// everything uniformly through the trait system and intrinsics or
/// something like that):
///
|
random_line_split
|
op.rs
|
nop_assign<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
expr: &'tcx ast::Expr,
op: ast::BinOp,
lhs_expr: &'tcx ast::Expr,
rhs_expr: &'tcx ast::Expr)
{
let tcx = fcx.ccx.tcx;
check_expr_with_lvalue_pref(fcx, lhs_expr, PreferMutLvalue);
check_expr(fcx, rhs_expr);
let lhs_ty = structurally_resolved_type(fcx, lhs_expr.span, fcx.expr_ty(lhs_expr));
let rhs_ty = structurally_resolved_type(fcx, rhs_expr.span, fcx.expr_ty(rhs_expr));
if is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op) {
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
fcx.write_nil(expr.id);
} else {
// error types are considered "builtin"
assert!(!ty::type_is_error(lhs_ty) ||!ty::type_is_error(rhs_ty));
span_err!(tcx.sess, lhs_expr.span, E0368,
"binary assignment operation `{}=` cannot be applied to types `{}` and `{}`",
ast_util::binop_to_string(op.node),
lhs_ty,
rhs_ty);
fcx.write_error(expr.id);
}
let tcx = fcx.tcx();
if!ty::expr_is_lval(tcx, lhs_expr) {
span_err!(tcx.sess, lhs_expr.span, E0067, "illegal left-hand side expression");
}
fcx.require_expr_have_sized_type(lhs_expr, traits::AssignmentLhsSized);
}
/// Check a potentially overloaded binary operator.
pub fn check_binop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
op: ast::BinOp,
lhs_expr: &'tcx ast::Expr,
rhs_expr: &'tcx ast::Expr)
{
let tcx = fcx.ccx.tcx;
debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
expr.id,
expr,
op,
lhs_expr,
rhs_expr);
check_expr(fcx, lhs_expr);
let lhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
// Annoyingly, SIMD ops don't fit into the PartialEq/PartialOrd
// traits, because their return type is not bool. Perhaps this
// should change, but for now if LHS is SIMD we go down a
// different path that bypassess all traits.
if ty::type_is_simd(fcx.tcx(), lhs_ty) {
check_expr_coercable_to_type(fcx, rhs_expr, lhs_ty);
let rhs_ty = fcx.resolve_type_vars_if_possible(fcx.expr_ty(lhs_expr));
let return_ty = enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
fcx.write_ty(expr.id, return_ty);
return;
}
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
// && and || are a simple case.
demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
check_expr_coercable_to_type(fcx, rhs_expr, ty::mk_bool(tcx));
fcx.write_ty(expr.id, ty::mk_bool(tcx));
}
_ => {
// Otherwise, we always treat operators as if they are
// overloaded. This is the way to be most flexible w/r/t
// types that get inferred.
let (rhs_ty, return_ty) =
check_overloaded_binop(fcx, expr, lhs_expr, lhs_ty, rhs_expr, op);
// Supply type inference hints if relevant. Probably these
// hints should be enforced during select as part of the
// `consider_unification_despite_ambiguity` routine, but this
// more convenient for now.
//
// The basic idea is to help type inference by taking
// advantage of things we know about how the impls for
// scalar types are arranged. This is important in a
// scenario like `1_u32 << 2`, because it lets us quickly
// deduce that the result type should be `u32`, even
// though we don't know yet what type 2 has and hence
// can't pin this down to a specific impl.
let rhs_ty = fcx.resolve_type_vars_if_possible(rhs_ty);
if
!ty::type_is_ty_var(lhs_ty) &&
!ty::type_is_ty_var(rhs_ty) &&
is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op)
{
let builtin_return_ty =
enforce_builtin_binop_types(fcx, lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
demand::suptype(fcx, expr.span, builtin_return_ty, return_ty);
}
fcx.write_ty(expr.id, return_ty);
}
}
}
fn enforce_builtin_binop_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
lhs_expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx ast::Expr,
rhs_ty: Ty<'tcx>,
op: ast::BinOp)
-> Ty<'tcx>
{
debug_assert!(is_builtin_binop(fcx.tcx(), lhs_ty, rhs_ty, op));
let tcx = fcx.tcx();
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
demand::suptype(fcx, lhs_expr.span, ty::mk_bool(tcx), lhs_ty);
demand::suptype(fcx, rhs_expr.span, ty::mk_bool(tcx), rhs_ty);
ty::mk_bool(tcx)
}
BinOpCategory::Shift => {
// For integers, the shift amount can be of any integral
// type. For simd, the type must match exactly.
if ty::type_is_simd(tcx, lhs_ty) {
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
}
// result type is same as LHS always
lhs_ty
}
BinOpCategory::Math |
BinOpCategory::Bitwise => {
// both LHS and RHS and result will have the same type
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
lhs_ty
}
BinOpCategory::Comparison => {
// both LHS and RHS and result will have the same type
demand::suptype(fcx, rhs_expr.span, lhs_ty, rhs_ty);
// if this is simd, result is same as lhs, else bool
if ty::type_is_simd(tcx, lhs_ty) {
let unit_ty = ty::simd_type(tcx, lhs_ty);
debug!("enforce_builtin_binop_types: lhs_ty={:?} unit_ty={:?}",
lhs_ty,
unit_ty);
if!ty::type_is_integral(unit_ty) {
tcx.sess.span_err(
lhs_expr.span,
&format!("binary comparison operation `{}` not supported \
for floating point SIMD vector `{}`",
ast_util::binop_to_string(op.node),
lhs_ty));
tcx.types.err
} else {
lhs_ty
}
} else {
ty::mk_bool(tcx)
}
}
}
}
fn
|
<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
lhs_expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
rhs_expr: &'tcx ast::Expr,
op: ast::BinOp)
-> (Ty<'tcx>, Ty<'tcx>)
{
debug!("check_overloaded_binop(expr.id={}, lhs_ty={:?})",
expr.id,
lhs_ty);
let (name, trait_def_id) = name_and_trait_def_id(fcx, op);
// NB: As we have not yet type-checked the RHS, we don't have the
// type at hand. Make a variable to represent it. The whole reason
// for this indirection is so that, below, we can check the expr
// using this variable as the expected type, which sometimes lets
// us do better coercions than we would be able to do otherwise,
// particularly for things like `String + &String`.
let rhs_ty_var = fcx.infcx().next_ty_var();
let return_ty = match lookup_op_method(fcx, expr, lhs_ty, vec![rhs_ty_var],
token::intern(name), trait_def_id,
lhs_expr) {
Ok(return_ty) => return_ty,
Err(()) => {
// error types are considered "builtin"
if!ty::type_is_error(lhs_ty) {
span_err!(fcx.tcx().sess, lhs_expr.span, E0369,
"binary operation `{}` cannot be applied to type `{}`",
ast_util::binop_to_string(op.node),
lhs_ty);
}
fcx.tcx().types.err
}
};
// see `NB` above
check_expr_coercable_to_type(fcx, rhs_expr, rhs_ty_var);
(rhs_ty_var, return_ty)
}
pub fn check_user_unop<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
op_str: &str,
mname: &str,
trait_did: Option<ast::DefId>,
ex: &'tcx ast::Expr,
operand_expr: &'tcx ast::Expr,
operand_ty: Ty<'tcx>,
op: ast::UnOp)
-> Ty<'tcx>
{
assert!(ast_util::is_by_value_unop(op));
match lookup_op_method(fcx, ex, operand_ty, vec![],
token::intern(mname), trait_did,
operand_expr) {
Ok(t) => t,
Err(()) => {
fcx.type_error_message(ex.span, |actual| {
format!("cannot apply unary operator `{}` to type `{}`",
op_str, actual)
}, operand_ty, None);
fcx.tcx().types.err
}
}
}
fn name_and_trait_def_id(fcx: &FnCtxt, op: ast::BinOp) -> (&'static str, Option<ast::DefId>) {
let lang = &fcx.tcx().lang_items;
match op.node {
ast::BiAdd => ("add", lang.add_trait()),
ast::BiSub => ("sub", lang.sub_trait()),
ast::BiMul => ("mul", lang.mul_trait()),
ast::BiDiv => ("div", lang.div_trait()),
ast::BiRem => ("rem", lang.rem_trait()),
ast::BiBitXor => ("bitxor", lang.bitxor_trait()),
ast::BiBitAnd => ("bitand", lang.bitand_trait()),
ast::BiBitOr => ("bitor", lang.bitor_trait()),
ast::BiShl => ("shl", lang.shl_trait()),
ast::BiShr => ("shr", lang.shr_trait()),
ast::BiLt => ("lt", lang.ord_trait()),
ast::BiLe => ("le", lang.ord_trait()),
ast::BiGe => ("ge", lang.ord_trait()),
ast::BiGt => ("gt", lang.ord_trait()),
ast::BiEq => ("eq", lang.eq_trait()),
ast::BiNe => ("ne", lang.eq_trait()),
ast::BiAnd | ast::BiOr => {
fcx.tcx().sess.span_bug(op.span, "&& and || are not overloadable")
}
}
}
fn lookup_op_method<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>,
expr: &'tcx ast::Expr,
lhs_ty: Ty<'tcx>,
other_tys: Vec<Ty<'tcx>>,
opname: ast::Name,
trait_did: Option<ast::DefId>,
lhs_expr: &'a ast::Expr)
-> Result<Ty<'tcx>,()>
{
debug!("lookup_op_method(expr={:?}, lhs_ty={:?}, opname={:?}, trait_did={:?}, lhs_expr={:?})",
expr,
lhs_ty,
opname,
trait_did,
lhs_expr);
let method = match trait_did {
Some(trait_did) => {
method::lookup_in_trait_adjusted(fcx,
expr.span,
Some(lhs_expr),
opname,
trait_did,
0,
false,
lhs_ty,
Some(other_tys))
}
None => None
};
match method {
Some(method) => {
let method_ty = method.ty;
// HACK(eddyb) Fully qualified path to work around a resolve bug.
let method_call = ::middle::ty::MethodCall::expr(expr.id);
fcx.inh.method_map.borrow_mut().insert(method_call, method);
// extract return type for method; all late bound regions
// should have been instantiated by now
let ret_ty = ty::ty_fn_ret(method_ty);
Ok(ty::no_late_bound_regions(fcx.tcx(), &ret_ty).unwrap().unwrap())
}
None => {
Err(())
}
}
}
// Binary operator categories. These categories summarize the behavior
// with respect to the builtin operationrs supported.
enum BinOpCategory {
/// &&, || -- cannot be overridden
Shortcircuit,
/// <<, >> -- when shifting a single integer, rhs can be any
/// integer type. For simd, types must match.
Shift,
/// +, -, etc -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd
Math,
/// &, |, ^ -- takes equal types, produces same type as input,
/// applicable to ints/floats/simd/bool
Bitwise,
/// ==,!=, etc -- takes equal types, produces bools, except for simd,
/// which produce the input type
Comparison,
}
impl BinOpCategory {
fn from(op: ast::BinOp) -> BinOpCategory {
match op.node {
ast::BiShl | ast::BiShr =>
BinOpCategory::Shift,
ast::BiAdd |
ast::BiSub |
ast::BiMul |
ast::BiDiv |
ast::BiRem =>
BinOpCategory::Math,
ast::BiBitXor |
ast::BiBitAnd |
ast::BiBitOr =>
BinOpCategory::Bitwise,
ast::BiEq |
ast::BiNe |
ast::BiLt |
ast::BiLe |
ast::BiGe |
ast::BiGt =>
BinOpCategory::Comparison,
ast::BiAnd |
ast::BiOr =>
BinOpCategory::Shortcircuit,
}
}
}
/// Returns true if this is a built-in arithmetic operation (e.g. u32
/// + u32, i16x4 == i16x4) and false if these types would have to be
/// overloaded to be legal. There are two reasons that we distinguish
/// builtin operations from overloaded ones (vs trying to drive
/// everything uniformly through the trait system and intrinsics or
/// something like that):
///
/// 1. Builtin operations can trivially be evaluated in constants.
/// 2. For comparison operators applied to SIMD types the result is
/// not of type `bool`. For example, `i16x4==i16x4` yields a
/// type like `i16x4`. This means that the overloaded trait
/// `PartialEq` is not applicable.
///
/// Reason #2 is the killer. I tried for a while to always use
/// overloaded logic and just check the types in constants/trans after
/// the fact, and it worked fine, except for SIMD types. -nmatsakis
fn is_builtin_binop<'tcx>(cx: &ty::ctxt<'tcx>,
lhs: Ty<'tcx>,
rhs: Ty<'tcx>,
op: ast::BinOp)
-> bool
{
match BinOpCategory::from(op) {
BinOpCategory::Shortcircuit => {
true
}
BinOpCategory::Shift => {
ty::type_is_error(lhs) || ty
|
check_overloaded_binop
|
identifier_name
|
lib.rs
|
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy
//! functions around it so we can call into it without having to wrap the C API
//! each fing time. Great for integration tests or a websocket wrapper etc etc.
use ::std::{env, thread, slice, str};
use ::std::ffi::CString;
use ::std::time::Duration;
// -----------------------------------------------------------------------------
// Turtl C wrapper
// -----------------------------------------------------------------------------
// i made this
extern "C" {
pub fn turtlc_start(config: *const ::std::os::raw::c_char, threaded: u8) -> i32;
pub fn turtlc_send(message_bytes: *const u8, message_len: usize) -> i32;
pub fn turtlc_recv(non_block: u8, msgid: *const ::std::os::raw::c_char, len: *mut usize) -> *const u8;
pub fn turtlc_recv_event(non_block: u8, len: *mut usize) -> *const u8;
pub fn turtlc_free(msg: *const u8, len: usize) -> i32;
pub fn turtlc_lasterr() -> *mut ::std::os::raw::c_char;
pub fn turtlc_free_err(lasterr: *mut ::std::os::raw::c_char) -> i32;
}
// -----------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------
/// Init turtl
pub fn init(app_config: &str) -> thread::JoinHandle<()> {
if env::var("TURTL_CONFIG_FILE").is_err() {
env::set_var("TURTL_CONFIG_FILE", "../config.yaml");
}
let config_copy = String::from(app_config);
let handle = thread::spawn(move || {
// send in a the config options we need for our tests
let app_config = config_copy.as_str();
let app_config_c = CString::new(app_config).expect("cwrap::init() -- failed to convert config to CString");
let ret = unsafe {
turtlc_start(app_config_c.as_ptr(), 0)
};
if ret!= 0 {
panic!("Error running turtl: err {}", ret);
}
});
// since we're starting our own thread here, we need to wait for the stinkin
// core to load its config before we start asking it for stuff.
thread::sleep(Duration::from_millis(500));
handle
}
/// Send a message to the core
pub fn send(msg: &str) {
let msg_vec = Vec::from(String::from(msg).as_bytes());
let ret = unsafe {
turtlc_send(msg_vec.as_ptr(), msg_vec.len())
};
if ret!= 0 {
panic!("Error sending msg: err {}", ret);
}
}
/// Receive a message from the core, blocking (note that if you are not using
/// {"reqres_append_mid": true} in the app config, you should pass "" for the
/// `mid` arg here).
pub fn recv(mid: &str) -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(0, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv() -- error getting event: {}", x),
None => panic!("recv() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Like recv, but non-blocking
pub fn recv_nb(mid: &str) -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv_nb() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(1, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
/// Receive a core event (blocks)
pub fn recv_event() -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(0, raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv_event() -- error getting event: {}", x),
None => panic!("recv_event() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Receive a core event (non blocking)
pub fn recv_event_nb() -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(1, raw_len)
};
if msg_c.is_null()
|
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
pub fn lasterr() -> Option<String> {
let ptr = unsafe { turtlc_lasterr() };
if ptr.is_null() {
return None;
}
let cstring = unsafe { CString::from_raw(ptr) };
match cstring.into_string() {
Ok(x) => Some(x),
Err(e) => {
println!("lasterr() -- error grabbing last error: {}", e);
None
}
}
}
|
{
return None;
}
|
conditional_block
|
lib.rs
|
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy
//! functions around it so we can call into it without having to wrap the C API
//! each fing time. Great for integration tests or a websocket wrapper etc etc.
use ::std::{env, thread, slice, str};
use ::std::ffi::CString;
use ::std::time::Duration;
// -----------------------------------------------------------------------------
// Turtl C wrapper
// -----------------------------------------------------------------------------
// i made this
extern "C" {
pub fn turtlc_start(config: *const ::std::os::raw::c_char, threaded: u8) -> i32;
pub fn turtlc_send(message_bytes: *const u8, message_len: usize) -> i32;
pub fn turtlc_recv(non_block: u8, msgid: *const ::std::os::raw::c_char, len: *mut usize) -> *const u8;
pub fn turtlc_recv_event(non_block: u8, len: *mut usize) -> *const u8;
pub fn turtlc_free(msg: *const u8, len: usize) -> i32;
pub fn turtlc_lasterr() -> *mut ::std::os::raw::c_char;
pub fn turtlc_free_err(lasterr: *mut ::std::os::raw::c_char) -> i32;
}
// -----------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------
/// Init turtl
pub fn init(app_config: &str) -> thread::JoinHandle<()>
|
handle
}
/// Send a message to the core
pub fn send(msg: &str) {
let msg_vec = Vec::from(String::from(msg).as_bytes());
let ret = unsafe {
turtlc_send(msg_vec.as_ptr(), msg_vec.len())
};
if ret!= 0 {
panic!("Error sending msg: err {}", ret);
}
}
/// Receive a message from the core, blocking (note that if you are not using
/// {"reqres_append_mid": true} in the app config, you should pass "" for the
/// `mid` arg here).
pub fn recv(mid: &str) -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(0, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv() -- error getting event: {}", x),
None => panic!("recv() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Like recv, but non-blocking
pub fn recv_nb(mid: &str) -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv_nb() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(1, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
/// Receive a core event (blocks)
pub fn recv_event() -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(0, raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv_event() -- error getting event: {}", x),
None => panic!("recv_event() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Receive a core event (non blocking)
pub fn recv_event_nb() -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(1, raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
pub fn lasterr() -> Option<String> {
let ptr = unsafe { turtlc_lasterr() };
if ptr.is_null() {
return None;
}
let cstring = unsafe { CString::from_raw(ptr) };
match cstring.into_string() {
Ok(x) => Some(x),
Err(e) => {
println!("lasterr() -- error grabbing last error: {}", e);
None
}
}
}
|
{
if env::var("TURTL_CONFIG_FILE").is_err() {
env::set_var("TURTL_CONFIG_FILE", "../config.yaml");
}
let config_copy = String::from(app_config);
let handle = thread::spawn(move || {
// send in a the config options we need for our tests
let app_config = config_copy.as_str();
let app_config_c = CString::new(app_config).expect("cwrap::init() -- failed to convert config to CString");
let ret = unsafe {
turtlc_start(app_config_c.as_ptr(), 0)
};
if ret != 0 {
panic!("Error running turtl: err {}", ret);
}
});
// since we're starting our own thread here, we need to wait for the stinkin
// core to load its config before we start asking it for stuff.
thread::sleep(Duration::from_millis(500));
|
identifier_body
|
lib.rs
|
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy
//! functions around it so we can call into it without having to wrap the C API
//! each fing time. Great for integration tests or a websocket wrapper etc etc.
use ::std::{env, thread, slice, str};
use ::std::ffi::CString;
use ::std::time::Duration;
// -----------------------------------------------------------------------------
// Turtl C wrapper
// -----------------------------------------------------------------------------
// i made this
extern "C" {
pub fn turtlc_start(config: *const ::std::os::raw::c_char, threaded: u8) -> i32;
pub fn turtlc_send(message_bytes: *const u8, message_len: usize) -> i32;
pub fn turtlc_recv(non_block: u8, msgid: *const ::std::os::raw::c_char, len: *mut usize) -> *const u8;
pub fn turtlc_recv_event(non_block: u8, len: *mut usize) -> *const u8;
pub fn turtlc_free(msg: *const u8, len: usize) -> i32;
pub fn turtlc_lasterr() -> *mut ::std::os::raw::c_char;
pub fn turtlc_free_err(lasterr: *mut ::std::os::raw::c_char) -> i32;
}
// -----------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------
/// Init turtl
pub fn init(app_config: &str) -> thread::JoinHandle<()> {
if env::var("TURTL_CONFIG_FILE").is_err() {
env::set_var("TURTL_CONFIG_FILE", "../config.yaml");
}
let config_copy = String::from(app_config);
let handle = thread::spawn(move || {
// send in a the config options we need for our tests
let app_config = config_copy.as_str();
let app_config_c = CString::new(app_config).expect("cwrap::init() -- failed to convert config to CString");
let ret = unsafe {
turtlc_start(app_config_c.as_ptr(), 0)
};
if ret!= 0 {
panic!("Error running turtl: err {}", ret);
}
});
// since we're starting our own thread here, we need to wait for the stinkin
// core to load its config before we start asking it for stuff.
thread::sleep(Duration::from_millis(500));
handle
}
/// Send a message to the core
pub fn send(msg: &str) {
let msg_vec = Vec::from(String::from(msg).as_bytes());
let ret = unsafe {
turtlc_send(msg_vec.as_ptr(), msg_vec.len())
};
if ret!= 0 {
panic!("Error sending msg: err {}", ret);
}
}
/// Receive a message from the core, blocking (note that if you are not using
/// {"reqres_append_mid": true} in the app config, you should pass "" for the
/// `mid` arg here).
pub fn recv(mid: &str) -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(0, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv() -- error getting event: {}", x),
None => panic!("recv() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Like recv, but non-blocking
pub fn recv_nb(mid: &str) -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv_nb() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(1, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
/// Receive a core event (blocks)
pub fn recv_event() -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(0, raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv_event() -- error getting event: {}", x),
|
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Receive a core event (non blocking)
pub fn recv_event_nb() -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(1, raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
pub fn lasterr() -> Option<String> {
let ptr = unsafe { turtlc_lasterr() };
if ptr.is_null() {
return None;
}
let cstring = unsafe { CString::from_raw(ptr) };
match cstring.into_string() {
Ok(x) => Some(x),
Err(e) => {
println!("lasterr() -- error grabbing last error: {}", e);
None
}
}
}
|
None => panic!("recv_event() -- got empty msg and couldn't grab lasterr"),
|
random_line_split
|
lib.rs
|
//! A simple crate the wraps the turtl core shared lib and adds some handy dandy
//! functions around it so we can call into it without having to wrap the C API
//! each fing time. Great for integration tests or a websocket wrapper etc etc.
use ::std::{env, thread, slice, str};
use ::std::ffi::CString;
use ::std::time::Duration;
// -----------------------------------------------------------------------------
// Turtl C wrapper
// -----------------------------------------------------------------------------
// i made this
extern "C" {
pub fn turtlc_start(config: *const ::std::os::raw::c_char, threaded: u8) -> i32;
pub fn turtlc_send(message_bytes: *const u8, message_len: usize) -> i32;
pub fn turtlc_recv(non_block: u8, msgid: *const ::std::os::raw::c_char, len: *mut usize) -> *const u8;
pub fn turtlc_recv_event(non_block: u8, len: *mut usize) -> *const u8;
pub fn turtlc_free(msg: *const u8, len: usize) -> i32;
pub fn turtlc_lasterr() -> *mut ::std::os::raw::c_char;
pub fn turtlc_free_err(lasterr: *mut ::std::os::raw::c_char) -> i32;
}
// -----------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------
/// Init turtl
pub fn init(app_config: &str) -> thread::JoinHandle<()> {
if env::var("TURTL_CONFIG_FILE").is_err() {
env::set_var("TURTL_CONFIG_FILE", "../config.yaml");
}
let config_copy = String::from(app_config);
let handle = thread::spawn(move || {
// send in a the config options we need for our tests
let app_config = config_copy.as_str();
let app_config_c = CString::new(app_config).expect("cwrap::init() -- failed to convert config to CString");
let ret = unsafe {
turtlc_start(app_config_c.as_ptr(), 0)
};
if ret!= 0 {
panic!("Error running turtl: err {}", ret);
}
});
// since we're starting our own thread here, we need to wait for the stinkin
// core to load its config before we start asking it for stuff.
thread::sleep(Duration::from_millis(500));
handle
}
/// Send a message to the core
pub fn
|
(msg: &str) {
let msg_vec = Vec::from(String::from(msg).as_bytes());
let ret = unsafe {
turtlc_send(msg_vec.as_ptr(), msg_vec.len())
};
if ret!= 0 {
panic!("Error sending msg: err {}", ret);
}
}
/// Receive a message from the core, blocking (note that if you are not using
/// {"reqres_append_mid": true} in the app config, you should pass "" for the
/// `mid` arg here).
pub fn recv(mid: &str) -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(0, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv() -- error getting event: {}", x),
None => panic!("recv() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Like recv, but non-blocking
pub fn recv_nb(mid: &str) -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let mid_c = CString::new(mid).expect("cwrap::recv_nb() -- failed to convert mid to CString");
let msg_c = unsafe {
turtlc_recv(1, mid_c.as_ptr(), raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
/// Receive a core event (blocks)
pub fn recv_event() -> String {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(0, raw_len)
};
if msg_c.is_null() && len > 0 {
match lasterr() {
Some(x) => panic!("recv_event() -- error getting event: {}", x),
None => panic!("recv_event() -- got empty msg and couldn't grab lasterr"),
}
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
ret
}
/// Receive a core event (non blocking)
pub fn recv_event_nb() -> Option<String> {
let mut len: usize = 0;
let raw_len = &mut len as *mut usize;
let msg_c = unsafe {
turtlc_recv_event(1, raw_len)
};
if msg_c.is_null() {
return None;
}
let slice = unsafe { slice::from_raw_parts(msg_c, len) };
let res_str = str::from_utf8(slice).expect("cwrap::recv_event_nb() -- failed to parse utf8 str");
let ret = String::from(res_str);
unsafe {
turtlc_free(msg_c, len);
}
Some(ret)
}
pub fn lasterr() -> Option<String> {
let ptr = unsafe { turtlc_lasterr() };
if ptr.is_null() {
return None;
}
let cstring = unsafe { CString::from_raw(ptr) };
match cstring.into_string() {
Ok(x) => Some(x),
Err(e) => {
println!("lasterr() -- error grabbing last error: {}", e);
None
}
}
}
|
send
|
identifier_name
|
day1.rs
|
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
enum Cardinal {
West,
North,
East,
South,
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
enum Turn {
Left,
Right,
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
struct Coord(i32, i32);
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
struct Steps {
current_direction: Cardinal,
west: i32,
north: i32,
east: i32,
south: i32,
}
impl Steps {
fn add_steps_with_direction(&mut self, direction: &Cardinal, length: &i32) {
match direction.clone() {
Cardinal::West => {
self.west = self.west + length;
}
Cardinal::North => {
self.north = self.north + length;
}
|
}
}
}
}
fn main() {
let directions =
"L3, R2, L5, R1, L1, L2, L2, R1, R5, R1, L1, L2, R2, R4, L4, L3, L3, R5, L1, R3, L5, L2, \
R4, L5, R4, R2, L2, L1, R1, L3, L3, R2, R1, L4, L1, L1, R4, R5, R1, L2, L1, R188, R4, \
L3, R54, L4, R4, R74, R2, L4, R185, R1, R3, R5, L2, L3, R1, L1, L3, R3, R2, L3, L4, R1, \
L3, L5, L2, R2, L1, R2, R1, L4, R5, R4, L5, L5, L4, R5, R4, L5, L3, R4, R1, L5, L4, L3, \
R5, L5, L2, L4, R4, R4, R2, L1, L3, L2, R5, R4, L5, R1, R2, R5, L2, R4, R5, L2, L3, R3, \
L4, R3, L2, R1, R4, L5, R1, L5, L3, R4, L2, L2, L5, L5, R5, R2, L5, R1, L3, L2, L2, R3, \
L3, L4, R2, R3, L1, R2, L5, L3, R4, L4, R4, R3, L3, R1, L3, R5, L5, R1, R5, R3, L1";
let directions: Vec<&str> = directions.split(", ").collect();
let mut journey = Steps {
current_direction: Cardinal::North,
west: 0,
north: 0,
east: 0,
south: 0,
};
let mut all_steps = HashSet::new();
all_steps.insert(coord(&journey));
for raw_direction in &directions {
let (direction, length) = parse_turn_length(raw_direction, &journey.current_direction);
find_visit_twice(&direction, &length, journey.clone(), &mut all_steps);
next_journey(&direction, &length, &mut journey);
}
println!("{} blocks away at destination", blocks_away(&journey))
}
fn find_visit_twice(direction: &Cardinal,
length: &i32,
mut journey: Steps,
all_steps: &mut std::collections::HashSet<Coord>) {
for _ in 1..(length + 1) {
journey.add_steps_with_direction(direction, &1);
if all_steps.insert(coord(&journey)) == false {
println!("{} blocks away from one location already visited",
blocks_away(&journey));
}
}
}
fn coord(journey: &Steps) -> Coord {
Coord(journey.east - journey.west, journey.north - journey.south)
}
fn blocks_away(journey: &Steps) -> i32 {
(journey.west - journey.east).abs() + (journey.north - journey.south).abs()
}
fn next_journey(direction: &Cardinal, length: &i32, journey: &mut Steps) {
journey.current_direction = direction.clone();
journey.add_steps_with_direction(direction, length);
}
fn parse_turn_length(raw_direction: &str, current_direction: &Cardinal) -> (Cardinal, i32) {
let ref turn = raw_direction[0..1];
let ref length = raw_direction[1..];
let turn = parse_turn(turn);
let direction = next_direction(current_direction, turn);
let length = match length.parse::<i32>() {
Ok(i) => i,
Err(_) => panic!("Unable to parse number of steps"),
};
(direction, length)
}
fn next_direction(direction: &Cardinal, turn: Turn) -> Cardinal {
match (direction.clone(), turn) {
(Cardinal::East, Turn::Left) => Cardinal::North,
(Cardinal::East, Turn::Right) => Cardinal::South,
(Cardinal::North, Turn::Left) => Cardinal::West,
(Cardinal::North, Turn::Right) => Cardinal::East,
(Cardinal::South, Turn::Left) => Cardinal::East,
(Cardinal::South, Turn::Right) => Cardinal::West,
(Cardinal::West, Turn::Left) => Cardinal::South,
(Cardinal::West, Turn::Right) => Cardinal::North,
}
}
fn parse_turn(c: &str) -> Turn {
match c {
"L" => Turn::Left,
"R" => Turn::Right,
_ => panic!("Cannot convert the Turn"),
}
}
|
Cardinal::East => {
self.east = self.east + length;
}
Cardinal::South => {
self.south = self.south + length;
|
random_line_split
|
day1.rs
|
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
enum Cardinal {
West,
North,
East,
South,
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
enum Turn {
Left,
Right,
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
struct Coord(i32, i32);
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
struct
|
{
current_direction: Cardinal,
west: i32,
north: i32,
east: i32,
south: i32,
}
impl Steps {
fn add_steps_with_direction(&mut self, direction: &Cardinal, length: &i32) {
match direction.clone() {
Cardinal::West => {
self.west = self.west + length;
}
Cardinal::North => {
self.north = self.north + length;
}
Cardinal::East => {
self.east = self.east + length;
}
Cardinal::South => {
self.south = self.south + length;
}
}
}
}
fn main() {
let directions =
"L3, R2, L5, R1, L1, L2, L2, R1, R5, R1, L1, L2, R2, R4, L4, L3, L3, R5, L1, R3, L5, L2, \
R4, L5, R4, R2, L2, L1, R1, L3, L3, R2, R1, L4, L1, L1, R4, R5, R1, L2, L1, R188, R4, \
L3, R54, L4, R4, R74, R2, L4, R185, R1, R3, R5, L2, L3, R1, L1, L3, R3, R2, L3, L4, R1, \
L3, L5, L2, R2, L1, R2, R1, L4, R5, R4, L5, L5, L4, R5, R4, L5, L3, R4, R1, L5, L4, L3, \
R5, L5, L2, L4, R4, R4, R2, L1, L3, L2, R5, R4, L5, R1, R2, R5, L2, R4, R5, L2, L3, R3, \
L4, R3, L2, R1, R4, L5, R1, L5, L3, R4, L2, L2, L5, L5, R5, R2, L5, R1, L3, L2, L2, R3, \
L3, L4, R2, R3, L1, R2, L5, L3, R4, L4, R4, R3, L3, R1, L3, R5, L5, R1, R5, R3, L1";
let directions: Vec<&str> = directions.split(", ").collect();
let mut journey = Steps {
current_direction: Cardinal::North,
west: 0,
north: 0,
east: 0,
south: 0,
};
let mut all_steps = HashSet::new();
all_steps.insert(coord(&journey));
for raw_direction in &directions {
let (direction, length) = parse_turn_length(raw_direction, &journey.current_direction);
find_visit_twice(&direction, &length, journey.clone(), &mut all_steps);
next_journey(&direction, &length, &mut journey);
}
println!("{} blocks away at destination", blocks_away(&journey))
}
fn find_visit_twice(direction: &Cardinal,
length: &i32,
mut journey: Steps,
all_steps: &mut std::collections::HashSet<Coord>) {
for _ in 1..(length + 1) {
journey.add_steps_with_direction(direction, &1);
if all_steps.insert(coord(&journey)) == false {
println!("{} blocks away from one location already visited",
blocks_away(&journey));
}
}
}
fn coord(journey: &Steps) -> Coord {
Coord(journey.east - journey.west, journey.north - journey.south)
}
fn blocks_away(journey: &Steps) -> i32 {
(journey.west - journey.east).abs() + (journey.north - journey.south).abs()
}
fn next_journey(direction: &Cardinal, length: &i32, journey: &mut Steps) {
journey.current_direction = direction.clone();
journey.add_steps_with_direction(direction, length);
}
fn parse_turn_length(raw_direction: &str, current_direction: &Cardinal) -> (Cardinal, i32) {
let ref turn = raw_direction[0..1];
let ref length = raw_direction[1..];
let turn = parse_turn(turn);
let direction = next_direction(current_direction, turn);
let length = match length.parse::<i32>() {
Ok(i) => i,
Err(_) => panic!("Unable to parse number of steps"),
};
(direction, length)
}
fn next_direction(direction: &Cardinal, turn: Turn) -> Cardinal {
match (direction.clone(), turn) {
(Cardinal::East, Turn::Left) => Cardinal::North,
(Cardinal::East, Turn::Right) => Cardinal::South,
(Cardinal::North, Turn::Left) => Cardinal::West,
(Cardinal::North, Turn::Right) => Cardinal::East,
(Cardinal::South, Turn::Left) => Cardinal::East,
(Cardinal::South, Turn::Right) => Cardinal::West,
(Cardinal::West, Turn::Left) => Cardinal::South,
(Cardinal::West, Turn::Right) => Cardinal::North,
}
}
fn parse_turn(c: &str) -> Turn {
match c {
"L" => Turn::Left,
"R" => Turn::Right,
_ => panic!("Cannot convert the Turn"),
}
}
|
Steps
|
identifier_name
|
day1.rs
|
use std::collections::HashSet;
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
enum Cardinal {
West,
North,
East,
South,
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
enum Turn {
Left,
Right,
}
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
struct Coord(i32, i32);
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
struct Steps {
current_direction: Cardinal,
west: i32,
north: i32,
east: i32,
south: i32,
}
impl Steps {
fn add_steps_with_direction(&mut self, direction: &Cardinal, length: &i32) {
match direction.clone() {
Cardinal::West => {
self.west = self.west + length;
}
Cardinal::North => {
self.north = self.north + length;
}
Cardinal::East => {
self.east = self.east + length;
}
Cardinal::South => {
self.south = self.south + length;
}
}
}
}
fn main() {
let directions =
"L3, R2, L5, R1, L1, L2, L2, R1, R5, R1, L1, L2, R2, R4, L4, L3, L3, R5, L1, R3, L5, L2, \
R4, L5, R4, R2, L2, L1, R1, L3, L3, R2, R1, L4, L1, L1, R4, R5, R1, L2, L1, R188, R4, \
L3, R54, L4, R4, R74, R2, L4, R185, R1, R3, R5, L2, L3, R1, L1, L3, R3, R2, L3, L4, R1, \
L3, L5, L2, R2, L1, R2, R1, L4, R5, R4, L5, L5, L4, R5, R4, L5, L3, R4, R1, L5, L4, L3, \
R5, L5, L2, L4, R4, R4, R2, L1, L3, L2, R5, R4, L5, R1, R2, R5, L2, R4, R5, L2, L3, R3, \
L4, R3, L2, R1, R4, L5, R1, L5, L3, R4, L2, L2, L5, L5, R5, R2, L5, R1, L3, L2, L2, R3, \
L3, L4, R2, R3, L1, R2, L5, L3, R4, L4, R4, R3, L3, R1, L3, R5, L5, R1, R5, R3, L1";
let directions: Vec<&str> = directions.split(", ").collect();
let mut journey = Steps {
current_direction: Cardinal::North,
west: 0,
north: 0,
east: 0,
south: 0,
};
let mut all_steps = HashSet::new();
all_steps.insert(coord(&journey));
for raw_direction in &directions {
let (direction, length) = parse_turn_length(raw_direction, &journey.current_direction);
find_visit_twice(&direction, &length, journey.clone(), &mut all_steps);
next_journey(&direction, &length, &mut journey);
}
println!("{} blocks away at destination", blocks_away(&journey))
}
fn find_visit_twice(direction: &Cardinal,
length: &i32,
mut journey: Steps,
all_steps: &mut std::collections::HashSet<Coord>) {
for _ in 1..(length + 1) {
journey.add_steps_with_direction(direction, &1);
if all_steps.insert(coord(&journey)) == false {
println!("{} blocks away from one location already visited",
blocks_away(&journey));
}
}
}
fn coord(journey: &Steps) -> Coord {
Coord(journey.east - journey.west, journey.north - journey.south)
}
fn blocks_away(journey: &Steps) -> i32
|
fn next_journey(direction: &Cardinal, length: &i32, journey: &mut Steps) {
journey.current_direction = direction.clone();
journey.add_steps_with_direction(direction, length);
}
fn parse_turn_length(raw_direction: &str, current_direction: &Cardinal) -> (Cardinal, i32) {
let ref turn = raw_direction[0..1];
let ref length = raw_direction[1..];
let turn = parse_turn(turn);
let direction = next_direction(current_direction, turn);
let length = match length.parse::<i32>() {
Ok(i) => i,
Err(_) => panic!("Unable to parse number of steps"),
};
(direction, length)
}
fn next_direction(direction: &Cardinal, turn: Turn) -> Cardinal {
match (direction.clone(), turn) {
(Cardinal::East, Turn::Left) => Cardinal::North,
(Cardinal::East, Turn::Right) => Cardinal::South,
(Cardinal::North, Turn::Left) => Cardinal::West,
(Cardinal::North, Turn::Right) => Cardinal::East,
(Cardinal::South, Turn::Left) => Cardinal::East,
(Cardinal::South, Turn::Right) => Cardinal::West,
(Cardinal::West, Turn::Left) => Cardinal::South,
(Cardinal::West, Turn::Right) => Cardinal::North,
}
}
fn parse_turn(c: &str) -> Turn {
match c {
"L" => Turn::Left,
"R" => Turn::Right,
_ => panic!("Cannot convert the Turn"),
}
}
|
{
(journey.west - journey.east).abs() + (journey.north - journey.south).abs()
}
|
identifier_body
|
multiwindow.rs
|
#![feature(phase)]
#[cfg(target_os = "android")]
#[phase(plugin, link)]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn
|
() {
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::spawn(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::spawn(move || {
run(window2, (0.0, 0.0, 1.0, 1.0));
});
let t3 = Thread::spawn(move || {
run(window3, (1.0, 0.0, 0.0, 1.0));
});
t1.join();
t2.join();
t3.join();
}
#[cfg(feature = "window")]
fn run(window: glutin::Window, color: (f32, f32, f32, f32)) {
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().collect::<Vec<glutin::Event>>();
}
}
|
main
|
identifier_name
|
multiwindow.rs
|
#![feature(phase)]
#[cfg(target_os = "android")]
|
#[phase(plugin, link)]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main() {
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::spawn(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::spawn(move || {
run(window2, (0.0, 0.0, 1.0, 1.0));
});
let t3 = Thread::spawn(move || {
run(window3, (1.0, 0.0, 0.0, 1.0));
});
t1.join();
t2.join();
t3.join();
}
#[cfg(feature = "window")]
fn run(window: glutin::Window, color: (f32, f32, f32, f32)) {
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().collect::<Vec<glutin::Event>>();
}
}
|
random_line_split
|
|
multiwindow.rs
|
#![feature(phase)]
#[cfg(target_os = "android")]
#[phase(plugin, link)]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main() {
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::spawn(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::spawn(move || {
run(window2, (0.0, 0.0, 1.0, 1.0));
});
let t3 = Thread::spawn(move || {
run(window3, (1.0, 0.0, 0.0, 1.0));
});
t1.join();
t2.join();
t3.join();
}
#[cfg(feature = "window")]
fn run(window: glutin::Window, color: (f32, f32, f32, f32))
|
{
unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().collect::<Vec<glutin::Event>>();
}
}
|
identifier_body
|
|
by-value-non-immediate-argument.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print s
// check:$1 = {a = 1, b = 2.5}
// debugger:continue
// debugger:finish
// debugger:print x
// check:$2 = {a = 3, b = 4.5}
// debugger:print y
// check:$3 = 5
// debugger:print z
// check:$4 = 6.5
// debugger:continue
// debugger:finish
// debugger:print a
|
// check:$5 = {7, 8, 9.5, 10.5}
// debugger:continue
// debugger:finish
// debugger:print a
// check:$6 = {11.5, 12.5, 13, 14}
// debugger:continue
// debugger:finish
// debugger:print x
// check:$7 = {{Case1, x = 0, y = 8970181431921507452}, {Case1, 0, 2088533116, 2088533116}}
// debugger:continue
#[deriving(Clone)]
struct Struct {
a: int,
b: float
}
#[deriving(Clone)]
struct StructStruct {
a: Struct,
b: Struct
}
fn fun(s: Struct) {
zzz();
}
fn fun_fun(StructStruct { a: x, b: Struct { a: y, b: z } }: StructStruct) {
zzz();
}
fn tup(a: (int, uint, float, float)) {
zzz();
}
struct Newtype(float, float, int, uint);
fn new_type(a: Newtype) {
zzz();
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Enum {
Case1 { x: i64, y: i64 },
Case2 (i64, i32, i32),
}
fn by_val_enum(x: Enum) {
zzz();
}
fn main() {
fun(Struct { a: 1, b: 2.5 });
fun_fun(StructStruct { a: Struct { a: 3, b: 4.5 }, b: Struct { a: 5, b: 6.5 } });
tup((7, 8, 9.5, 10.5));
new_type(Newtype(11.5, 12.5, 13, 14));
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
by_val_enum(Case1 { x: 0, y: 8970181431921507452 });
}
fn zzz() {()}
|
random_line_split
|
|
by-value-non-immediate-argument.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print s
// check:$1 = {a = 1, b = 2.5}
// debugger:continue
// debugger:finish
// debugger:print x
// check:$2 = {a = 3, b = 4.5}
// debugger:print y
// check:$3 = 5
// debugger:print z
// check:$4 = 6.5
// debugger:continue
// debugger:finish
// debugger:print a
// check:$5 = {7, 8, 9.5, 10.5}
// debugger:continue
// debugger:finish
// debugger:print a
// check:$6 = {11.5, 12.5, 13, 14}
// debugger:continue
// debugger:finish
// debugger:print x
// check:$7 = {{Case1, x = 0, y = 8970181431921507452}, {Case1, 0, 2088533116, 2088533116}}
// debugger:continue
#[deriving(Clone)]
struct Struct {
a: int,
b: float
}
#[deriving(Clone)]
struct
|
{
a: Struct,
b: Struct
}
fn fun(s: Struct) {
zzz();
}
fn fun_fun(StructStruct { a: x, b: Struct { a: y, b: z } }: StructStruct) {
zzz();
}
fn tup(a: (int, uint, float, float)) {
zzz();
}
struct Newtype(float, float, int, uint);
fn new_type(a: Newtype) {
zzz();
}
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Enum {
Case1 { x: i64, y: i64 },
Case2 (i64, i32, i32),
}
fn by_val_enum(x: Enum) {
zzz();
}
fn main() {
fun(Struct { a: 1, b: 2.5 });
fun_fun(StructStruct { a: Struct { a: 3, b: 4.5 }, b: Struct { a: 5, b: 6.5 } });
tup((7, 8, 9.5, 10.5));
new_type(Newtype(11.5, 12.5, 13, 14));
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
by_val_enum(Case1 { x: 0, y: 8970181431921507452 });
}
fn zzz() {()}
|
StructStruct
|
identifier_name
|
sink.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/. */
//! Small helpers to abstract over different containers.
#![deny(missing_docs)]
use smallvec::{Array, SmallVec};
/// A trait to abstract over a `push` method that may be implemented for
/// different kind of types.
///
/// Used to abstract over `Array`, `SmallVec` and `Vec`, and also to implement a
/// type which `push` method does only tweak a byte when we only need to check
/// for the presence of something.
pub trait Push<T> {
/// Push a value into self.
fn push(&mut self, value: T);
}
impl<T> Push<T> for Vec<T> {
fn push(&mut self, value: T)
|
}
impl<A: Array> Push<A::Item> for SmallVec<A> {
fn push(&mut self, value: A::Item) {
SmallVec::push(self, value);
}
}
|
{
Vec::push(self, value);
}
|
identifier_body
|
sink.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/. */
//! Small helpers to abstract over different containers.
#![deny(missing_docs)]
use smallvec::{Array, SmallVec};
/// A trait to abstract over a `push` method that may be implemented for
/// different kind of types.
///
/// Used to abstract over `Array`, `SmallVec` and `Vec`, and also to implement a
/// type which `push` method does only tweak a byte when we only need to check
/// for the presence of something.
pub trait Push<T> {
/// Push a value into self.
fn push(&mut self, value: T);
}
impl<T> Push<T> for Vec<T> {
fn push(&mut self, value: T) {
Vec::push(self, value);
}
}
|
SmallVec::push(self, value);
}
}
|
impl<A: Array> Push<A::Item> for SmallVec<A> {
fn push(&mut self, value: A::Item) {
|
random_line_split
|
sink.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/. */
//! Small helpers to abstract over different containers.
#![deny(missing_docs)]
use smallvec::{Array, SmallVec};
/// A trait to abstract over a `push` method that may be implemented for
/// different kind of types.
///
/// Used to abstract over `Array`, `SmallVec` and `Vec`, and also to implement a
/// type which `push` method does only tweak a byte when we only need to check
/// for the presence of something.
pub trait Push<T> {
/// Push a value into self.
fn push(&mut self, value: T);
}
impl<T> Push<T> for Vec<T> {
fn
|
(&mut self, value: T) {
Vec::push(self, value);
}
}
impl<A: Array> Push<A::Item> for SmallVec<A> {
fn push(&mut self, value: A::Item) {
SmallVec::push(self, value);
}
}
|
push
|
identifier_name
|
hello.rs
|
#[no_mangle]
pub extern fn hello() {
// The statements here will be executed when the compiled binary is called
// Print text to the console
println!("Hello World!");
}
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// contributed by TeXitoi
use std::cmp::min;
use std::io::{BufferedWriter, File};
use std::io;
use std::num::Float;
use std::os;
const LINE_LENGTH: usize = 60;
const IM: u32 = 139968;
struct MyRandom {
last: u32
}
impl MyRandom {
fn new() -> MyRandom { MyRandom { last: 42 } }
fn normalize(p: f32) -> u32 {(p * IM as f32).floor() as u32}
fn gen(&mut self) -> u32 {
self.last = (self.last * 3877 + 29573) % IM;
self.last
}
}
struct AAGen<'a> {
rng: &'a mut MyRandom,
data: Vec<(u32, u8)>
}
impl<'a> AAGen<'a> {
fn new<'b>(rng: &'b mut MyRandom, aa: &[(char, f32)]) -> AAGen<'b> {
let mut cum = 0.;
let data = aa.iter()
.map(|&(ch, p)| { cum += p; (MyRandom::normalize(cum), ch as u8) })
.collect();
AAGen { rng: rng, data: data }
}
}
impl<'a> Iterator for AAGen<'a> {
|
self.data.iter()
.skip_while(|pc| pc.0 < r)
.map(|&(_, c)| c)
.next()
}
}
fn make_fasta<W: Writer, I: Iterator<Item=u8>>(
wr: &mut W, header: &str, mut it: I, mut n: usize)
-> std::io::IoResult<()>
{
//try!(wr.write(header.as_bytes()));
let mut line = [0u8; LINE_LENGTH + 1];
while n > 0 {
let nb = min(LINE_LENGTH, n);
for i in (0..nb) {
line[i] = it.next().unwrap();
}
n -= nb;
line[nb] = '\n' as u8;
//try!(wr.write(&line[..(nb+1)]));
}
Ok(())
}
fn run<W: Writer>(writer: &mut W) -> std::io::IoResult<()> {
let n = 25000000;
let rng = &mut MyRandom::new();
let alu =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG\
GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA\
CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT\
ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA\
GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG\
AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC\
AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
let iub = &[('a', 0.27), ('c', 0.12), ('g', 0.12),
('t', 0.27), ('B', 0.02), ('D', 0.02),
('H', 0.02), ('K', 0.02), ('M', 0.02),
('N', 0.02), ('R', 0.02), ('S', 0.02),
('V', 0.02), ('W', 0.02), ('Y', 0.02)];
let homosapiens = &[('a', 0.3029549426680),
('c', 0.1979883004921),
('g', 0.1975473066391),
('t', 0.3015094502008)];
try!(make_fasta(writer, ">ONE Homo sapiens alu\n",
alu.as_bytes().iter().cycle().map(|c| *c), n * 2));
try!(make_fasta(writer, ">TWO IUB ambiguity codes\n",
AAGen::new(rng, iub), n * 3));
try!(make_fasta(writer, ">THREE Homo sapiens frequency\n",
AAGen::new(rng, homosapiens), n * 5));
writer.flush()
}
#[no_mangle]
pub extern fn benchmark() {
run(&mut io::stdout()).unwrap()
}
|
type Item = u8;
fn next(&mut self) -> Option<u8> {
let r = self.rng.gen();
|
random_line_split
|
hello.rs
|
#[no_mangle]
pub extern fn hello() {
// The statements here will be executed when the compiled binary is called
// Print text to the console
println!("Hello World!");
}
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// contributed by TeXitoi
use std::cmp::min;
use std::io::{BufferedWriter, File};
use std::io;
use std::num::Float;
use std::os;
const LINE_LENGTH: usize = 60;
const IM: u32 = 139968;
struct MyRandom {
last: u32
}
impl MyRandom {
fn new() -> MyRandom { MyRandom { last: 42 } }
fn normalize(p: f32) -> u32 {(p * IM as f32).floor() as u32}
fn gen(&mut self) -> u32 {
self.last = (self.last * 3877 + 29573) % IM;
self.last
}
}
struct AAGen<'a> {
rng: &'a mut MyRandom,
data: Vec<(u32, u8)>
}
impl<'a> AAGen<'a> {
fn new<'b>(rng: &'b mut MyRandom, aa: &[(char, f32)]) -> AAGen<'b> {
let mut cum = 0.;
let data = aa.iter()
.map(|&(ch, p)| { cum += p; (MyRandom::normalize(cum), ch as u8) })
.collect();
AAGen { rng: rng, data: data }
}
}
impl<'a> Iterator for AAGen<'a> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
let r = self.rng.gen();
self.data.iter()
.skip_while(|pc| pc.0 < r)
.map(|&(_, c)| c)
.next()
}
}
fn
|
<W: Writer, I: Iterator<Item=u8>>(
wr: &mut W, header: &str, mut it: I, mut n: usize)
-> std::io::IoResult<()>
{
//try!(wr.write(header.as_bytes()));
let mut line = [0u8; LINE_LENGTH + 1];
while n > 0 {
let nb = min(LINE_LENGTH, n);
for i in (0..nb) {
line[i] = it.next().unwrap();
}
n -= nb;
line[nb] = '\n' as u8;
//try!(wr.write(&line[..(nb+1)]));
}
Ok(())
}
fn run<W: Writer>(writer: &mut W) -> std::io::IoResult<()> {
let n = 25000000;
let rng = &mut MyRandom::new();
let alu =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG\
GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA\
CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT\
ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA\
GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG\
AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC\
AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
let iub = &[('a', 0.27), ('c', 0.12), ('g', 0.12),
('t', 0.27), ('B', 0.02), ('D', 0.02),
('H', 0.02), ('K', 0.02), ('M', 0.02),
('N', 0.02), ('R', 0.02), ('S', 0.02),
('V', 0.02), ('W', 0.02), ('Y', 0.02)];
let homosapiens = &[('a', 0.3029549426680),
('c', 0.1979883004921),
('g', 0.1975473066391),
('t', 0.3015094502008)];
try!(make_fasta(writer, ">ONE Homo sapiens alu\n",
alu.as_bytes().iter().cycle().map(|c| *c), n * 2));
try!(make_fasta(writer, ">TWO IUB ambiguity codes\n",
AAGen::new(rng, iub), n * 3));
try!(make_fasta(writer, ">THREE Homo sapiens frequency\n",
AAGen::new(rng, homosapiens), n * 5));
writer.flush()
}
#[no_mangle]
pub extern fn benchmark() {
run(&mut io::stdout()).unwrap()
}
|
make_fasta
|
identifier_name
|
hello.rs
|
#[no_mangle]
pub extern fn hello() {
// The statements here will be executed when the compiled binary is called
// Print text to the console
println!("Hello World!");
}
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// contributed by TeXitoi
use std::cmp::min;
use std::io::{BufferedWriter, File};
use std::io;
use std::num::Float;
use std::os;
const LINE_LENGTH: usize = 60;
const IM: u32 = 139968;
struct MyRandom {
last: u32
}
impl MyRandom {
fn new() -> MyRandom { MyRandom { last: 42 } }
fn normalize(p: f32) -> u32 {(p * IM as f32).floor() as u32}
fn gen(&mut self) -> u32 {
self.last = (self.last * 3877 + 29573) % IM;
self.last
}
}
struct AAGen<'a> {
rng: &'a mut MyRandom,
data: Vec<(u32, u8)>
}
impl<'a> AAGen<'a> {
fn new<'b>(rng: &'b mut MyRandom, aa: &[(char, f32)]) -> AAGen<'b> {
let mut cum = 0.;
let data = aa.iter()
.map(|&(ch, p)| { cum += p; (MyRandom::normalize(cum), ch as u8) })
.collect();
AAGen { rng: rng, data: data }
}
}
impl<'a> Iterator for AAGen<'a> {
type Item = u8;
fn next(&mut self) -> Option<u8> {
let r = self.rng.gen();
self.data.iter()
.skip_while(|pc| pc.0 < r)
.map(|&(_, c)| c)
.next()
}
}
fn make_fasta<W: Writer, I: Iterator<Item=u8>>(
wr: &mut W, header: &str, mut it: I, mut n: usize)
-> std::io::IoResult<()>
{
//try!(wr.write(header.as_bytes()));
let mut line = [0u8; LINE_LENGTH + 1];
while n > 0 {
let nb = min(LINE_LENGTH, n);
for i in (0..nb) {
line[i] = it.next().unwrap();
}
n -= nb;
line[nb] = '\n' as u8;
//try!(wr.write(&line[..(nb+1)]));
}
Ok(())
}
fn run<W: Writer>(writer: &mut W) -> std::io::IoResult<()> {
let n = 25000000;
let rng = &mut MyRandom::new();
let alu =
"GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG\
GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA\
CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT\
ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA\
GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG\
AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC\
AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
let iub = &[('a', 0.27), ('c', 0.12), ('g', 0.12),
('t', 0.27), ('B', 0.02), ('D', 0.02),
('H', 0.02), ('K', 0.02), ('M', 0.02),
('N', 0.02), ('R', 0.02), ('S', 0.02),
('V', 0.02), ('W', 0.02), ('Y', 0.02)];
let homosapiens = &[('a', 0.3029549426680),
('c', 0.1979883004921),
('g', 0.1975473066391),
('t', 0.3015094502008)];
try!(make_fasta(writer, ">ONE Homo sapiens alu\n",
alu.as_bytes().iter().cycle().map(|c| *c), n * 2));
try!(make_fasta(writer, ">TWO IUB ambiguity codes\n",
AAGen::new(rng, iub), n * 3));
try!(make_fasta(writer, ">THREE Homo sapiens frequency\n",
AAGen::new(rng, homosapiens), n * 5));
writer.flush()
}
#[no_mangle]
pub extern fn benchmark()
|
{
run(&mut io::stdout()).unwrap()
}
|
identifier_body
|
|
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/. */
#![deny(unsafe_code)]
extern crate base64;
extern crate brotli;
extern crate cookie as cookie_rs;
extern crate devtools_traits;
extern crate embedder_traits;
extern crate flate2;
|
extern crate immeta;
extern crate ipc_channel;
#[macro_use]
extern crate lazy_static;
#[macro_use] extern crate log;
extern crate malloc_size_of;
#[macro_use] extern crate malloc_size_of_derive;
#[macro_use] #[no_link] extern crate matches;
#[macro_use]
extern crate mime;
extern crate mime_guess;
extern crate msg;
extern crate net_traits;
extern crate openssl;
extern crate pixels;
#[macro_use]
extern crate profile_traits;
#[macro_use] extern crate serde;
extern crate serde_json;
extern crate servo_allocator;
extern crate servo_arc;
extern crate servo_channel;
extern crate servo_config;
extern crate servo_url;
extern crate time;
extern crate unicase;
extern crate url;
extern crate uuid;
extern crate webrender_api;
extern crate ws;
mod blob_loader;
pub mod connector;
pub mod cookie;
pub mod cookie_storage;
mod data_loader;
pub mod filemanager_thread;
mod hosts;
pub mod hsts;
pub mod http_cache;
pub mod http_loader;
pub mod image_cache;
pub mod mime_classifier;
pub mod resource_thread;
mod storage_thread;
pub mod subresource_integrity;
mod websocket_loader;
/// An implementation of the [Fetch specification](https://fetch.spec.whatwg.org/)
pub mod fetch {
pub mod cors_cache;
pub mod methods;
}
/// A module for re-exports of items used in unit tests.
pub mod test {
pub use http_loader::HttpState;
pub use hosts::{replace_host_table, parse_hostsfile};
}
|
extern crate hyper;
extern crate hyper_openssl;
extern crate hyper_serde;
|
random_line_split
|
future.rs
|
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use crate::callback::must_call;
use futures::channel::mpsc;
use futures::channel::oneshot as futures_oneshot;
use futures::future::{self, BoxFuture, Future, FutureExt, TryFutureExt};
use futures::stream::{Stream, StreamExt};
use futures::task::{self, ArcWake, Context, Poll};
use std::sync::{Arc, Mutex};
/// Generates a paired future and callback so that when callback is being called, its result
/// is automatically passed as a future result.
pub fn paired_future_callback<T>() -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>)
where
T: Send +'static,
{
let (tx, future) = futures_oneshot::channel::<T>();
let callback = Box::new(move |result| {
let r = tx.send(result);
if r.is_err() {
warn!("paired_future_callback: Failed to send result to the future rx, discarded.");
}
});
(callback, future)
}
pub fn paired_must_called_future_callback<T>(
arg_on_drop: impl FnOnce() -> T + Send +'static,
) -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>)
where
T: Send +'static,
{
let (tx, future) = futures_oneshot::channel::<T>();
let callback = must_call(
move |result| {
let r = tx.send(result);
if r.is_err() {
warn!("paired_future_callback: Failed to send result to the future rx, discarded.");
}
},
arg_on_drop,
);
(callback, future)
}
/// Create a stream proxy with buffer representing the remote stream. The returned task
/// will receive messages from the remote stream as much as possible.
pub fn create_stream_with_buffer<T, S>(
|
size: usize,
) -> (
impl Stream<Item = T> + Send +'static,
impl Future<Output = ()> + Send +'static,
)
where
S: Stream<Item = T> + Send +'static,
T: Send +'static,
{
let (tx, rx) = mpsc::channel::<T>(size);
let driver = s
.then(future::ok::<T, mpsc::SendError>)
.forward(tx)
.map_err(|e| warn!("stream with buffer send error"; "error" => %e))
.map(|_| ());
(rx, driver)
}
/// Polls the provided future immediately. If the future is not ready,
/// it will register the waker. When the event is ready, the waker will
/// be notified, then the internal future is immediately polled in the
/// thread calling `wake()`.
pub fn poll_future_notify<F: Future<Output = ()> + Send +'static>(f: F) {
let f: BoxFuture<'static, ()> = Box::pin(f);
let waker = Arc::new(BatchCommandsWaker(Mutex::new(Some(f))));
waker.wake();
}
// BatchCommandsWaker is used to make business pool notifiy completion queues directly.
struct BatchCommandsWaker(Mutex<Option<BoxFuture<'static, ()>>>);
impl ArcWake for BatchCommandsWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
let mut future_slot = arc_self.0.lock().unwrap();
if let Some(mut future) = future_slot.take() {
let waker = task::waker_ref(&arc_self);
let cx = &mut Context::from_waker(&*waker);
match future.as_mut().poll(cx) {
Poll::Pending => {
*future_slot = Some(future);
}
Poll::Ready(()) => {}
}
}
}
}
|
s: S,
|
random_line_split
|
future.rs
|
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use crate::callback::must_call;
use futures::channel::mpsc;
use futures::channel::oneshot as futures_oneshot;
use futures::future::{self, BoxFuture, Future, FutureExt, TryFutureExt};
use futures::stream::{Stream, StreamExt};
use futures::task::{self, ArcWake, Context, Poll};
use std::sync::{Arc, Mutex};
/// Generates a paired future and callback so that when callback is being called, its result
/// is automatically passed as a future result.
pub fn paired_future_callback<T>() -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>)
where
T: Send +'static,
{
let (tx, future) = futures_oneshot::channel::<T>();
let callback = Box::new(move |result| {
let r = tx.send(result);
if r.is_err()
|
});
(callback, future)
}
pub fn paired_must_called_future_callback<T>(
arg_on_drop: impl FnOnce() -> T + Send +'static,
) -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>)
where
T: Send +'static,
{
let (tx, future) = futures_oneshot::channel::<T>();
let callback = must_call(
move |result| {
let r = tx.send(result);
if r.is_err() {
warn!("paired_future_callback: Failed to send result to the future rx, discarded.");
}
},
arg_on_drop,
);
(callback, future)
}
/// Create a stream proxy with buffer representing the remote stream. The returned task
/// will receive messages from the remote stream as much as possible.
pub fn create_stream_with_buffer<T, S>(
s: S,
size: usize,
) -> (
impl Stream<Item = T> + Send +'static,
impl Future<Output = ()> + Send +'static,
)
where
S: Stream<Item = T> + Send +'static,
T: Send +'static,
{
let (tx, rx) = mpsc::channel::<T>(size);
let driver = s
.then(future::ok::<T, mpsc::SendError>)
.forward(tx)
.map_err(|e| warn!("stream with buffer send error"; "error" => %e))
.map(|_| ());
(rx, driver)
}
/// Polls the provided future immediately. If the future is not ready,
/// it will register the waker. When the event is ready, the waker will
/// be notified, then the internal future is immediately polled in the
/// thread calling `wake()`.
pub fn poll_future_notify<F: Future<Output = ()> + Send +'static>(f: F) {
let f: BoxFuture<'static, ()> = Box::pin(f);
let waker = Arc::new(BatchCommandsWaker(Mutex::new(Some(f))));
waker.wake();
}
// BatchCommandsWaker is used to make business pool notifiy completion queues directly.
struct BatchCommandsWaker(Mutex<Option<BoxFuture<'static, ()>>>);
impl ArcWake for BatchCommandsWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
let mut future_slot = arc_self.0.lock().unwrap();
if let Some(mut future) = future_slot.take() {
let waker = task::waker_ref(&arc_self);
let cx = &mut Context::from_waker(&*waker);
match future.as_mut().poll(cx) {
Poll::Pending => {
*future_slot = Some(future);
}
Poll::Ready(()) => {}
}
}
}
}
|
{
warn!("paired_future_callback: Failed to send result to the future rx, discarded.");
}
|
conditional_block
|
future.rs
|
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use crate::callback::must_call;
use futures::channel::mpsc;
use futures::channel::oneshot as futures_oneshot;
use futures::future::{self, BoxFuture, Future, FutureExt, TryFutureExt};
use futures::stream::{Stream, StreamExt};
use futures::task::{self, ArcWake, Context, Poll};
use std::sync::{Arc, Mutex};
/// Generates a paired future and callback so that when callback is being called, its result
/// is automatically passed as a future result.
pub fn paired_future_callback<T>() -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>)
where
T: Send +'static,
{
let (tx, future) = futures_oneshot::channel::<T>();
let callback = Box::new(move |result| {
let r = tx.send(result);
if r.is_err() {
warn!("paired_future_callback: Failed to send result to the future rx, discarded.");
}
});
(callback, future)
}
pub fn paired_must_called_future_callback<T>(
arg_on_drop: impl FnOnce() -> T + Send +'static,
) -> (Box<dyn FnOnce(T) + Send>, futures_oneshot::Receiver<T>)
where
T: Send +'static,
{
let (tx, future) = futures_oneshot::channel::<T>();
let callback = must_call(
move |result| {
let r = tx.send(result);
if r.is_err() {
warn!("paired_future_callback: Failed to send result to the future rx, discarded.");
}
},
arg_on_drop,
);
(callback, future)
}
/// Create a stream proxy with buffer representing the remote stream. The returned task
/// will receive messages from the remote stream as much as possible.
pub fn create_stream_with_buffer<T, S>(
s: S,
size: usize,
) -> (
impl Stream<Item = T> + Send +'static,
impl Future<Output = ()> + Send +'static,
)
where
S: Stream<Item = T> + Send +'static,
T: Send +'static,
{
let (tx, rx) = mpsc::channel::<T>(size);
let driver = s
.then(future::ok::<T, mpsc::SendError>)
.forward(tx)
.map_err(|e| warn!("stream with buffer send error"; "error" => %e))
.map(|_| ());
(rx, driver)
}
/// Polls the provided future immediately. If the future is not ready,
/// it will register the waker. When the event is ready, the waker will
/// be notified, then the internal future is immediately polled in the
/// thread calling `wake()`.
pub fn
|
<F: Future<Output = ()> + Send +'static>(f: F) {
let f: BoxFuture<'static, ()> = Box::pin(f);
let waker = Arc::new(BatchCommandsWaker(Mutex::new(Some(f))));
waker.wake();
}
// BatchCommandsWaker is used to make business pool notifiy completion queues directly.
struct BatchCommandsWaker(Mutex<Option<BoxFuture<'static, ()>>>);
impl ArcWake for BatchCommandsWaker {
fn wake_by_ref(arc_self: &Arc<Self>) {
let mut future_slot = arc_self.0.lock().unwrap();
if let Some(mut future) = future_slot.take() {
let waker = task::waker_ref(&arc_self);
let cx = &mut Context::from_waker(&*waker);
match future.as_mut().poll(cx) {
Poll::Pending => {
*future_slot = Some(future);
}
Poll::Ready(()) => {}
}
}
}
}
|
poll_future_notify
|
identifier_name
|
denominations.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*;
#[inline]
/// 1 Ether in Wei
pub fn ether() -> U256 { U256::exp10(18) }
#[inline]
/// 1 Finney in Wei
pub fn
|
() -> U256 { U256::exp10(15) }
#[inline]
/// 1 Szabo in Wei
pub fn szabo() -> U256 { U256::exp10(12) }
#[inline]
/// 1 Shannon in Wei
pub fn shannon() -> U256 { U256::exp10(9) }
#[inline]
/// 1 Wei in Wei
pub fn wei() -> U256 { U256::exp10(0) }
|
finney
|
identifier_name
|
denominations.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*;
#[inline]
/// 1 Ether in Wei
pub fn ether() -> U256 { U256::exp10(18) }
#[inline]
/// 1 Finney in Wei
pub fn finney() -> U256 { U256::exp10(15) }
#[inline]
/// 1 Szabo in Wei
pub fn szabo() -> U256 { U256::exp10(12) }
#[inline]
/// 1 Shannon in Wei
pub fn shannon() -> U256 { U256::exp10(9) }
#[inline]
|
/// 1 Wei in Wei
pub fn wei() -> U256 { U256::exp10(0) }
|
random_line_split
|
|
denominations.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::*;
#[inline]
/// 1 Ether in Wei
pub fn ether() -> U256 { U256::exp10(18) }
#[inline]
/// 1 Finney in Wei
pub fn finney() -> U256 { U256::exp10(15) }
#[inline]
/// 1 Szabo in Wei
pub fn szabo() -> U256 { U256::exp10(12) }
#[inline]
/// 1 Shannon in Wei
pub fn shannon() -> U256
|
#[inline]
/// 1 Wei in Wei
pub fn wei() -> U256 { U256::exp10(0) }
|
{ U256::exp10(9) }
|
identifier_body
|
breakctr.rs
|
use std::env;
use std::slice;
use std::io::prelude::*;
use common::{err, challenge, ascii, base64, util, charfreq};
use common::cipher::one_byte_xor as obx;
use common::cipher::aes;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 19,
title: "Break fixed-nonce CTR mode using substitions",
help: "param1: path to file containing base64 encoded plain strings",
execute_fn: interactive
};
// heuristically determined constants:
const trigrams_limit: usize = 50; // number of trigrams to use for guessing using duplicate occurrences
const trigrams_limit_last_characters: usize = 400; // number of trigrams to use for guessing last few characters
const trigrams_key_limit: usize = 20; // number of candidate keys to use for guessing after sorting by (weight * count)
const trigrams_min_dups: usize = 3; // minimum number of trigram duplicates needed in a column
const min_prefixes_for_last_chars: usize = 3; // minimum number of prefixes needed to guess the last few characters without weights
// break ctr cipher one column at a time
// input: a list of cipher strings encrypted usinf CTR with same nonce
// output: a corresponding list of decrypted plain texts and keystream
//
pub fn break_ctr(ciphers: &Vec<Vec<u8>>) -> Result<Vec<u8>, err::Error> {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
let mut keystream = Vec::<u8>::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let (tri_idx, tri_c) = detect_trigrams(&ciphers);
let mut tri_idx_it = tri_idx.iter(); // iterator over trigram column indexes
let mut tri_c_it = tri_c.iter(); // iterator over corresponding lists of cipher characters
let mut all_ciphers_done = false;
while!all_ciphers_done {
let mut col = Vec::<u8>::new(); // extract a column
for it in cipher_its.iter_mut() {
match it.next() {
Some(v) => col.push(*v),
None => {}
};
}
if col.len() > 0 {
let tidx = match tri_idx_it.next() { // trigram column index: 0, 1 or 2
Some(v) => *v, // 3: if no trigram
None => 3
};
let empty_vec = Vec::<u8>::new();
let tc = match tri_c_it.next() { // cipher character list for the column
Some(v) => v, // (those found as trigram duplicates)
None => &empty_vec
};
let cw: (Vec<u8>, Vec<u32>);
if tidx < 3 && tc.len() > trigrams_min_dups {
cw = try!(filter_candidates(tidx, &tc));
} else {
cw = try!(filter_candidates_for_last_chars(&ciphers, &keystream));
}
let weights: Vec<f32> = cw.1.iter().map(|v| *v as f32).collect();
let mut options = obx::GuessOptions::new();
if cw.0.len() > 0 {
try!(options.set_candidates(&cw.0, &weights));
}
keystream.push(try!(obx::guess_key(&col, Some(&options))).key);
} else {
all_ciphers_done = true;
}
}
Ok(keystream)
}
fn filter_candidates(col: usize, c: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let tri_col: Vec<u8> = trigrams_col_no_weights!(col, trigrams_limit, "");
let result: Vec<u8>;
let weights: Vec<u32> = Vec::<u32>::new(); // will not contain weights
//println!("dup count: {}", c.len());
if c.len() == 1 {
result = tri_col.iter().map(|tc| tc ^ c[0]).collect();
} else {
let mut r = Vec::<u8>::new();
let cipher_chars_freq = util::freq(&c);
let trigram_chars_freq = util::freq(&tri_col);
for ccf in cipher_chars_freq.iter() { // eliminate candidates
// e.g. if a cipher char's freq = 2, then only
// select trigram chars whose freq >= 2
let filtered_by_freq = trigram_chars_freq.iter().filter(|tcf| tcf.1 >= ccf.1 && tcf.0!= ('#' as u8));
let keys: Vec<u8> = filtered_by_freq.map(|fbf| fbf.0 ^ ccf.0).collect();
r.extend(&keys);
|
}
let mut r2: Vec<(u8, usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1).cmp(&(a.1))); // sort by descending count
// only take the first "n" candidate keys
result = (0.. trigrams_key_limit).zip(&r2).map(|(_, &t)| (t as (u8, usize)).0).collect();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// for the last few characters (columns for which the count of duplicate trigrams detected < 3),
// we use last 2 decrypted characters as a prefix to predict next character using the trigram list
//
fn filter_candidates_for_last_chars(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let mut prefixes = Vec::<(Vec<u8>, u8, usize)>::new(); // all prefixes of length 2
let mut ks_it = keystream.iter().rev();
let k2 = ks_it.next().unwrap();
let k1 = ks_it.next().unwrap();
let ks_len = keystream.len();
let vnl = ascii::valid_non_letters();
let replace_non_letter_by_hash = |p| match vnl.iter().any(|&c| c == p) { // so, d, becomes d#
true => '#' as u8, // this'll help lookup matching trigrams
false => p };
for cipher in ciphers { // for each of the ciphers, decrypt the last 2 bytes
if cipher.len() >= ks_len + 1 { // using the keystream generated so far
let mut prefix = Vec::<u8>::new(); // predict the next plain character using matching trigrams
// with the same 2-byte prefix
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 2] ^ k1));
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 1] ^ k2));
//println!("{}", rts!(&prefix));
prefixes.push((prefix, cipher[ks_len], cipher.len() - ks_len));
}
}
let mut r = Vec::<(u8, u32)>::new(); // hold the (key, weight) pairs before sorting
let not_enough_prefixes = prefixes.len() < min_prefixes_for_last_chars;
for p in prefixes {
let tcol: Vec<(u8, u32)> = try!(charfreq::trigrams_col(2, trigrams_limit_last_characters, rts!(&p.0).as_ref()));
let letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0!= '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
let non_letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0 == '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
r.extend(letter_keys); // add candidate keys for letters
r.extend(non_letter_keys); // add candidate keys for non-letters
}
let mut r2: Vec<((u8, u32), usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1 as u32 * (b.0).1).cmp(&(a.1 as u32 * (a.0).1))); // sort by descending (weight * count)
//for i in r2.iter() {
// println!("({}, {}), {}", (i.0).0, (i.0).1, i.1);
//}
// only take the first "n" candidate keys
let (result, mut weights): (Vec<u8>, Vec<u32>) = (0.. trigrams_key_limit).zip(r2).map(|(_, t)| ((t.0).0, (t.0).1)).unzip();
if! not_enough_prefixes {
weights.clear();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// detect trigrams (by detecting repeating 3-byte patterns starting at a column)
// return:
// 1. a vector of size = max cipher length
// with 0, 1 or 2 to indicate trigram character column in each position
// 3: no trigram detected in that position
// 2. a vector of size = max cipher length
// with trigram bytes (cipher) if detected in that position
// else: empty vector
//
pub fn detect_trigrams(ciphers: &Vec<Vec<u8>>) -> (Vec<usize>, Vec<Vec<u8>>) {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let mut result_i = Vec::<usize>::new(); // column number 0, 1 or 2 of the detected duplicate trigram
let mut result_c = Vec::<Vec<u8>>::new(); // cipher characters for each of the duplicate trigram detected in that column
let mut buf = Vec::<Vec<u8>>::new(); // a cycling 3-byte buffer for trigram duplicate detection
for _ in 0.. ciphers.len() {
buf.push(vec![0; 3]);
}
let mut idx = 0; // cipher byte index
let mut all_ciphers_done = false;
while! all_ciphers_done {
{
let mut buf_it = buf.iter_mut();
all_ciphers_done = true;
for it in cipher_its.iter_mut() {
let c = match it.next() {
Some(v) => { all_ciphers_done = false; v }, // if all cipher iters yield none, we are done
None => { let mut b = buf_it.next().unwrap(); b.clear(); continue; }
};
let t = buf_it.next().unwrap();
t[0] = t[1]; t[1] = t[2]; t[2] = *c; // cycle the buffer
}
}
if all_ciphers_done {
break;
}
//println!("-");
result_i.push(3);
result_c.push(vec![]);
if idx >= 2 {
let trigrams_left = buf.iter().filter(|t| t.len()!= 0).count() > 1;
if trigrams_left {
let dups = util::dup::<Vec<u8>>(&buf);
for dup in dups {
if dup.0.len()!= 0 {
//println!("dup: {}, {}", ascii::raw_to_str(&dup.0).unwrap(), dup.1);
result_i[idx - 2] = 0; result_c[idx - 2].push(dup.0[0]);
result_i[idx - 1] = 1; result_c[idx - 1].push(dup.0[1]);
result_i[idx] = 2; result_c[idx].push(dup.0[2]);
}
}
} else {
all_ciphers_done = true;
}
}
idx += 1;
}
(result_i, result_c)
}
pub fn xor_keystream(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Vec<String> {
let mut result = Vec::<String>::new();
for c in ciphers {
result.push(c.iter().zip(keystream.iter()).map(|(&c, &k)| chr!(c ^ k)).collect());
}
result
}
pub fn generate_ciphers_from_file(filepath: &str) -> Result<Vec<Vec<u8>>, err::Error> {
let text = try!(util::read_file_to_str(&filepath));
let cbox = try!(cb::CipherBox::new(&vec![], aes::ctr_128));
let mut ciphers = Vec::<Vec<u8>>::new();
for line in text.lines() {
ciphers.push(try!(cbox.encrypt(&b64tr!(&line))));
}
Ok(ciphers)
}
pub fn break_ctr_with_manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let keystream = try!(break_ctr(&ciphers));
let plains = try!(manual_guess_for_last_chars(&ciphers, &keystream, &guesses));
Ok(plains)
}
// this function will keep asking the user for his guesses for last characters
// it first calls auto decryption, then expects the user to supply guesses
// a guess is provided as: line no, suffix
// e.g. > 4, head
// use # for wildcard
// e.g. > 4, hat# or > 4, ##er, etc.
// enter nothing to exit the loop
//
// input parameter guesses is intended for automated testing
//
pub fn manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, auto_guess_keystream: &Vec<u8>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let mut plains = xor_keystream(&ciphers, &auto_guess_keystream);
let mut keystream = auto_guess_keystream.clone();
fn display(plains: &Vec<String>) { // display plain text lines with line numbers
let mut c = 0;
for p in plains {
println!("{:02} {}", c, p);
c += 1;
}
}
fn fix_keystream(line_no: usize, suffix: &str, ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<Vec<u8>, err::Error> {
let suffix_r = raw!(&suffix);
let cipher: &Vec<u8> = &ciphers[line_no];
let new_ks_bytes: Vec<u8> = cipher.iter().rev().zip(suffix_r.iter().rev()).map(|(c, s)| c ^ s).rev().collect();
let mut new_keystream = keystream.clone();
let ks_start = cipher.len() - suffix_r.len();
for i in 0.. new_ks_bytes.len() {
if suffix_r[i]!= '#' as u8 {
new_keystream[ks_start + i] = new_ks_bytes[i];
}
}
Ok(new_keystream)
};
if guesses.len() > 0 { // guesses provided, so, don't ask the user
for guess in guesses {
keystream = try!(fix_keystream(guess.0, guess.1, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
}
} else { // interact with user
display(&plains);
loop {
let user_input = try!(util::input("enter guess (line no, last chars) [blank to exit]: "));
if user_input.trim() == "" {
break;
}
let parts: Vec<&str> = user_input.splitn(2, ",").collect();
ctry!(parts.len()!= 2, "need two values: line number, suffix");
let line_no = etry!(parts[0].parse::<usize>(), format!("{} is not a valid number", parts[0]));
let suffix = parts[1].trim();
keystream = try!(fix_keystream(line_no, &suffix, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
display(&plains);
}
}
Ok(plains)
}
pub fn interactive() -> err::ExitCode {
let input_filepath = match env::args().nth(2) {
Some(v) => v,
None => { println!("please specify input plain data (base64 encoded) filepath"); return exit_err!(); }
};
let ciphers = rtry!(generate_ciphers_from_file(&input_filepath), exit_err!());
let plains = rtry!(break_ctr_with_manual_guess_for_last_chars(&ciphers, &vec![]), exit_err!());
for p in plains {
println!("{}", p);
}
exit_ok!()
}
|
random_line_split
|
|
breakctr.rs
|
use std::env;
use std::slice;
use std::io::prelude::*;
use common::{err, challenge, ascii, base64, util, charfreq};
use common::cipher::one_byte_xor as obx;
use common::cipher::aes;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 19,
title: "Break fixed-nonce CTR mode using substitions",
help: "param1: path to file containing base64 encoded plain strings",
execute_fn: interactive
};
// heuristically determined constants:
const trigrams_limit: usize = 50; // number of trigrams to use for guessing using duplicate occurrences
const trigrams_limit_last_characters: usize = 400; // number of trigrams to use for guessing last few characters
const trigrams_key_limit: usize = 20; // number of candidate keys to use for guessing after sorting by (weight * count)
const trigrams_min_dups: usize = 3; // minimum number of trigram duplicates needed in a column
const min_prefixes_for_last_chars: usize = 3; // minimum number of prefixes needed to guess the last few characters without weights
// break ctr cipher one column at a time
// input: a list of cipher strings encrypted usinf CTR with same nonce
// output: a corresponding list of decrypted plain texts and keystream
//
pub fn break_ctr(ciphers: &Vec<Vec<u8>>) -> Result<Vec<u8>, err::Error> {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
let mut keystream = Vec::<u8>::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let (tri_idx, tri_c) = detect_trigrams(&ciphers);
let mut tri_idx_it = tri_idx.iter(); // iterator over trigram column indexes
let mut tri_c_it = tri_c.iter(); // iterator over corresponding lists of cipher characters
let mut all_ciphers_done = false;
while!all_ciphers_done {
let mut col = Vec::<u8>::new(); // extract a column
for it in cipher_its.iter_mut() {
match it.next() {
Some(v) => col.push(*v),
None => {}
};
}
if col.len() > 0 {
let tidx = match tri_idx_it.next() { // trigram column index: 0, 1 or 2
Some(v) => *v, // 3: if no trigram
None => 3
};
let empty_vec = Vec::<u8>::new();
let tc = match tri_c_it.next() { // cipher character list for the column
Some(v) => v, // (those found as trigram duplicates)
None => &empty_vec
};
let cw: (Vec<u8>, Vec<u32>);
if tidx < 3 && tc.len() > trigrams_min_dups {
cw = try!(filter_candidates(tidx, &tc));
} else {
cw = try!(filter_candidates_for_last_chars(&ciphers, &keystream));
}
let weights: Vec<f32> = cw.1.iter().map(|v| *v as f32).collect();
let mut options = obx::GuessOptions::new();
if cw.0.len() > 0 {
try!(options.set_candidates(&cw.0, &weights));
}
keystream.push(try!(obx::guess_key(&col, Some(&options))).key);
} else {
all_ciphers_done = true;
}
}
Ok(keystream)
}
fn filter_candidates(col: usize, c: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let tri_col: Vec<u8> = trigrams_col_no_weights!(col, trigrams_limit, "");
let result: Vec<u8>;
let weights: Vec<u32> = Vec::<u32>::new(); // will not contain weights
//println!("dup count: {}", c.len());
if c.len() == 1 {
result = tri_col.iter().map(|tc| tc ^ c[0]).collect();
} else {
let mut r = Vec::<u8>::new();
let cipher_chars_freq = util::freq(&c);
let trigram_chars_freq = util::freq(&tri_col);
for ccf in cipher_chars_freq.iter() { // eliminate candidates
// e.g. if a cipher char's freq = 2, then only
// select trigram chars whose freq >= 2
let filtered_by_freq = trigram_chars_freq.iter().filter(|tcf| tcf.1 >= ccf.1 && tcf.0!= ('#' as u8));
let keys: Vec<u8> = filtered_by_freq.map(|fbf| fbf.0 ^ ccf.0).collect();
r.extend(&keys);
}
let mut r2: Vec<(u8, usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1).cmp(&(a.1))); // sort by descending count
// only take the first "n" candidate keys
result = (0.. trigrams_key_limit).zip(&r2).map(|(_, &t)| (t as (u8, usize)).0).collect();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// for the last few characters (columns for which the count of duplicate trigrams detected < 3),
// we use last 2 decrypted characters as a prefix to predict next character using the trigram list
//
fn filter_candidates_for_last_chars(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let mut prefixes = Vec::<(Vec<u8>, u8, usize)>::new(); // all prefixes of length 2
let mut ks_it = keystream.iter().rev();
let k2 = ks_it.next().unwrap();
let k1 = ks_it.next().unwrap();
let ks_len = keystream.len();
let vnl = ascii::valid_non_letters();
let replace_non_letter_by_hash = |p| match vnl.iter().any(|&c| c == p) { // so, d, becomes d#
true => '#' as u8, // this'll help lookup matching trigrams
false => p };
for cipher in ciphers { // for each of the ciphers, decrypt the last 2 bytes
if cipher.len() >= ks_len + 1 { // using the keystream generated so far
let mut prefix = Vec::<u8>::new(); // predict the next plain character using matching trigrams
// with the same 2-byte prefix
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 2] ^ k1));
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 1] ^ k2));
//println!("{}", rts!(&prefix));
prefixes.push((prefix, cipher[ks_len], cipher.len() - ks_len));
}
}
let mut r = Vec::<(u8, u32)>::new(); // hold the (key, weight) pairs before sorting
let not_enough_prefixes = prefixes.len() < min_prefixes_for_last_chars;
for p in prefixes {
let tcol: Vec<(u8, u32)> = try!(charfreq::trigrams_col(2, trigrams_limit_last_characters, rts!(&p.0).as_ref()));
let letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0!= '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
let non_letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0 == '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
r.extend(letter_keys); // add candidate keys for letters
r.extend(non_letter_keys); // add candidate keys for non-letters
}
let mut r2: Vec<((u8, u32), usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1 as u32 * (b.0).1).cmp(&(a.1 as u32 * (a.0).1))); // sort by descending (weight * count)
//for i in r2.iter() {
// println!("({}, {}), {}", (i.0).0, (i.0).1, i.1);
//}
// only take the first "n" candidate keys
let (result, mut weights): (Vec<u8>, Vec<u32>) = (0.. trigrams_key_limit).zip(r2).map(|(_, t)| ((t.0).0, (t.0).1)).unzip();
if! not_enough_prefixes {
weights.clear();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// detect trigrams (by detecting repeating 3-byte patterns starting at a column)
// return:
// 1. a vector of size = max cipher length
// with 0, 1 or 2 to indicate trigram character column in each position
// 3: no trigram detected in that position
// 2. a vector of size = max cipher length
// with trigram bytes (cipher) if detected in that position
// else: empty vector
//
pub fn detect_trigrams(ciphers: &Vec<Vec<u8>>) -> (Vec<usize>, Vec<Vec<u8>>) {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let mut result_i = Vec::<usize>::new(); // column number 0, 1 or 2 of the detected duplicate trigram
let mut result_c = Vec::<Vec<u8>>::new(); // cipher characters for each of the duplicate trigram detected in that column
let mut buf = Vec::<Vec<u8>>::new(); // a cycling 3-byte buffer for trigram duplicate detection
for _ in 0.. ciphers.len() {
buf.push(vec![0; 3]);
}
let mut idx = 0; // cipher byte index
let mut all_ciphers_done = false;
while! all_ciphers_done {
{
let mut buf_it = buf.iter_mut();
all_ciphers_done = true;
for it in cipher_its.iter_mut() {
let c = match it.next() {
Some(v) => { all_ciphers_done = false; v }, // if all cipher iters yield none, we are done
None => { let mut b = buf_it.next().unwrap(); b.clear(); continue; }
};
let t = buf_it.next().unwrap();
t[0] = t[1]; t[1] = t[2]; t[2] = *c; // cycle the buffer
}
}
if all_ciphers_done {
break;
}
//println!("-");
result_i.push(3);
result_c.push(vec![]);
if idx >= 2 {
let trigrams_left = buf.iter().filter(|t| t.len()!= 0).count() > 1;
if trigrams_left {
let dups = util::dup::<Vec<u8>>(&buf);
for dup in dups {
if dup.0.len()!= 0 {
//println!("dup: {}, {}", ascii::raw_to_str(&dup.0).unwrap(), dup.1);
result_i[idx - 2] = 0; result_c[idx - 2].push(dup.0[0]);
result_i[idx - 1] = 1; result_c[idx - 1].push(dup.0[1]);
result_i[idx] = 2; result_c[idx].push(dup.0[2]);
}
}
} else {
all_ciphers_done = true;
}
}
idx += 1;
}
(result_i, result_c)
}
pub fn xor_keystream(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Vec<String> {
let mut result = Vec::<String>::new();
for c in ciphers {
result.push(c.iter().zip(keystream.iter()).map(|(&c, &k)| chr!(c ^ k)).collect());
}
result
}
pub fn generate_ciphers_from_file(filepath: &str) -> Result<Vec<Vec<u8>>, err::Error> {
let text = try!(util::read_file_to_str(&filepath));
let cbox = try!(cb::CipherBox::new(&vec![], aes::ctr_128));
let mut ciphers = Vec::<Vec<u8>>::new();
for line in text.lines() {
ciphers.push(try!(cbox.encrypt(&b64tr!(&line))));
}
Ok(ciphers)
}
pub fn
|
(ciphers: &Vec<Vec<u8>>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let keystream = try!(break_ctr(&ciphers));
let plains = try!(manual_guess_for_last_chars(&ciphers, &keystream, &guesses));
Ok(plains)
}
// this function will keep asking the user for his guesses for last characters
// it first calls auto decryption, then expects the user to supply guesses
// a guess is provided as: line no, suffix
// e.g. > 4, head
// use # for wildcard
// e.g. > 4, hat# or > 4, ##er, etc.
// enter nothing to exit the loop
//
// input parameter guesses is intended for automated testing
//
pub fn manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, auto_guess_keystream: &Vec<u8>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let mut plains = xor_keystream(&ciphers, &auto_guess_keystream);
let mut keystream = auto_guess_keystream.clone();
fn display(plains: &Vec<String>) { // display plain text lines with line numbers
let mut c = 0;
for p in plains {
println!("{:02} {}", c, p);
c += 1;
}
}
fn fix_keystream(line_no: usize, suffix: &str, ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<Vec<u8>, err::Error> {
let suffix_r = raw!(&suffix);
let cipher: &Vec<u8> = &ciphers[line_no];
let new_ks_bytes: Vec<u8> = cipher.iter().rev().zip(suffix_r.iter().rev()).map(|(c, s)| c ^ s).rev().collect();
let mut new_keystream = keystream.clone();
let ks_start = cipher.len() - suffix_r.len();
for i in 0.. new_ks_bytes.len() {
if suffix_r[i]!= '#' as u8 {
new_keystream[ks_start + i] = new_ks_bytes[i];
}
}
Ok(new_keystream)
};
if guesses.len() > 0 { // guesses provided, so, don't ask the user
for guess in guesses {
keystream = try!(fix_keystream(guess.0, guess.1, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
}
} else { // interact with user
display(&plains);
loop {
let user_input = try!(util::input("enter guess (line no, last chars) [blank to exit]: "));
if user_input.trim() == "" {
break;
}
let parts: Vec<&str> = user_input.splitn(2, ",").collect();
ctry!(parts.len()!= 2, "need two values: line number, suffix");
let line_no = etry!(parts[0].parse::<usize>(), format!("{} is not a valid number", parts[0]));
let suffix = parts[1].trim();
keystream = try!(fix_keystream(line_no, &suffix, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
display(&plains);
}
}
Ok(plains)
}
pub fn interactive() -> err::ExitCode {
let input_filepath = match env::args().nth(2) {
Some(v) => v,
None => { println!("please specify input plain data (base64 encoded) filepath"); return exit_err!(); }
};
let ciphers = rtry!(generate_ciphers_from_file(&input_filepath), exit_err!());
let plains = rtry!(break_ctr_with_manual_guess_for_last_chars(&ciphers, &vec![]), exit_err!());
for p in plains {
println!("{}", p);
}
exit_ok!()
}
|
break_ctr_with_manual_guess_for_last_chars
|
identifier_name
|
breakctr.rs
|
use std::env;
use std::slice;
use std::io::prelude::*;
use common::{err, challenge, ascii, base64, util, charfreq};
use common::cipher::one_byte_xor as obx;
use common::cipher::aes;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 19,
title: "Break fixed-nonce CTR mode using substitions",
help: "param1: path to file containing base64 encoded plain strings",
execute_fn: interactive
};
// heuristically determined constants:
const trigrams_limit: usize = 50; // number of trigrams to use for guessing using duplicate occurrences
const trigrams_limit_last_characters: usize = 400; // number of trigrams to use for guessing last few characters
const trigrams_key_limit: usize = 20; // number of candidate keys to use for guessing after sorting by (weight * count)
const trigrams_min_dups: usize = 3; // minimum number of trigram duplicates needed in a column
const min_prefixes_for_last_chars: usize = 3; // minimum number of prefixes needed to guess the last few characters without weights
// break ctr cipher one column at a time
// input: a list of cipher strings encrypted usinf CTR with same nonce
// output: a corresponding list of decrypted plain texts and keystream
//
pub fn break_ctr(ciphers: &Vec<Vec<u8>>) -> Result<Vec<u8>, err::Error> {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
let mut keystream = Vec::<u8>::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let (tri_idx, tri_c) = detect_trigrams(&ciphers);
let mut tri_idx_it = tri_idx.iter(); // iterator over trigram column indexes
let mut tri_c_it = tri_c.iter(); // iterator over corresponding lists of cipher characters
let mut all_ciphers_done = false;
while!all_ciphers_done {
let mut col = Vec::<u8>::new(); // extract a column
for it in cipher_its.iter_mut() {
match it.next() {
Some(v) => col.push(*v),
None => {}
};
}
if col.len() > 0 {
let tidx = match tri_idx_it.next() { // trigram column index: 0, 1 or 2
Some(v) => *v, // 3: if no trigram
None => 3
};
let empty_vec = Vec::<u8>::new();
let tc = match tri_c_it.next() { // cipher character list for the column
Some(v) => v, // (those found as trigram duplicates)
None => &empty_vec
};
let cw: (Vec<u8>, Vec<u32>);
if tidx < 3 && tc.len() > trigrams_min_dups {
cw = try!(filter_candidates(tidx, &tc));
} else {
cw = try!(filter_candidates_for_last_chars(&ciphers, &keystream));
}
let weights: Vec<f32> = cw.1.iter().map(|v| *v as f32).collect();
let mut options = obx::GuessOptions::new();
if cw.0.len() > 0 {
try!(options.set_candidates(&cw.0, &weights));
}
keystream.push(try!(obx::guess_key(&col, Some(&options))).key);
} else {
all_ciphers_done = true;
}
}
Ok(keystream)
}
fn filter_candidates(col: usize, c: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let tri_col: Vec<u8> = trigrams_col_no_weights!(col, trigrams_limit, "");
let result: Vec<u8>;
let weights: Vec<u32> = Vec::<u32>::new(); // will not contain weights
//println!("dup count: {}", c.len());
if c.len() == 1 {
result = tri_col.iter().map(|tc| tc ^ c[0]).collect();
} else {
let mut r = Vec::<u8>::new();
let cipher_chars_freq = util::freq(&c);
let trigram_chars_freq = util::freq(&tri_col);
for ccf in cipher_chars_freq.iter() { // eliminate candidates
// e.g. if a cipher char's freq = 2, then only
// select trigram chars whose freq >= 2
let filtered_by_freq = trigram_chars_freq.iter().filter(|tcf| tcf.1 >= ccf.1 && tcf.0!= ('#' as u8));
let keys: Vec<u8> = filtered_by_freq.map(|fbf| fbf.0 ^ ccf.0).collect();
r.extend(&keys);
}
let mut r2: Vec<(u8, usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1).cmp(&(a.1))); // sort by descending count
// only take the first "n" candidate keys
result = (0.. trigrams_key_limit).zip(&r2).map(|(_, &t)| (t as (u8, usize)).0).collect();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// for the last few characters (columns for which the count of duplicate trigrams detected < 3),
// we use last 2 decrypted characters as a prefix to predict next character using the trigram list
//
fn filter_candidates_for_last_chars(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let mut prefixes = Vec::<(Vec<u8>, u8, usize)>::new(); // all prefixes of length 2
let mut ks_it = keystream.iter().rev();
let k2 = ks_it.next().unwrap();
let k1 = ks_it.next().unwrap();
let ks_len = keystream.len();
let vnl = ascii::valid_non_letters();
let replace_non_letter_by_hash = |p| match vnl.iter().any(|&c| c == p) { // so, d, becomes d#
true => '#' as u8, // this'll help lookup matching trigrams
false => p };
for cipher in ciphers { // for each of the ciphers, decrypt the last 2 bytes
if cipher.len() >= ks_len + 1 { // using the keystream generated so far
let mut prefix = Vec::<u8>::new(); // predict the next plain character using matching trigrams
// with the same 2-byte prefix
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 2] ^ k1));
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 1] ^ k2));
//println!("{}", rts!(&prefix));
prefixes.push((prefix, cipher[ks_len], cipher.len() - ks_len));
}
}
let mut r = Vec::<(u8, u32)>::new(); // hold the (key, weight) pairs before sorting
let not_enough_prefixes = prefixes.len() < min_prefixes_for_last_chars;
for p in prefixes {
let tcol: Vec<(u8, u32)> = try!(charfreq::trigrams_col(2, trigrams_limit_last_characters, rts!(&p.0).as_ref()));
let letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0!= '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
let non_letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0 == '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
r.extend(letter_keys); // add candidate keys for letters
r.extend(non_letter_keys); // add candidate keys for non-letters
}
let mut r2: Vec<((u8, u32), usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1 as u32 * (b.0).1).cmp(&(a.1 as u32 * (a.0).1))); // sort by descending (weight * count)
//for i in r2.iter() {
// println!("({}, {}), {}", (i.0).0, (i.0).1, i.1);
//}
// only take the first "n" candidate keys
let (result, mut weights): (Vec<u8>, Vec<u32>) = (0.. trigrams_key_limit).zip(r2).map(|(_, t)| ((t.0).0, (t.0).1)).unzip();
if! not_enough_prefixes {
weights.clear();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// detect trigrams (by detecting repeating 3-byte patterns starting at a column)
// return:
// 1. a vector of size = max cipher length
// with 0, 1 or 2 to indicate trigram character column in each position
// 3: no trigram detected in that position
// 2. a vector of size = max cipher length
// with trigram bytes (cipher) if detected in that position
// else: empty vector
//
pub fn detect_trigrams(ciphers: &Vec<Vec<u8>>) -> (Vec<usize>, Vec<Vec<u8>>) {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let mut result_i = Vec::<usize>::new(); // column number 0, 1 or 2 of the detected duplicate trigram
let mut result_c = Vec::<Vec<u8>>::new(); // cipher characters for each of the duplicate trigram detected in that column
let mut buf = Vec::<Vec<u8>>::new(); // a cycling 3-byte buffer for trigram duplicate detection
for _ in 0.. ciphers.len() {
buf.push(vec![0; 3]);
}
let mut idx = 0; // cipher byte index
let mut all_ciphers_done = false;
while! all_ciphers_done {
{
let mut buf_it = buf.iter_mut();
all_ciphers_done = true;
for it in cipher_its.iter_mut() {
let c = match it.next() {
Some(v) => { all_ciphers_done = false; v }, // if all cipher iters yield none, we are done
None => { let mut b = buf_it.next().unwrap(); b.clear(); continue; }
};
let t = buf_it.next().unwrap();
t[0] = t[1]; t[1] = t[2]; t[2] = *c; // cycle the buffer
}
}
if all_ciphers_done {
break;
}
//println!("-");
result_i.push(3);
result_c.push(vec![]);
if idx >= 2 {
let trigrams_left = buf.iter().filter(|t| t.len()!= 0).count() > 1;
if trigrams_left {
let dups = util::dup::<Vec<u8>>(&buf);
for dup in dups {
if dup.0.len()!= 0 {
//println!("dup: {}, {}", ascii::raw_to_str(&dup.0).unwrap(), dup.1);
result_i[idx - 2] = 0; result_c[idx - 2].push(dup.0[0]);
result_i[idx - 1] = 1; result_c[idx - 1].push(dup.0[1]);
result_i[idx] = 2; result_c[idx].push(dup.0[2]);
}
}
} else {
all_ciphers_done = true;
}
}
idx += 1;
}
(result_i, result_c)
}
pub fn xor_keystream(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Vec<String> {
let mut result = Vec::<String>::new();
for c in ciphers {
result.push(c.iter().zip(keystream.iter()).map(|(&c, &k)| chr!(c ^ k)).collect());
}
result
}
pub fn generate_ciphers_from_file(filepath: &str) -> Result<Vec<Vec<u8>>, err::Error> {
let text = try!(util::read_file_to_str(&filepath));
let cbox = try!(cb::CipherBox::new(&vec![], aes::ctr_128));
let mut ciphers = Vec::<Vec<u8>>::new();
for line in text.lines() {
ciphers.push(try!(cbox.encrypt(&b64tr!(&line))));
}
Ok(ciphers)
}
pub fn break_ctr_with_manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let keystream = try!(break_ctr(&ciphers));
let plains = try!(manual_guess_for_last_chars(&ciphers, &keystream, &guesses));
Ok(plains)
}
// this function will keep asking the user for his guesses for last characters
// it first calls auto decryption, then expects the user to supply guesses
// a guess is provided as: line no, suffix
// e.g. > 4, head
// use # for wildcard
// e.g. > 4, hat# or > 4, ##er, etc.
// enter nothing to exit the loop
//
// input parameter guesses is intended for automated testing
//
pub fn manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, auto_guess_keystream: &Vec<u8>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error>
|
for i in 0.. new_ks_bytes.len() {
if suffix_r[i]!= '#' as u8 {
new_keystream[ks_start + i] = new_ks_bytes[i];
}
}
Ok(new_keystream)
};
if guesses.len() > 0 { // guesses provided, so, don't ask the user
for guess in guesses {
keystream = try!(fix_keystream(guess.0, guess.1, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
}
} else { // interact with user
display(&plains);
loop {
let user_input = try!(util::input("enter guess (line no, last chars) [blank to exit]: "));
if user_input.trim() == "" {
break;
}
let parts: Vec<&str> = user_input.splitn(2, ",").collect();
ctry!(parts.len()!= 2, "need two values: line number, suffix");
let line_no = etry!(parts[0].parse::<usize>(), format!("{} is not a valid number", parts[0]));
let suffix = parts[1].trim();
keystream = try!(fix_keystream(line_no, &suffix, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
display(&plains);
}
}
Ok(plains)
}
pub fn interactive() -> err::ExitCode {
let input_filepath = match env::args().nth(2) {
Some(v) => v,
None => { println!("please specify input plain data (base64 encoded) filepath"); return exit_err!(); }
};
let ciphers = rtry!(generate_ciphers_from_file(&input_filepath), exit_err!());
let plains = rtry!(break_ctr_with_manual_guess_for_last_chars(&ciphers, &vec![]), exit_err!());
for p in plains {
println!("{}", p);
}
exit_ok!()
}
|
{
let mut plains = xor_keystream(&ciphers, &auto_guess_keystream);
let mut keystream = auto_guess_keystream.clone();
fn display(plains: &Vec<String>) { // display plain text lines with line numbers
let mut c = 0;
for p in plains {
println!("{:02} {}", c, p);
c += 1;
}
}
fn fix_keystream(line_no: usize, suffix: &str, ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<Vec<u8>, err::Error> {
let suffix_r = raw!(&suffix);
let cipher: &Vec<u8> = &ciphers[line_no];
let new_ks_bytes: Vec<u8> = cipher.iter().rev().zip(suffix_r.iter().rev()).map(|(c, s)| c ^ s).rev().collect();
let mut new_keystream = keystream.clone();
let ks_start = cipher.len() - suffix_r.len();
|
identifier_body
|
breakctr.rs
|
use std::env;
use std::slice;
use std::io::prelude::*;
use common::{err, challenge, ascii, base64, util, charfreq};
use common::cipher::one_byte_xor as obx;
use common::cipher::aes;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 19,
title: "Break fixed-nonce CTR mode using substitions",
help: "param1: path to file containing base64 encoded plain strings",
execute_fn: interactive
};
// heuristically determined constants:
const trigrams_limit: usize = 50; // number of trigrams to use for guessing using duplicate occurrences
const trigrams_limit_last_characters: usize = 400; // number of trigrams to use for guessing last few characters
const trigrams_key_limit: usize = 20; // number of candidate keys to use for guessing after sorting by (weight * count)
const trigrams_min_dups: usize = 3; // minimum number of trigram duplicates needed in a column
const min_prefixes_for_last_chars: usize = 3; // minimum number of prefixes needed to guess the last few characters without weights
// break ctr cipher one column at a time
// input: a list of cipher strings encrypted usinf CTR with same nonce
// output: a corresponding list of decrypted plain texts and keystream
//
pub fn break_ctr(ciphers: &Vec<Vec<u8>>) -> Result<Vec<u8>, err::Error> {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
let mut keystream = Vec::<u8>::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let (tri_idx, tri_c) = detect_trigrams(&ciphers);
let mut tri_idx_it = tri_idx.iter(); // iterator over trigram column indexes
let mut tri_c_it = tri_c.iter(); // iterator over corresponding lists of cipher characters
let mut all_ciphers_done = false;
while!all_ciphers_done {
let mut col = Vec::<u8>::new(); // extract a column
for it in cipher_its.iter_mut() {
match it.next() {
Some(v) => col.push(*v),
None => {}
};
}
if col.len() > 0 {
let tidx = match tri_idx_it.next() { // trigram column index: 0, 1 or 2
Some(v) => *v, // 3: if no trigram
None => 3
};
let empty_vec = Vec::<u8>::new();
let tc = match tri_c_it.next() { // cipher character list for the column
Some(v) => v, // (those found as trigram duplicates)
None => &empty_vec
};
let cw: (Vec<u8>, Vec<u32>);
if tidx < 3 && tc.len() > trigrams_min_dups {
cw = try!(filter_candidates(tidx, &tc));
} else {
cw = try!(filter_candidates_for_last_chars(&ciphers, &keystream));
}
let weights: Vec<f32> = cw.1.iter().map(|v| *v as f32).collect();
let mut options = obx::GuessOptions::new();
if cw.0.len() > 0 {
try!(options.set_candidates(&cw.0, &weights));
}
keystream.push(try!(obx::guess_key(&col, Some(&options))).key);
} else
|
}
Ok(keystream)
}
fn filter_candidates(col: usize, c: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let tri_col: Vec<u8> = trigrams_col_no_weights!(col, trigrams_limit, "");
let result: Vec<u8>;
let weights: Vec<u32> = Vec::<u32>::new(); // will not contain weights
//println!("dup count: {}", c.len());
if c.len() == 1 {
result = tri_col.iter().map(|tc| tc ^ c[0]).collect();
} else {
let mut r = Vec::<u8>::new();
let cipher_chars_freq = util::freq(&c);
let trigram_chars_freq = util::freq(&tri_col);
for ccf in cipher_chars_freq.iter() { // eliminate candidates
// e.g. if a cipher char's freq = 2, then only
// select trigram chars whose freq >= 2
let filtered_by_freq = trigram_chars_freq.iter().filter(|tcf| tcf.1 >= ccf.1 && tcf.0!= ('#' as u8));
let keys: Vec<u8> = filtered_by_freq.map(|fbf| fbf.0 ^ ccf.0).collect();
r.extend(&keys);
}
let mut r2: Vec<(u8, usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1).cmp(&(a.1))); // sort by descending count
// only take the first "n" candidate keys
result = (0.. trigrams_key_limit).zip(&r2).map(|(_, &t)| (t as (u8, usize)).0).collect();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// for the last few characters (columns for which the count of duplicate trigrams detected < 3),
// we use last 2 decrypted characters as a prefix to predict next character using the trigram list
//
fn filter_candidates_for_last_chars(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<(Vec<u8>, Vec<u32>), err::Error> {
let mut prefixes = Vec::<(Vec<u8>, u8, usize)>::new(); // all prefixes of length 2
let mut ks_it = keystream.iter().rev();
let k2 = ks_it.next().unwrap();
let k1 = ks_it.next().unwrap();
let ks_len = keystream.len();
let vnl = ascii::valid_non_letters();
let replace_non_letter_by_hash = |p| match vnl.iter().any(|&c| c == p) { // so, d, becomes d#
true => '#' as u8, // this'll help lookup matching trigrams
false => p };
for cipher in ciphers { // for each of the ciphers, decrypt the last 2 bytes
if cipher.len() >= ks_len + 1 { // using the keystream generated so far
let mut prefix = Vec::<u8>::new(); // predict the next plain character using matching trigrams
// with the same 2-byte prefix
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 2] ^ k1));
prefix.push(replace_non_letter_by_hash(cipher[ks_len - 1] ^ k2));
//println!("{}", rts!(&prefix));
prefixes.push((prefix, cipher[ks_len], cipher.len() - ks_len));
}
}
let mut r = Vec::<(u8, u32)>::new(); // hold the (key, weight) pairs before sorting
let not_enough_prefixes = prefixes.len() < min_prefixes_for_last_chars;
for p in prefixes {
let tcol: Vec<(u8, u32)> = try!(charfreq::trigrams_col(2, trigrams_limit_last_characters, rts!(&p.0).as_ref()));
let letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0!= '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
let non_letter_keys: Vec<(u8, u32)> = tcol.iter().filter(|&u| u.0 == '#' as u8).map(|u| (u.0 ^ p.1, u.1)).collect();
r.extend(letter_keys); // add candidate keys for letters
r.extend(non_letter_keys); // add candidate keys for non-letters
}
let mut r2: Vec<((u8, u32), usize)> = util::freq(&r); // get a count of occurrence of each of the keys
r2.sort_by(|&a, &b| (b.1 as u32 * (b.0).1).cmp(&(a.1 as u32 * (a.0).1))); // sort by descending (weight * count)
//for i in r2.iter() {
// println!("({}, {}), {}", (i.0).0, (i.0).1, i.1);
//}
// only take the first "n" candidate keys
let (result, mut weights): (Vec<u8>, Vec<u32>) = (0.. trigrams_key_limit).zip(r2).map(|(_, t)| ((t.0).0, (t.0).1)).unzip();
if! not_enough_prefixes {
weights.clear();
}
//println!("candidates: {}", rawd!(&result));
Ok((result, weights))
}
// detect trigrams (by detecting repeating 3-byte patterns starting at a column)
// return:
// 1. a vector of size = max cipher length
// with 0, 1 or 2 to indicate trigram character column in each position
// 3: no trigram detected in that position
// 2. a vector of size = max cipher length
// with trigram bytes (cipher) if detected in that position
// else: empty vector
//
pub fn detect_trigrams(ciphers: &Vec<Vec<u8>>) -> (Vec<usize>, Vec<Vec<u8>>) {
let mut cipher_its: Vec<slice::Iter<u8>> = Vec::new();
for c in ciphers {
cipher_its.push(c.iter());
}
let mut result_i = Vec::<usize>::new(); // column number 0, 1 or 2 of the detected duplicate trigram
let mut result_c = Vec::<Vec<u8>>::new(); // cipher characters for each of the duplicate trigram detected in that column
let mut buf = Vec::<Vec<u8>>::new(); // a cycling 3-byte buffer for trigram duplicate detection
for _ in 0.. ciphers.len() {
buf.push(vec![0; 3]);
}
let mut idx = 0; // cipher byte index
let mut all_ciphers_done = false;
while! all_ciphers_done {
{
let mut buf_it = buf.iter_mut();
all_ciphers_done = true;
for it in cipher_its.iter_mut() {
let c = match it.next() {
Some(v) => { all_ciphers_done = false; v }, // if all cipher iters yield none, we are done
None => { let mut b = buf_it.next().unwrap(); b.clear(); continue; }
};
let t = buf_it.next().unwrap();
t[0] = t[1]; t[1] = t[2]; t[2] = *c; // cycle the buffer
}
}
if all_ciphers_done {
break;
}
//println!("-");
result_i.push(3);
result_c.push(vec![]);
if idx >= 2 {
let trigrams_left = buf.iter().filter(|t| t.len()!= 0).count() > 1;
if trigrams_left {
let dups = util::dup::<Vec<u8>>(&buf);
for dup in dups {
if dup.0.len()!= 0 {
//println!("dup: {}, {}", ascii::raw_to_str(&dup.0).unwrap(), dup.1);
result_i[idx - 2] = 0; result_c[idx - 2].push(dup.0[0]);
result_i[idx - 1] = 1; result_c[idx - 1].push(dup.0[1]);
result_i[idx] = 2; result_c[idx].push(dup.0[2]);
}
}
} else {
all_ciphers_done = true;
}
}
idx += 1;
}
(result_i, result_c)
}
pub fn xor_keystream(ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Vec<String> {
let mut result = Vec::<String>::new();
for c in ciphers {
result.push(c.iter().zip(keystream.iter()).map(|(&c, &k)| chr!(c ^ k)).collect());
}
result
}
pub fn generate_ciphers_from_file(filepath: &str) -> Result<Vec<Vec<u8>>, err::Error> {
let text = try!(util::read_file_to_str(&filepath));
let cbox = try!(cb::CipherBox::new(&vec![], aes::ctr_128));
let mut ciphers = Vec::<Vec<u8>>::new();
for line in text.lines() {
ciphers.push(try!(cbox.encrypt(&b64tr!(&line))));
}
Ok(ciphers)
}
pub fn break_ctr_with_manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let keystream = try!(break_ctr(&ciphers));
let plains = try!(manual_guess_for_last_chars(&ciphers, &keystream, &guesses));
Ok(plains)
}
// this function will keep asking the user for his guesses for last characters
// it first calls auto decryption, then expects the user to supply guesses
// a guess is provided as: line no, suffix
// e.g. > 4, head
// use # for wildcard
// e.g. > 4, hat# or > 4, ##er, etc.
// enter nothing to exit the loop
//
// input parameter guesses is intended for automated testing
//
pub fn manual_guess_for_last_chars(ciphers: &Vec<Vec<u8>>, auto_guess_keystream: &Vec<u8>, guesses: &Vec<(usize, &str)>) ->
Result<Vec<String>, err::Error> {
let mut plains = xor_keystream(&ciphers, &auto_guess_keystream);
let mut keystream = auto_guess_keystream.clone();
fn display(plains: &Vec<String>) { // display plain text lines with line numbers
let mut c = 0;
for p in plains {
println!("{:02} {}", c, p);
c += 1;
}
}
fn fix_keystream(line_no: usize, suffix: &str, ciphers: &Vec<Vec<u8>>, keystream: &Vec<u8>) -> Result<Vec<u8>, err::Error> {
let suffix_r = raw!(&suffix);
let cipher: &Vec<u8> = &ciphers[line_no];
let new_ks_bytes: Vec<u8> = cipher.iter().rev().zip(suffix_r.iter().rev()).map(|(c, s)| c ^ s).rev().collect();
let mut new_keystream = keystream.clone();
let ks_start = cipher.len() - suffix_r.len();
for i in 0.. new_ks_bytes.len() {
if suffix_r[i]!= '#' as u8 {
new_keystream[ks_start + i] = new_ks_bytes[i];
}
}
Ok(new_keystream)
};
if guesses.len() > 0 { // guesses provided, so, don't ask the user
for guess in guesses {
keystream = try!(fix_keystream(guess.0, guess.1, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
}
} else { // interact with user
display(&plains);
loop {
let user_input = try!(util::input("enter guess (line no, last chars) [blank to exit]: "));
if user_input.trim() == "" {
break;
}
let parts: Vec<&str> = user_input.splitn(2, ",").collect();
ctry!(parts.len()!= 2, "need two values: line number, suffix");
let line_no = etry!(parts[0].parse::<usize>(), format!("{} is not a valid number", parts[0]));
let suffix = parts[1].trim();
keystream = try!(fix_keystream(line_no, &suffix, &ciphers, &mut keystream));
plains = xor_keystream(&ciphers, &keystream);
display(&plains);
}
}
Ok(plains)
}
pub fn interactive() -> err::ExitCode {
let input_filepath = match env::args().nth(2) {
Some(v) => v,
None => { println!("please specify input plain data (base64 encoded) filepath"); return exit_err!(); }
};
let ciphers = rtry!(generate_ciphers_from_file(&input_filepath), exit_err!());
let plains = rtry!(break_ctr_with_manual_guess_for_last_chars(&ciphers, &vec![]), exit_err!());
for p in plains {
println!("{}", p);
}
exit_ok!()
}
|
{
all_ciphers_done = true;
}
|
conditional_block
|
space_map_disk.rs
|
use anyhow::Result;
use crate::pdata::btree_builder::*;
use crate::pdata::space_map::*;
use crate::pdata::space_map_common::*;
use crate::write_batcher::*;
//------------------------------------------
pub fn write_disk_sm(w: &mut WriteBatcher, sm: &dyn SpaceMap) -> Result<SMRoot> {
let (index_entries, ref_count_root) = write_common(w, sm)?;
let mut index_builder: BTreeBuilder<IndexEntry> = BTreeBuilder::new(Box::new(NoopRC {}));
for (i, ie) in index_entries.iter().enumerate() {
index_builder.push_value(w, i as u64, *ie)?;
}
|
w.flush()?;
Ok(SMRoot {
nr_blocks: sm.get_nr_blocks()?,
nr_allocated: sm.get_nr_allocated()?,
bitmap_root,
ref_count_root,
})
}
//------------------------------------------
|
let bitmap_root = index_builder.complete(w)?;
|
random_line_split
|
structure.rs
|
// Copyright 2015 The Gfx-rs 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.
//! Macro for implementing Structure for vertex and constant buffers.
#[macro_export]
macro_rules! gfx_impl_struct {
($runtime_format:ty : $compile_format:path = $root:ident {
$( $field:ident: $ty:ty = $name:expr, )*
}) => {
#[derive(Clone, Copy, Debug)]
pub struct $root {
$( pub $field: $ty, )*
}
impl $crate::pso::buffer::Structure<$runtime_format> for $root {
fn query(name: &str) -> Option<$crate::pso::buffer::Element<$runtime_format>> {
use std::mem::size_of;
use $crate::pso::buffer::{Element, ElemOffset, ElemStride};
let stride = size_of::<$root>() as ElemStride;
let tmp: &$root = unsafe{ ::std::mem::uninitialized() };
let base = tmp as *const _ as usize;
match name {
$(
$name => Some(Element {
format: <$ty as $compile_format>::get_format(),
offset: ((&tmp.$field as *const _ as usize) - base) as ElemOffset,
|
}
}
}
}
}
#[macro_export]
macro_rules! gfx_vertex_struct {
($root:ident {
$( $field:ident: $ty:ty = $name:expr, )*
}) => (gfx_impl_struct!{
$crate::format::Format : $crate::format::Formatted =
$root {
$( $field: $ty = $name, )*
}
})
}
#[macro_export]
macro_rules! gfx_constant_struct {
($root:ident {
$( $field:ident: $ty:ty = $name:expr, )*
}) => (gfx_impl_struct!{
$crate::shade::ConstFormat : $crate::shade::Formatted =
$root {
$( $field: $ty = $name, )*
}
})
}
|
stride: stride,
}),
)*
_ => None,
|
random_line_split
|
owned_stack.rs
|
// This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <[email protected]>
// See the LICENSE file included in this distribution.
extern crate alloc;
use core::slice;
use self::alloc::heap;
use self::alloc::boxed::Box;
/// OwnedStack holds a non-guarded, heap-allocated stack.
#[derive(Debug)]
pub struct OwnedStack(Box<[u8]>);
impl OwnedStack {
/// Allocates a new stack with exactly `size` accessible bytes and alignment appropriate
/// for the current platform using the default Rust allocator.
pub fn
|
(size: usize) -> OwnedStack {
unsafe {
let ptr = heap::allocate(size, ::STACK_ALIGNMENT);
OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, size)))
}
}
}
impl ::stack::Stack for OwnedStack {
#[inline(always)]
fn base(&self) -> *mut u8 {
// The slice cannot wrap around the address space, so the conversion from usize
// to isize will not wrap either.
let len: isize = self.0.len() as isize;
unsafe { self.limit().offset(len) }
}
#[inline(always)]
fn limit(&self) -> *mut u8 {
self.0.as_ptr() as *mut u8
}
}
|
new
|
identifier_name
|
owned_stack.rs
|
// This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <[email protected]>
// See the LICENSE file included in this distribution.
extern crate alloc;
use core::slice;
use self::alloc::heap;
use self::alloc::boxed::Box;
/// OwnedStack holds a non-guarded, heap-allocated stack.
#[derive(Debug)]
pub struct OwnedStack(Box<[u8]>);
|
pub fn new(size: usize) -> OwnedStack {
unsafe {
let ptr = heap::allocate(size, ::STACK_ALIGNMENT);
OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, size)))
}
}
}
impl ::stack::Stack for OwnedStack {
#[inline(always)]
fn base(&self) -> *mut u8 {
// The slice cannot wrap around the address space, so the conversion from usize
// to isize will not wrap either.
let len: isize = self.0.len() as isize;
unsafe { self.limit().offset(len) }
}
#[inline(always)]
fn limit(&self) -> *mut u8 {
self.0.as_ptr() as *mut u8
}
}
|
impl OwnedStack {
/// Allocates a new stack with exactly `size` accessible bytes and alignment appropriate
/// for the current platform using the default Rust allocator.
|
random_line_split
|
crypto.rs
|
use argon2::{self, Config, ThreadMode, Variant, Version};
use errors::Error;
// hash encodes plaintext with a salt vector slice. Returns encoded string or
// fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html)
pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> {
// cfg is Argon2id hybrid version. It follows the Argon2i approach
// for the first pass over memory and the Argon2d approach for subsequent passes.
//
|
// For optimal security, cost parameters should be fine tuned to machine
// CPU and memory specs.
//
// ref: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
let cfg = Config {
variant: Variant::Argon2id,
version: Version::Version13,
mem_cost: 512,
time_cost: 100,
lanes: 4,
thread_mode: ThreadMode::Parallel,
secret: &[],
ad: &[],
hash_length: 28,
};
let argon2id = argon2::hash_encoded(password.as_bytes(), &salt.as_ref(), &cfg)?;
Ok(argon2id)
}
// verifies hash_encoded method output as true. Returns DecodingFail if failure.
pub fn verify(encoded_hash: &str, password: &[u8]) -> Result<bool, Error> {
let is_valid = argon2::verify_encoded(encoded_hash, password)?;
Ok(is_valid)
}
// generate_salt creates salt vector of a usize parameter.
pub fn generate_salt(size: usize) -> Vec<u8> {
nonce(size).as_bytes().to_vec()
}
// nonce takes a usize parameter for length
fn nonce(take: usize) -> String {
use rand::{self, Rng};
rand::thread_rng()
.gen_ascii_chars()
.take(take)
.collect::<String>()
}
#[cfg(test)]
mod tests {
use super::generate_salt;
use super::hash;
use super::verify;
const PWD: &str = "Passw0rd!";
const INCORRECT_PWD: &str = "Inc0rrect!";
#[test]
fn gen_salt() {
let salt = generate_salt(24);
assert_eq!(24, salt.len());
}
#[test]
fn hash_and_validate() {
let salt = generate_salt(16);
let digest = hash(&PWD, salt).unwrap();
let verified = verify(&digest, &PWD.as_bytes()).unwrap();
let should_eq_false = verify(&digest, &INCORRECT_PWD.as_bytes()).unwrap();
assert_eq!(verified, true);
assert_eq!(should_eq_false, false)
}
}
|
random_line_split
|
|
crypto.rs
|
use argon2::{self, Config, ThreadMode, Variant, Version};
use errors::Error;
// hash encodes plaintext with a salt vector slice. Returns encoded string or
// fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html)
pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> {
// cfg is Argon2id hybrid version. It follows the Argon2i approach
// for the first pass over memory and the Argon2d approach for subsequent passes.
//
// For optimal security, cost parameters should be fine tuned to machine
// CPU and memory specs.
//
// ref: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
let cfg = Config {
variant: Variant::Argon2id,
version: Version::Version13,
mem_cost: 512,
time_cost: 100,
lanes: 4,
thread_mode: ThreadMode::Parallel,
secret: &[],
ad: &[],
hash_length: 28,
};
let argon2id = argon2::hash_encoded(password.as_bytes(), &salt.as_ref(), &cfg)?;
Ok(argon2id)
}
// verifies hash_encoded method output as true. Returns DecodingFail if failure.
pub fn verify(encoded_hash: &str, password: &[u8]) -> Result<bool, Error>
|
// generate_salt creates salt vector of a usize parameter.
pub fn generate_salt(size: usize) -> Vec<u8> {
nonce(size).as_bytes().to_vec()
}
// nonce takes a usize parameter for length
fn nonce(take: usize) -> String {
use rand::{self, Rng};
rand::thread_rng()
.gen_ascii_chars()
.take(take)
.collect::<String>()
}
#[cfg(test)]
mod tests {
use super::generate_salt;
use super::hash;
use super::verify;
const PWD: &str = "Passw0rd!";
const INCORRECT_PWD: &str = "Inc0rrect!";
#[test]
fn gen_salt() {
let salt = generate_salt(24);
assert_eq!(24, salt.len());
}
#[test]
fn hash_and_validate() {
let salt = generate_salt(16);
let digest = hash(&PWD, salt).unwrap();
let verified = verify(&digest, &PWD.as_bytes()).unwrap();
let should_eq_false = verify(&digest, &INCORRECT_PWD.as_bytes()).unwrap();
assert_eq!(verified, true);
assert_eq!(should_eq_false, false)
}
}
|
{
let is_valid = argon2::verify_encoded(encoded_hash, password)?;
Ok(is_valid)
}
|
identifier_body
|
crypto.rs
|
use argon2::{self, Config, ThreadMode, Variant, Version};
use errors::Error;
// hash encodes plaintext with a salt vector slice. Returns encoded string or
// fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html)
pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> {
// cfg is Argon2id hybrid version. It follows the Argon2i approach
// for the first pass over memory and the Argon2d approach for subsequent passes.
//
// For optimal security, cost parameters should be fine tuned to machine
// CPU and memory specs.
//
// ref: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
let cfg = Config {
variant: Variant::Argon2id,
version: Version::Version13,
mem_cost: 512,
time_cost: 100,
lanes: 4,
thread_mode: ThreadMode::Parallel,
secret: &[],
ad: &[],
hash_length: 28,
};
let argon2id = argon2::hash_encoded(password.as_bytes(), &salt.as_ref(), &cfg)?;
Ok(argon2id)
}
// verifies hash_encoded method output as true. Returns DecodingFail if failure.
pub fn verify(encoded_hash: &str, password: &[u8]) -> Result<bool, Error> {
let is_valid = argon2::verify_encoded(encoded_hash, password)?;
Ok(is_valid)
}
// generate_salt creates salt vector of a usize parameter.
pub fn generate_salt(size: usize) -> Vec<u8> {
nonce(size).as_bytes().to_vec()
}
// nonce takes a usize parameter for length
fn nonce(take: usize) -> String {
use rand::{self, Rng};
rand::thread_rng()
.gen_ascii_chars()
.take(take)
.collect::<String>()
}
#[cfg(test)]
mod tests {
use super::generate_salt;
use super::hash;
use super::verify;
const PWD: &str = "Passw0rd!";
const INCORRECT_PWD: &str = "Inc0rrect!";
#[test]
fn
|
() {
let salt = generate_salt(24);
assert_eq!(24, salt.len());
}
#[test]
fn hash_and_validate() {
let salt = generate_salt(16);
let digest = hash(&PWD, salt).unwrap();
let verified = verify(&digest, &PWD.as_bytes()).unwrap();
let should_eq_false = verify(&digest, &INCORRECT_PWD.as_bytes()).unwrap();
assert_eq!(verified, true);
assert_eq!(should_eq_false, false)
}
}
|
gen_salt
|
identifier_name
|
into_matcher.rs
|
use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
}
}
lazy_static! {
static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
}
pub static FORMAT_PARAM: &'static str = "format";
// FIXME: Once const fn lands this could be defined in terms of the above
static FORMAT_VAR: &'static str = ":format";
static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*";
static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*";
// matches request params (e.g.?foo=true&bar=false)
static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?";
impl From<String> for Matcher {
fn from(s: String) -> Matcher
|
// There should only ever be one match (after subgroup 0)
let c = captures.iter().skip(1).next().unwrap();
format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap())
});
let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ);
let regex = Regex::new(&line_regex).unwrap();
Matcher::new(with_format, regex)
}
}
|
{
let with_format = if s.contains(FORMAT_VAR) {
s
} else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// which would get overwritten with the next replace call
let with_placeholder = with_format.replace("**", "___DOUBLE_WILDCARD___");
// Then replace the regular wildcard symbols (*) with the appropriate regex
let star_replaced = with_placeholder.replace("*", VAR_SEQ);
// Now replace the previously marked double wild cards (**)
let wildcarded = star_replaced.replace("___DOUBLE_WILDCARD___", VAR_SEQ_WITH_SLASH);
// Add a named capture for each :(variable) symbol
let named_captures = REGEX_VAR_SEQ.replace_all(&wildcarded, |captures: &Captures| {
|
identifier_body
|
into_matcher.rs
|
use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn
|
(s: &'a str) -> Matcher {
From::from(s.to_string())
}
}
lazy_static! {
static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
}
pub static FORMAT_PARAM: &'static str = "format";
// FIXME: Once const fn lands this could be defined in terms of the above
static FORMAT_VAR: &'static str = ":format";
static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*";
static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*";
// matches request params (e.g.?foo=true&bar=false)
static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?";
impl From<String> for Matcher {
fn from(s: String) -> Matcher {
let with_format = if s.contains(FORMAT_VAR) {
s
} else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// which would get overwritten with the next replace call
let with_placeholder = with_format.replace("**", "___DOUBLE_WILDCARD___");
// Then replace the regular wildcard symbols (*) with the appropriate regex
let star_replaced = with_placeholder.replace("*", VAR_SEQ);
// Now replace the previously marked double wild cards (**)
let wildcarded = star_replaced.replace("___DOUBLE_WILDCARD___", VAR_SEQ_WITH_SLASH);
// Add a named capture for each :(variable) symbol
let named_captures = REGEX_VAR_SEQ.replace_all(&wildcarded, |captures: &Captures| {
// There should only ever be one match (after subgroup 0)
let c = captures.iter().skip(1).next().unwrap();
format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap())
});
let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ);
let regex = Regex::new(&line_regex).unwrap();
Matcher::new(with_format, regex)
}
}
|
from
|
identifier_name
|
into_matcher.rs
|
use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
}
}
lazy_static! {
static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
}
pub static FORMAT_PARAM: &'static str = "format";
// FIXME: Once const fn lands this could be defined in terms of the above
static FORMAT_VAR: &'static str = ":format";
static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*";
static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*";
// matches request params (e.g.?foo=true&bar=false)
static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?";
impl From<String> for Matcher {
fn from(s: String) -> Matcher {
let with_format = if s.contains(FORMAT_VAR)
|
else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// which would get overwritten with the next replace call
let with_placeholder = with_format.replace("**", "___DOUBLE_WILDCARD___");
// Then replace the regular wildcard symbols (*) with the appropriate regex
let star_replaced = with_placeholder.replace("*", VAR_SEQ);
// Now replace the previously marked double wild cards (**)
let wildcarded = star_replaced.replace("___DOUBLE_WILDCARD___", VAR_SEQ_WITH_SLASH);
// Add a named capture for each :(variable) symbol
let named_captures = REGEX_VAR_SEQ.replace_all(&wildcarded, |captures: &Captures| {
// There should only ever be one match (after subgroup 0)
let c = captures.iter().skip(1).next().unwrap();
format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap())
});
let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ);
let regex = Regex::new(&line_regex).unwrap();
Matcher::new(with_format, regex)
}
}
|
{
s
}
|
conditional_block
|
into_matcher.rs
|
use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
}
}
lazy_static! {
|
static FORMAT_VAR: &'static str = ":format";
static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*";
static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*";
// matches request params (e.g.?foo=true&bar=false)
static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?";
impl From<String> for Matcher {
fn from(s: String) -> Matcher {
let with_format = if s.contains(FORMAT_VAR) {
s
} else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// which would get overwritten with the next replace call
let with_placeholder = with_format.replace("**", "___DOUBLE_WILDCARD___");
// Then replace the regular wildcard symbols (*) with the appropriate regex
let star_replaced = with_placeholder.replace("*", VAR_SEQ);
// Now replace the previously marked double wild cards (**)
let wildcarded = star_replaced.replace("___DOUBLE_WILDCARD___", VAR_SEQ_WITH_SLASH);
// Add a named capture for each :(variable) symbol
let named_captures = REGEX_VAR_SEQ.replace_all(&wildcarded, |captures: &Captures| {
// There should only ever be one match (after subgroup 0)
let c = captures.iter().skip(1).next().unwrap();
format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap())
});
let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ);
let regex = Regex::new(&line_regex).unwrap();
Matcher::new(with_format, regex)
}
}
|
static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
}
pub static FORMAT_PARAM: &'static str = "format";
// FIXME: Once const fn lands this could be defined in terms of the above
|
random_line_split
|
mod.rs
|
use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, V>, ()>;
pub type SnapshotMapRef<'a, K, V, L> = SnapshotMap<K, V, &'a mut FxHashMap<K, V>, &'a mut L>;
pub struct SnapshotMap<K, V, M = FxHashMap<K, V>, L = VecLog<UndoLog<K, V>>> {
map: M,
undo_log: L,
_marker: PhantomData<(K, V)>,
}
// HACK(eddyb) manual impl avoids `Default` bounds on `K` and `V`.
impl<K, V, M, L> Default for SnapshotMap<K, V, M, L>
where
M: Default,
L: Default,
{
fn default() -> Self {
SnapshotMap { map: Default::default(), undo_log: Default::default(), _marker: PhantomData }
}
}
pub enum UndoLog<K, V> {
Inserted(K),
Overwrite(K, V),
Purged,
}
impl<K, V, M, L> SnapshotMap<K, V, M, L> {
#[inline]
pub fn with_log<L2>(&mut self, undo_log: L2) -> SnapshotMap<K, V, &mut M, L2> {
SnapshotMap { map: &mut self.map, undo_log, _marker: PhantomData }
}
}
impl<K, V, M, L> SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: BorrowMut<FxHashMap<K, V>> + Borrow<FxHashMap<K, V>>,
L: UndoLogs<UndoLog<K, V>>,
{
pub fn clear(&mut self) {
self.map.borrow_mut().clear();
self.undo_log.clear();
}
pub fn insert(&mut self, key: K, value: V) -> bool {
match self.map.borrow_mut().insert(key.clone(), value) {
None => {
self.undo_log.push(UndoLog::Inserted(key));
true
}
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
false
}
}
}
pub fn remove(&mut self, key: K) -> bool {
match self.map.borrow_mut().remove(&key) {
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
true
}
None => false,
}
|
pub fn get(&self, key: &K) -> Option<&V> {
self.map.borrow().get(key)
}
}
impl<K, V> SnapshotMap<K, V>
where
K: Hash + Clone + Eq,
{
pub fn snapshot(&mut self) -> Snapshot {
self.undo_log.start_snapshot()
}
pub fn commit(&mut self, snapshot: Snapshot) {
self.undo_log.commit(snapshot)
}
pub fn rollback_to(&mut self, snapshot: Snapshot) {
let map = &mut self.map;
self.undo_log.rollback_to(|| map, snapshot)
}
}
impl<'k, K, V, M, L> ops::Index<&'k K> for SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: Borrow<FxHashMap<K, V>>,
{
type Output = V;
fn index(&self, key: &'k K) -> &V {
&self.map.borrow()[key]
}
}
impl<K, V, M, L> Rollback<UndoLog<K, V>> for SnapshotMap<K, V, M, L>
where
K: Eq + Hash,
M: Rollback<UndoLog<K, V>>,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
self.map.reverse(undo)
}
}
impl<K, V> Rollback<UndoLog<K, V>> for FxHashMap<K, V>
where
K: Eq + Hash,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
match undo {
UndoLog::Inserted(key) => {
self.remove(&key);
}
UndoLog::Overwrite(key, old_value) => {
self.insert(key, old_value);
}
UndoLog::Purged => {}
}
}
}
|
}
|
random_line_split
|
mod.rs
|
use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, V>, ()>;
pub type SnapshotMapRef<'a, K, V, L> = SnapshotMap<K, V, &'a mut FxHashMap<K, V>, &'a mut L>;
pub struct SnapshotMap<K, V, M = FxHashMap<K, V>, L = VecLog<UndoLog<K, V>>> {
map: M,
undo_log: L,
_marker: PhantomData<(K, V)>,
}
// HACK(eddyb) manual impl avoids `Default` bounds on `K` and `V`.
impl<K, V, M, L> Default for SnapshotMap<K, V, M, L>
where
M: Default,
L: Default,
{
fn default() -> Self {
SnapshotMap { map: Default::default(), undo_log: Default::default(), _marker: PhantomData }
}
}
pub enum UndoLog<K, V> {
Inserted(K),
Overwrite(K, V),
Purged,
}
impl<K, V, M, L> SnapshotMap<K, V, M, L> {
#[inline]
pub fn with_log<L2>(&mut self, undo_log: L2) -> SnapshotMap<K, V, &mut M, L2> {
SnapshotMap { map: &mut self.map, undo_log, _marker: PhantomData }
}
}
impl<K, V, M, L> SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: BorrowMut<FxHashMap<K, V>> + Borrow<FxHashMap<K, V>>,
L: UndoLogs<UndoLog<K, V>>,
{
pub fn clear(&mut self) {
self.map.borrow_mut().clear();
self.undo_log.clear();
}
pub fn insert(&mut self, key: K, value: V) -> bool {
match self.map.borrow_mut().insert(key.clone(), value) {
None => {
self.undo_log.push(UndoLog::Inserted(key));
true
}
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
false
}
}
}
pub fn remove(&mut self, key: K) -> bool {
match self.map.borrow_mut().remove(&key) {
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
true
}
None => false,
}
}
pub fn get(&self, key: &K) -> Option<&V> {
self.map.borrow().get(key)
}
}
impl<K, V> SnapshotMap<K, V>
where
K: Hash + Clone + Eq,
{
pub fn snapshot(&mut self) -> Snapshot {
self.undo_log.start_snapshot()
}
pub fn commit(&mut self, snapshot: Snapshot) {
self.undo_log.commit(snapshot)
}
pub fn rollback_to(&mut self, snapshot: Snapshot) {
let map = &mut self.map;
self.undo_log.rollback_to(|| map, snapshot)
}
}
impl<'k, K, V, M, L> ops::Index<&'k K> for SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: Borrow<FxHashMap<K, V>>,
{
type Output = V;
fn index(&self, key: &'k K) -> &V {
&self.map.borrow()[key]
}
}
impl<K, V, M, L> Rollback<UndoLog<K, V>> for SnapshotMap<K, V, M, L>
where
K: Eq + Hash,
M: Rollback<UndoLog<K, V>>,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
self.map.reverse(undo)
}
}
impl<K, V> Rollback<UndoLog<K, V>> for FxHashMap<K, V>
where
K: Eq + Hash,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
match undo {
UndoLog::Inserted(key) => {
self.remove(&key);
}
UndoLog::Overwrite(key, old_value) =>
|
UndoLog::Purged => {}
}
}
}
|
{
self.insert(key, old_value);
}
|
conditional_block
|
mod.rs
|
use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, V>, ()>;
pub type SnapshotMapRef<'a, K, V, L> = SnapshotMap<K, V, &'a mut FxHashMap<K, V>, &'a mut L>;
pub struct SnapshotMap<K, V, M = FxHashMap<K, V>, L = VecLog<UndoLog<K, V>>> {
map: M,
undo_log: L,
_marker: PhantomData<(K, V)>,
}
// HACK(eddyb) manual impl avoids `Default` bounds on `K` and `V`.
impl<K, V, M, L> Default for SnapshotMap<K, V, M, L>
where
M: Default,
L: Default,
{
fn default() -> Self {
SnapshotMap { map: Default::default(), undo_log: Default::default(), _marker: PhantomData }
}
}
pub enum UndoLog<K, V> {
Inserted(K),
Overwrite(K, V),
Purged,
}
impl<K, V, M, L> SnapshotMap<K, V, M, L> {
#[inline]
pub fn with_log<L2>(&mut self, undo_log: L2) -> SnapshotMap<K, V, &mut M, L2> {
SnapshotMap { map: &mut self.map, undo_log, _marker: PhantomData }
}
}
impl<K, V, M, L> SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: BorrowMut<FxHashMap<K, V>> + Borrow<FxHashMap<K, V>>,
L: UndoLogs<UndoLog<K, V>>,
{
pub fn clear(&mut self) {
self.map.borrow_mut().clear();
self.undo_log.clear();
}
pub fn insert(&mut self, key: K, value: V) -> bool
|
pub fn remove(&mut self, key: K) -> bool {
match self.map.borrow_mut().remove(&key) {
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
true
}
None => false,
}
}
pub fn get(&self, key: &K) -> Option<&V> {
self.map.borrow().get(key)
}
}
impl<K, V> SnapshotMap<K, V>
where
K: Hash + Clone + Eq,
{
pub fn snapshot(&mut self) -> Snapshot {
self.undo_log.start_snapshot()
}
pub fn commit(&mut self, snapshot: Snapshot) {
self.undo_log.commit(snapshot)
}
pub fn rollback_to(&mut self, snapshot: Snapshot) {
let map = &mut self.map;
self.undo_log.rollback_to(|| map, snapshot)
}
}
impl<'k, K, V, M, L> ops::Index<&'k K> for SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: Borrow<FxHashMap<K, V>>,
{
type Output = V;
fn index(&self, key: &'k K) -> &V {
&self.map.borrow()[key]
}
}
impl<K, V, M, L> Rollback<UndoLog<K, V>> for SnapshotMap<K, V, M, L>
where
K: Eq + Hash,
M: Rollback<UndoLog<K, V>>,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
self.map.reverse(undo)
}
}
impl<K, V> Rollback<UndoLog<K, V>> for FxHashMap<K, V>
where
K: Eq + Hash,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
match undo {
UndoLog::Inserted(key) => {
self.remove(&key);
}
UndoLog::Overwrite(key, old_value) => {
self.insert(key, old_value);
}
UndoLog::Purged => {}
}
}
}
|
{
match self.map.borrow_mut().insert(key.clone(), value) {
None => {
self.undo_log.push(UndoLog::Inserted(key));
true
}
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
false
}
}
}
|
identifier_body
|
mod.rs
|
use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, V>, ()>;
pub type SnapshotMapRef<'a, K, V, L> = SnapshotMap<K, V, &'a mut FxHashMap<K, V>, &'a mut L>;
pub struct SnapshotMap<K, V, M = FxHashMap<K, V>, L = VecLog<UndoLog<K, V>>> {
map: M,
undo_log: L,
_marker: PhantomData<(K, V)>,
}
// HACK(eddyb) manual impl avoids `Default` bounds on `K` and `V`.
impl<K, V, M, L> Default for SnapshotMap<K, V, M, L>
where
M: Default,
L: Default,
{
fn default() -> Self {
SnapshotMap { map: Default::default(), undo_log: Default::default(), _marker: PhantomData }
}
}
pub enum UndoLog<K, V> {
Inserted(K),
Overwrite(K, V),
Purged,
}
impl<K, V, M, L> SnapshotMap<K, V, M, L> {
#[inline]
pub fn
|
<L2>(&mut self, undo_log: L2) -> SnapshotMap<K, V, &mut M, L2> {
SnapshotMap { map: &mut self.map, undo_log, _marker: PhantomData }
}
}
impl<K, V, M, L> SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: BorrowMut<FxHashMap<K, V>> + Borrow<FxHashMap<K, V>>,
L: UndoLogs<UndoLog<K, V>>,
{
pub fn clear(&mut self) {
self.map.borrow_mut().clear();
self.undo_log.clear();
}
pub fn insert(&mut self, key: K, value: V) -> bool {
match self.map.borrow_mut().insert(key.clone(), value) {
None => {
self.undo_log.push(UndoLog::Inserted(key));
true
}
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
false
}
}
}
pub fn remove(&mut self, key: K) -> bool {
match self.map.borrow_mut().remove(&key) {
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
true
}
None => false,
}
}
pub fn get(&self, key: &K) -> Option<&V> {
self.map.borrow().get(key)
}
}
impl<K, V> SnapshotMap<K, V>
where
K: Hash + Clone + Eq,
{
pub fn snapshot(&mut self) -> Snapshot {
self.undo_log.start_snapshot()
}
pub fn commit(&mut self, snapshot: Snapshot) {
self.undo_log.commit(snapshot)
}
pub fn rollback_to(&mut self, snapshot: Snapshot) {
let map = &mut self.map;
self.undo_log.rollback_to(|| map, snapshot)
}
}
impl<'k, K, V, M, L> ops::Index<&'k K> for SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: Borrow<FxHashMap<K, V>>,
{
type Output = V;
fn index(&self, key: &'k K) -> &V {
&self.map.borrow()[key]
}
}
impl<K, V, M, L> Rollback<UndoLog<K, V>> for SnapshotMap<K, V, M, L>
where
K: Eq + Hash,
M: Rollback<UndoLog<K, V>>,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
self.map.reverse(undo)
}
}
impl<K, V> Rollback<UndoLog<K, V>> for FxHashMap<K, V>
where
K: Eq + Hash,
{
fn reverse(&mut self, undo: UndoLog<K, V>) {
match undo {
UndoLog::Inserted(key) => {
self.remove(&key);
}
UndoLog::Overwrite(key, old_value) => {
self.insert(key, old_value);
}
UndoLog::Purged => {}
}
}
}
|
with_log
|
identifier_name
|
menu.rs
|
// Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec::Vec;
use gfx::GameDisplay;
use super::{UiBox, UiFont, draw_text_box, compute_text_box_bounds};
pub struct VertTextMenu<TFont, TBox> {
pub entries: Vec<String>,
pub formatted_entries: Vec<String>,
pub bg_color: (u8, u8, u8),
pub selected_prefix: String,
pub unselected_prefix: String,
pub curr_selected: uint,
pub coords: (int, int),
pub box_size: (uint, uint),
pub text_gap: uint
}
impl<TFont: UiFont, TBox: UiBox>
VertTextMenu<TFont, TBox> {
pub fn new() -> VertTextMenu<TFont, TBox> {
|
formatted_entries: Vec::new(),
bg_color: (0,0,0),
selected_prefix: "".to_string(),
unselected_prefix: "".to_string(),
curr_selected: 0,
coords: (0,0),
box_size: (0,0),
text_gap: 2
}
}
pub fn move_down(&mut self) {
let last_idx = self.entries.len() - 1;
if self.curr_selected < last_idx {
let new_idx = self.curr_selected + 1;
self.update_selected(new_idx);
}
}
pub fn move_up(&mut self) {
if self.curr_selected > 0 {
let new_idx = self.curr_selected - 1;
self.update_selected(new_idx);
}
}
fn update_selected(&mut self, new_idx: uint) {
let old_selected = self.curr_selected;
self.curr_selected = new_idx;
let selected_formatted = self.get_formatted(self.curr_selected);
self.formatted_entries.push(selected_formatted);
self.formatted_entries.swap_remove(self.curr_selected);
let unselected_formatted = self.get_formatted(old_selected);
self.formatted_entries.push(unselected_formatted);
self.formatted_entries.swap_remove(old_selected);
}
fn get_formatted(&self, v: uint) -> String {
let entry = &self.entries[v];
let prefix = if v == self.curr_selected {
&self.selected_prefix
} else {
&self.unselected_prefix
};
format!("{} {}", *prefix, entry)
}
pub fn update_bounds(&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) {
// figure out width, in pixels, of the text (based on longest entry line)
self.formatted_entries = Vec::new();
for v in range(0, self.entries.len()) {
let formatted = self.get_formatted(v);
self.formatted_entries.push(formatted);
}
self.box_size = compute_text_box_bounds(
self.formatted_entries.as_slice(), ui_font, ui_box, self.text_gap);
self.coords = coords;
}
pub fn draw_menu(&self, display: &GameDisplay, ui_font: &TFont, ui_box: &TBox) {
draw_text_box(
display, self.coords, self.box_size, self.bg_color,
self.formatted_entries.slice_from(0), ui_font, ui_box, self.text_gap);
}
}
|
VertTextMenu {
entries: Vec::new(),
|
random_line_split
|
menu.rs
|
// Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec::Vec;
use gfx::GameDisplay;
use super::{UiBox, UiFont, draw_text_box, compute_text_box_bounds};
pub struct VertTextMenu<TFont, TBox> {
pub entries: Vec<String>,
pub formatted_entries: Vec<String>,
pub bg_color: (u8, u8, u8),
pub selected_prefix: String,
pub unselected_prefix: String,
pub curr_selected: uint,
pub coords: (int, int),
pub box_size: (uint, uint),
pub text_gap: uint
}
impl<TFont: UiFont, TBox: UiBox>
VertTextMenu<TFont, TBox> {
pub fn new() -> VertTextMenu<TFont, TBox> {
VertTextMenu {
entries: Vec::new(),
formatted_entries: Vec::new(),
bg_color: (0,0,0),
selected_prefix: "".to_string(),
unselected_prefix: "".to_string(),
curr_selected: 0,
coords: (0,0),
box_size: (0,0),
text_gap: 2
}
}
pub fn move_down(&mut self) {
let last_idx = self.entries.len() - 1;
if self.curr_selected < last_idx {
let new_idx = self.curr_selected + 1;
self.update_selected(new_idx);
}
}
pub fn move_up(&mut self) {
if self.curr_selected > 0 {
let new_idx = self.curr_selected - 1;
self.update_selected(new_idx);
}
}
fn update_selected(&mut self, new_idx: uint) {
let old_selected = self.curr_selected;
self.curr_selected = new_idx;
let selected_formatted = self.get_formatted(self.curr_selected);
self.formatted_entries.push(selected_formatted);
self.formatted_entries.swap_remove(self.curr_selected);
let unselected_formatted = self.get_formatted(old_selected);
self.formatted_entries.push(unselected_formatted);
self.formatted_entries.swap_remove(old_selected);
}
fn get_formatted(&self, v: uint) -> String {
let entry = &self.entries[v];
let prefix = if v == self.curr_selected {
&self.selected_prefix
} else {
&self.unselected_prefix
};
format!("{} {}", *prefix, entry)
}
pub fn
|
(&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) {
// figure out width, in pixels, of the text (based on longest entry line)
self.formatted_entries = Vec::new();
for v in range(0, self.entries.len()) {
let formatted = self.get_formatted(v);
self.formatted_entries.push(formatted);
}
self.box_size = compute_text_box_bounds(
self.formatted_entries.as_slice(), ui_font, ui_box, self.text_gap);
self.coords = coords;
}
pub fn draw_menu(&self, display: &GameDisplay, ui_font: &TFont, ui_box: &TBox) {
draw_text_box(
display, self.coords, self.box_size, self.bg_color,
self.formatted_entries.slice_from(0), ui_font, ui_box, self.text_gap);
}
}
|
update_bounds
|
identifier_name
|
menu.rs
|
// Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec::Vec;
use gfx::GameDisplay;
use super::{UiBox, UiFont, draw_text_box, compute_text_box_bounds};
pub struct VertTextMenu<TFont, TBox> {
pub entries: Vec<String>,
pub formatted_entries: Vec<String>,
pub bg_color: (u8, u8, u8),
pub selected_prefix: String,
pub unselected_prefix: String,
pub curr_selected: uint,
pub coords: (int, int),
pub box_size: (uint, uint),
pub text_gap: uint
}
impl<TFont: UiFont, TBox: UiBox>
VertTextMenu<TFont, TBox> {
pub fn new() -> VertTextMenu<TFont, TBox> {
VertTextMenu {
entries: Vec::new(),
formatted_entries: Vec::new(),
bg_color: (0,0,0),
selected_prefix: "".to_string(),
unselected_prefix: "".to_string(),
curr_selected: 0,
coords: (0,0),
box_size: (0,0),
text_gap: 2
}
}
pub fn move_down(&mut self) {
let last_idx = self.entries.len() - 1;
if self.curr_selected < last_idx {
let new_idx = self.curr_selected + 1;
self.update_selected(new_idx);
}
}
pub fn move_up(&mut self) {
if self.curr_selected > 0 {
let new_idx = self.curr_selected - 1;
self.update_selected(new_idx);
}
}
fn update_selected(&mut self, new_idx: uint) {
let old_selected = self.curr_selected;
self.curr_selected = new_idx;
let selected_formatted = self.get_formatted(self.curr_selected);
self.formatted_entries.push(selected_formatted);
self.formatted_entries.swap_remove(self.curr_selected);
let unselected_formatted = self.get_formatted(old_selected);
self.formatted_entries.push(unselected_formatted);
self.formatted_entries.swap_remove(old_selected);
}
fn get_formatted(&self, v: uint) -> String {
let entry = &self.entries[v];
let prefix = if v == self.curr_selected
|
else {
&self.unselected_prefix
};
format!("{} {}", *prefix, entry)
}
pub fn update_bounds(&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) {
// figure out width, in pixels, of the text (based on longest entry line)
self.formatted_entries = Vec::new();
for v in range(0, self.entries.len()) {
let formatted = self.get_formatted(v);
self.formatted_entries.push(formatted);
}
self.box_size = compute_text_box_bounds(
self.formatted_entries.as_slice(), ui_font, ui_box, self.text_gap);
self.coords = coords;
}
pub fn draw_menu(&self, display: &GameDisplay, ui_font: &TFont, ui_box: &TBox) {
draw_text_box(
display, self.coords, self.box_size, self.bg_color,
self.formatted_entries.slice_from(0), ui_font, ui_box, self.text_gap);
}
}
|
{
&self.selected_prefix
}
|
conditional_block
|
main.rs
|
#![crate_name = "weather_client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
use std::env;
fn
|
(s: &str) -> i64 {
s.parse().unwrap()
}
fn main() {
println!("Collecting updates from weather server...");
let context = zmq::Context::new();
let subscriber = context.socket(zmq::SUB).unwrap();
assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args: Vec<String> = env::args().collect();
let filter = if args.len() > 1 { &args[1] } else { "10001" };
assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok());
let mut total_temp = 0;
for _ in 0.. 100 {
let string = subscriber.recv_string(0).unwrap().unwrap();
let chks: Vec<i64> = string.split(' ').map(atoi).collect();
let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]);
total_temp += temperature;
}
println!("Average temperature for zipcode '{}' was {}F", filter, (total_temp / 100));
}
|
atoi
|
identifier_name
|
main.rs
|
#![crate_name = "weather_client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
use std::env;
fn atoi(s: &str) -> i64
|
fn main() {
println!("Collecting updates from weather server...");
let context = zmq::Context::new();
let subscriber = context.socket(zmq::SUB).unwrap();
assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args: Vec<String> = env::args().collect();
let filter = if args.len() > 1 { &args[1] } else { "10001" };
assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok());
let mut total_temp = 0;
for _ in 0.. 100 {
let string = subscriber.recv_string(0).unwrap().unwrap();
let chks: Vec<i64> = string.split(' ').map(atoi).collect();
let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]);
total_temp += temperature;
}
println!("Average temperature for zipcode '{}' was {}F", filter, (total_temp / 100));
}
|
{
s.parse().unwrap()
}
|
identifier_body
|
main.rs
|
#![crate_name = "weather_client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
use std::env;
fn atoi(s: &str) -> i64 {
s.parse().unwrap()
}
fn main() {
println!("Collecting updates from weather server...");
let context = zmq::Context::new();
let subscriber = context.socket(zmq::SUB).unwrap();
assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args: Vec<String> = env::args().collect();
let filter = if args.len() > 1 { &args[1] } else { "10001" };
assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok());
let mut total_temp = 0;
|
let string = subscriber.recv_string(0).unwrap().unwrap();
let chks: Vec<i64> = string.split(' ').map(atoi).collect();
let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]);
total_temp += temperature;
}
println!("Average temperature for zipcode '{}' was {}F", filter, (total_temp / 100));
}
|
for _ in 0 .. 100 {
|
random_line_split
|
main.rs
|
#![crate_name = "weather_client"]
/*!
* Weather update client
* Connects SUB socket to tcp://localhost:5556
* Collects weather updates and find avg temp in zipcode
*/
extern crate zmq;
use std::env;
fn atoi(s: &str) -> i64 {
s.parse().unwrap()
}
fn main() {
println!("Collecting updates from weather server...");
let context = zmq::Context::new();
let subscriber = context.socket(zmq::SUB).unwrap();
assert!(subscriber.connect("tcp://localhost:5556").is_ok());
let args: Vec<String> = env::args().collect();
let filter = if args.len() > 1 { &args[1] } else
|
;
assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok());
let mut total_temp = 0;
for _ in 0.. 100 {
let string = subscriber.recv_string(0).unwrap().unwrap();
let chks: Vec<i64> = string.split(' ').map(atoi).collect();
let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]);
total_temp += temperature;
}
println!("Average temperature for zipcode '{}' was {}F", filter, (total_temp / 100));
}
|
{ "10001" }
|
conditional_block
|
ttf.rs
|
//! Module for creating text textures.
use std::ffi::CString;
use std::path::Path;
use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888};
use sdl2_sys::surface::SDL_Surface;
use sdl2_sys::surface;
use gl;
use common::color::Color4;
use yaglw::gl_context::GLContext;
use yaglw::texture::Texture2D;
#[allow(non_camel_case_types)]
#[allow(dead_code)]
#[allow(missing_docs)]
pub mod ffi {
extern crate libc;
use sdl2_sys::pixels::SDL_Color;
use sdl2_sys::surface::SDL_Surface;
pub use self::libc::{c_int, c_char, c_void, c_long};
pub type TTF_Font = c_void;
pub type TTF_StyleFlag = c_int;
pub static TTF_STYLE_NORMAL: TTF_StyleFlag = 0x00;
pub static TTF_STYLE_BOLD: TTF_StyleFlag = 0x01;
pub static TTF_STYLE_ITALIC: TTF_StyleFlag = 0x02;
pub static TTF_STYLE_UNDERLINE: c_int = 0x04;
pub static TTF_STYLE_STRIKETHROUGH: c_int = 0x08;
pub type TTF_Hinting = c_int;
pub static TTF_HINTING_NORMAL: TTF_Hinting = 0;
pub static TTF_HINTING_LIGHT: TTF_Hinting = 1;
pub static TTF_HINTING_MONO: TTF_Hinting = 2;
pub static TTF_HINTING_NONE: TTF_Hinting = 3;
#[link(name="SDL2_ttf")]
extern "C" {
pub fn TTF_Init() -> c_int;
pub fn TTF_WasInit() -> c_int;
pub fn TTF_Quit();
pub fn TTF_OpenFont(file: *const c_char, ptsize: c_int) -> *mut TTF_Font;
pub fn TTF_OpenFontIndex(file: *const c_char, ptsize: c_int, index: c_long) -> *mut TTF_Font;
pub fn TTF_CloseFont(font: *mut TTF_Font);
pub fn TTF_GetFontStyle(font: *const TTF_Font) -> TTF_StyleFlag;
pub fn TTF_SetFontStyle(font: *mut TTF_Font, style: TTF_StyleFlag);
pub fn TTF_GetFontOutline(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontOutline(font: *mut TTF_Font, outline: c_int);
pub fn TTF_GetFontHinting(font: *const TTF_Font) -> TTF_Hinting;
pub fn TTF_SetFontHinting(font: *mut TTF_Font, hinting: TTF_Hinting);
pub fn TTF_GetFontKerning(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontKerning(font: *mut TTF_Font, kerning: c_int);
pub fn TTF_FontHeight(font: *const TTF_Font) -> c_int;
pub fn TTF_FontAscent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontDescent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontLineSkip(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaces(font: *const TTF_Font) -> c_long;
pub fn TTF_FontFaceIsFixedWidth(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaceFamilyName(font: *const TTF_Font) -> *const c_char;
pub fn TTF_GlyphIsProvided(font: *const TTF_Font, glyph: u16) -> c_int;
pub fn TTF_GlyphMetrics(font: *const TTF_Font, glyph: u16, minx: *mut c_int, maxx: *mut c_int, miny: *mut c_int, maxy: *mut c_int, advance: *mut c_int) -> c_int;
pub fn TTF_SizeUTF8(font: *mut TTF_Font, text: *const c_char, w: *mut c_int, h: *mut c_int) -> c_int;
pub fn TTF_RenderUTF8_Solid(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Shaded(font: *const TTF_Font, text: *const c_char, fg: SDL_Color, bg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Blended(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
}
}
/// SDL Font datatype.
pub struct Font {
p: *mut ffi::TTF_Font
}
fn ensure_init()
|
impl Font {
#[allow(missing_docs)]
pub fn new(font: &Path, point_size: u32) -> Font {
ensure_init();
let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap();
let ptr = c_path.as_ptr() as *const i8;
let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) };
assert!(!p.is_null());
Font { p: p }
}
/// Color is rgba
pub fn render<'a, 'b:'a>(
&self,
gl: &'a GLContext,
txt: &str,
color: Color4<u8>,
) -> Texture2D<'b> {
let sdl_color = SDL_Color {
r: color.r,
g: color.g,
b: color.b,
a: color.a
};
let surface_ptr = {
let c_str = CString::new(txt.as_bytes()).unwrap();
let ptr = c_str.as_ptr() as *const i8;
unsafe {
ffi::TTF_RenderUTF8_Blended(self.p as *const ffi::c_void, ptr, sdl_color)
}
};
let tex = unsafe {
surface_ptr.as_ref().expect("Cannot render text.")
};
unsafe {
assert_eq!((*tex.format).format, SDL_PIXELFORMAT_ARGB8888);
}
let texture = Texture2D::new(gl);
unsafe {
gl::BindTexture(gl::TEXTURE_2D, texture.handle.gl_id);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, tex.w, tex.h, 0, gl::BGRA, gl::UNSIGNED_INT_8_8_8_8_REV, tex.pixels as *const _);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
surface::SDL_FreeSurface(surface_ptr as *mut SDL_Surface);
}
texture
}
/// Color the text red.
#[allow(dead_code)]
pub fn red<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF))
}
/// dark black #333
#[allow(dead_code)]
pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF))
}
/// light black #555
#[allow(dead_code)]
pub fn light<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x55, 0x55, 0x55, 0xFF))
}
}
impl Drop for Font {
fn drop(&mut self) {
unsafe { ffi::TTF_CloseFont(self.p) }
}
}
//#[test]
//fn load_and_unload() {
// Font::new(&Path::new("fonts/Open_Sans/OpenSans-Regular.ttf"), 12);
//}
|
{
unsafe {
if ffi::TTF_WasInit() == 0 {
assert_eq!(ffi::TTF_Init(), 0);
}
}
}
|
identifier_body
|
ttf.rs
|
//! Module for creating text textures.
use std::ffi::CString;
use std::path::Path;
use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888};
use sdl2_sys::surface::SDL_Surface;
use sdl2_sys::surface;
use gl;
use common::color::Color4;
use yaglw::gl_context::GLContext;
use yaglw::texture::Texture2D;
#[allow(non_camel_case_types)]
#[allow(dead_code)]
#[allow(missing_docs)]
pub mod ffi {
extern crate libc;
use sdl2_sys::pixels::SDL_Color;
use sdl2_sys::surface::SDL_Surface;
pub use self::libc::{c_int, c_char, c_void, c_long};
pub type TTF_Font = c_void;
pub type TTF_StyleFlag = c_int;
pub static TTF_STYLE_NORMAL: TTF_StyleFlag = 0x00;
pub static TTF_STYLE_BOLD: TTF_StyleFlag = 0x01;
pub static TTF_STYLE_ITALIC: TTF_StyleFlag = 0x02;
pub static TTF_STYLE_UNDERLINE: c_int = 0x04;
pub static TTF_STYLE_STRIKETHROUGH: c_int = 0x08;
pub type TTF_Hinting = c_int;
pub static TTF_HINTING_NORMAL: TTF_Hinting = 0;
pub static TTF_HINTING_LIGHT: TTF_Hinting = 1;
pub static TTF_HINTING_MONO: TTF_Hinting = 2;
pub static TTF_HINTING_NONE: TTF_Hinting = 3;
#[link(name="SDL2_ttf")]
extern "C" {
pub fn TTF_Init() -> c_int;
pub fn TTF_WasInit() -> c_int;
pub fn TTF_Quit();
pub fn TTF_OpenFont(file: *const c_char, ptsize: c_int) -> *mut TTF_Font;
pub fn TTF_OpenFontIndex(file: *const c_char, ptsize: c_int, index: c_long) -> *mut TTF_Font;
pub fn TTF_CloseFont(font: *mut TTF_Font);
pub fn TTF_GetFontStyle(font: *const TTF_Font) -> TTF_StyleFlag;
pub fn TTF_SetFontStyle(font: *mut TTF_Font, style: TTF_StyleFlag);
pub fn TTF_GetFontOutline(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontOutline(font: *mut TTF_Font, outline: c_int);
pub fn TTF_GetFontHinting(font: *const TTF_Font) -> TTF_Hinting;
pub fn TTF_SetFontHinting(font: *mut TTF_Font, hinting: TTF_Hinting);
pub fn TTF_GetFontKerning(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontKerning(font: *mut TTF_Font, kerning: c_int);
pub fn TTF_FontHeight(font: *const TTF_Font) -> c_int;
pub fn TTF_FontAscent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontDescent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontLineSkip(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaces(font: *const TTF_Font) -> c_long;
pub fn TTF_FontFaceIsFixedWidth(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaceFamilyName(font: *const TTF_Font) -> *const c_char;
pub fn TTF_GlyphIsProvided(font: *const TTF_Font, glyph: u16) -> c_int;
pub fn TTF_GlyphMetrics(font: *const TTF_Font, glyph: u16, minx: *mut c_int, maxx: *mut c_int, miny: *mut c_int, maxy: *mut c_int, advance: *mut c_int) -> c_int;
pub fn TTF_SizeUTF8(font: *mut TTF_Font, text: *const c_char, w: *mut c_int, h: *mut c_int) -> c_int;
pub fn TTF_RenderUTF8_Solid(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Shaded(font: *const TTF_Font, text: *const c_char, fg: SDL_Color, bg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Blended(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
}
}
/// SDL Font datatype.
pub struct Font {
p: *mut ffi::TTF_Font
}
fn ensure_init() {
unsafe {
if ffi::TTF_WasInit() == 0 {
assert_eq!(ffi::TTF_Init(), 0);
}
}
}
impl Font {
#[allow(missing_docs)]
pub fn new(font: &Path, point_size: u32) -> Font {
ensure_init();
let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap();
let ptr = c_path.as_ptr() as *const i8;
let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) };
assert!(!p.is_null());
Font { p: p }
}
/// Color is rgba
pub fn render<'a, 'b:'a>(
&self,
gl: &'a GLContext,
txt: &str,
color: Color4<u8>,
) -> Texture2D<'b> {
let sdl_color = SDL_Color {
r: color.r,
g: color.g,
b: color.b,
a: color.a
};
let surface_ptr = {
let c_str = CString::new(txt.as_bytes()).unwrap();
let ptr = c_str.as_ptr() as *const i8;
unsafe {
ffi::TTF_RenderUTF8_Blended(self.p as *const ffi::c_void, ptr, sdl_color)
}
};
let tex = unsafe {
surface_ptr.as_ref().expect("Cannot render text.")
};
unsafe {
assert_eq!((*tex.format).format, SDL_PIXELFORMAT_ARGB8888);
}
let texture = Texture2D::new(gl);
unsafe {
gl::BindTexture(gl::TEXTURE_2D, texture.handle.gl_id);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, tex.w, tex.h, 0, gl::BGRA, gl::UNSIGNED_INT_8_8_8_8_REV, tex.pixels as *const _);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
surface::SDL_FreeSurface(surface_ptr as *mut SDL_Surface);
}
texture
}
/// Color the text red.
#[allow(dead_code)]
pub fn red<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF))
}
/// dark black #333
#[allow(dead_code)]
pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF))
}
/// light black #555
#[allow(dead_code)]
pub fn
|
<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x55, 0x55, 0x55, 0xFF))
}
}
impl Drop for Font {
fn drop(&mut self) {
unsafe { ffi::TTF_CloseFont(self.p) }
}
}
//#[test]
//fn load_and_unload() {
// Font::new(&Path::new("fonts/Open_Sans/OpenSans-Regular.ttf"), 12);
//}
|
light
|
identifier_name
|
ttf.rs
|
//! Module for creating text textures.
use std::ffi::CString;
use std::path::Path;
use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888};
use sdl2_sys::surface::SDL_Surface;
use sdl2_sys::surface;
use gl;
use common::color::Color4;
use yaglw::gl_context::GLContext;
use yaglw::texture::Texture2D;
#[allow(non_camel_case_types)]
#[allow(dead_code)]
#[allow(missing_docs)]
pub mod ffi {
extern crate libc;
use sdl2_sys::pixels::SDL_Color;
use sdl2_sys::surface::SDL_Surface;
pub use self::libc::{c_int, c_char, c_void, c_long};
pub type TTF_Font = c_void;
pub type TTF_StyleFlag = c_int;
pub static TTF_STYLE_NORMAL: TTF_StyleFlag = 0x00;
pub static TTF_STYLE_BOLD: TTF_StyleFlag = 0x01;
pub static TTF_STYLE_ITALIC: TTF_StyleFlag = 0x02;
pub static TTF_STYLE_UNDERLINE: c_int = 0x04;
pub static TTF_STYLE_STRIKETHROUGH: c_int = 0x08;
pub type TTF_Hinting = c_int;
pub static TTF_HINTING_NORMAL: TTF_Hinting = 0;
pub static TTF_HINTING_LIGHT: TTF_Hinting = 1;
pub static TTF_HINTING_MONO: TTF_Hinting = 2;
pub static TTF_HINTING_NONE: TTF_Hinting = 3;
#[link(name="SDL2_ttf")]
extern "C" {
pub fn TTF_Init() -> c_int;
pub fn TTF_WasInit() -> c_int;
pub fn TTF_Quit();
pub fn TTF_OpenFont(file: *const c_char, ptsize: c_int) -> *mut TTF_Font;
pub fn TTF_OpenFontIndex(file: *const c_char, ptsize: c_int, index: c_long) -> *mut TTF_Font;
pub fn TTF_CloseFont(font: *mut TTF_Font);
pub fn TTF_GetFontStyle(font: *const TTF_Font) -> TTF_StyleFlag;
pub fn TTF_SetFontStyle(font: *mut TTF_Font, style: TTF_StyleFlag);
pub fn TTF_GetFontOutline(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontOutline(font: *mut TTF_Font, outline: c_int);
pub fn TTF_GetFontHinting(font: *const TTF_Font) -> TTF_Hinting;
pub fn TTF_SetFontHinting(font: *mut TTF_Font, hinting: TTF_Hinting);
pub fn TTF_GetFontKerning(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontKerning(font: *mut TTF_Font, kerning: c_int);
pub fn TTF_FontHeight(font: *const TTF_Font) -> c_int;
pub fn TTF_FontAscent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontDescent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontLineSkip(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaces(font: *const TTF_Font) -> c_long;
pub fn TTF_FontFaceIsFixedWidth(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaceFamilyName(font: *const TTF_Font) -> *const c_char;
pub fn TTF_GlyphIsProvided(font: *const TTF_Font, glyph: u16) -> c_int;
pub fn TTF_GlyphMetrics(font: *const TTF_Font, glyph: u16, minx: *mut c_int, maxx: *mut c_int, miny: *mut c_int, maxy: *mut c_int, advance: *mut c_int) -> c_int;
pub fn TTF_SizeUTF8(font: *mut TTF_Font, text: *const c_char, w: *mut c_int, h: *mut c_int) -> c_int;
pub fn TTF_RenderUTF8_Solid(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Shaded(font: *const TTF_Font, text: *const c_char, fg: SDL_Color, bg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Blended(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
}
}
/// SDL Font datatype.
pub struct Font {
p: *mut ffi::TTF_Font
}
fn ensure_init() {
unsafe {
if ffi::TTF_WasInit() == 0 {
assert_eq!(ffi::TTF_Init(), 0);
}
}
}
impl Font {
#[allow(missing_docs)]
pub fn new(font: &Path, point_size: u32) -> Font {
ensure_init();
let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap();
let ptr = c_path.as_ptr() as *const i8;
let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) };
assert!(!p.is_null());
Font { p: p }
}
/// Color is rgba
pub fn render<'a, 'b:'a>(
&self,
gl: &'a GLContext,
txt: &str,
color: Color4<u8>,
) -> Texture2D<'b> {
let sdl_color = SDL_Color {
r: color.r,
g: color.g,
b: color.b,
a: color.a
};
|
ffi::TTF_RenderUTF8_Blended(self.p as *const ffi::c_void, ptr, sdl_color)
}
};
let tex = unsafe {
surface_ptr.as_ref().expect("Cannot render text.")
};
unsafe {
assert_eq!((*tex.format).format, SDL_PIXELFORMAT_ARGB8888);
}
let texture = Texture2D::new(gl);
unsafe {
gl::BindTexture(gl::TEXTURE_2D, texture.handle.gl_id);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, tex.w, tex.h, 0, gl::BGRA, gl::UNSIGNED_INT_8_8_8_8_REV, tex.pixels as *const _);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
surface::SDL_FreeSurface(surface_ptr as *mut SDL_Surface);
}
texture
}
/// Color the text red.
#[allow(dead_code)]
pub fn red<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF))
}
/// dark black #333
#[allow(dead_code)]
pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF))
}
/// light black #555
#[allow(dead_code)]
pub fn light<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x55, 0x55, 0x55, 0xFF))
}
}
impl Drop for Font {
fn drop(&mut self) {
unsafe { ffi::TTF_CloseFont(self.p) }
}
}
//#[test]
//fn load_and_unload() {
// Font::new(&Path::new("fonts/Open_Sans/OpenSans-Regular.ttf"), 12);
//}
|
let surface_ptr = {
let c_str = CString::new(txt.as_bytes()).unwrap();
let ptr = c_str.as_ptr() as *const i8;
unsafe {
|
random_line_split
|
ttf.rs
|
//! Module for creating text textures.
use std::ffi::CString;
use std::path::Path;
use sdl2_sys::pixels::{SDL_Color,SDL_PIXELFORMAT_ARGB8888};
use sdl2_sys::surface::SDL_Surface;
use sdl2_sys::surface;
use gl;
use common::color::Color4;
use yaglw::gl_context::GLContext;
use yaglw::texture::Texture2D;
#[allow(non_camel_case_types)]
#[allow(dead_code)]
#[allow(missing_docs)]
pub mod ffi {
extern crate libc;
use sdl2_sys::pixels::SDL_Color;
use sdl2_sys::surface::SDL_Surface;
pub use self::libc::{c_int, c_char, c_void, c_long};
pub type TTF_Font = c_void;
pub type TTF_StyleFlag = c_int;
pub static TTF_STYLE_NORMAL: TTF_StyleFlag = 0x00;
pub static TTF_STYLE_BOLD: TTF_StyleFlag = 0x01;
pub static TTF_STYLE_ITALIC: TTF_StyleFlag = 0x02;
pub static TTF_STYLE_UNDERLINE: c_int = 0x04;
pub static TTF_STYLE_STRIKETHROUGH: c_int = 0x08;
pub type TTF_Hinting = c_int;
pub static TTF_HINTING_NORMAL: TTF_Hinting = 0;
pub static TTF_HINTING_LIGHT: TTF_Hinting = 1;
pub static TTF_HINTING_MONO: TTF_Hinting = 2;
pub static TTF_HINTING_NONE: TTF_Hinting = 3;
#[link(name="SDL2_ttf")]
extern "C" {
pub fn TTF_Init() -> c_int;
pub fn TTF_WasInit() -> c_int;
pub fn TTF_Quit();
pub fn TTF_OpenFont(file: *const c_char, ptsize: c_int) -> *mut TTF_Font;
pub fn TTF_OpenFontIndex(file: *const c_char, ptsize: c_int, index: c_long) -> *mut TTF_Font;
pub fn TTF_CloseFont(font: *mut TTF_Font);
pub fn TTF_GetFontStyle(font: *const TTF_Font) -> TTF_StyleFlag;
pub fn TTF_SetFontStyle(font: *mut TTF_Font, style: TTF_StyleFlag);
pub fn TTF_GetFontOutline(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontOutline(font: *mut TTF_Font, outline: c_int);
pub fn TTF_GetFontHinting(font: *const TTF_Font) -> TTF_Hinting;
pub fn TTF_SetFontHinting(font: *mut TTF_Font, hinting: TTF_Hinting);
pub fn TTF_GetFontKerning(font: *const TTF_Font) -> c_int;
pub fn TTF_SetFontKerning(font: *mut TTF_Font, kerning: c_int);
pub fn TTF_FontHeight(font: *const TTF_Font) -> c_int;
pub fn TTF_FontAscent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontDescent(font: *const TTF_Font) -> c_int;
pub fn TTF_FontLineSkip(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaces(font: *const TTF_Font) -> c_long;
pub fn TTF_FontFaceIsFixedWidth(font: *const TTF_Font) -> c_int;
pub fn TTF_FontFaceFamilyName(font: *const TTF_Font) -> *const c_char;
pub fn TTF_GlyphIsProvided(font: *const TTF_Font, glyph: u16) -> c_int;
pub fn TTF_GlyphMetrics(font: *const TTF_Font, glyph: u16, minx: *mut c_int, maxx: *mut c_int, miny: *mut c_int, maxy: *mut c_int, advance: *mut c_int) -> c_int;
pub fn TTF_SizeUTF8(font: *mut TTF_Font, text: *const c_char, w: *mut c_int, h: *mut c_int) -> c_int;
pub fn TTF_RenderUTF8_Solid(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Shaded(font: *const TTF_Font, text: *const c_char, fg: SDL_Color, bg: SDL_Color) -> *mut SDL_Surface;
pub fn TTF_RenderUTF8_Blended(font: *const TTF_Font, text: *const c_char, fg: SDL_Color) -> *mut SDL_Surface;
}
}
/// SDL Font datatype.
pub struct Font {
p: *mut ffi::TTF_Font
}
fn ensure_init() {
unsafe {
if ffi::TTF_WasInit() == 0
|
}
}
impl Font {
#[allow(missing_docs)]
pub fn new(font: &Path, point_size: u32) -> Font {
ensure_init();
let c_path = CString::new(font.to_str().unwrap().as_bytes()).unwrap();
let ptr = c_path.as_ptr() as *const i8;
let p = unsafe { ffi::TTF_OpenFont(ptr, point_size as ffi::c_int) };
assert!(!p.is_null());
Font { p: p }
}
/// Color is rgba
pub fn render<'a, 'b:'a>(
&self,
gl: &'a GLContext,
txt: &str,
color: Color4<u8>,
) -> Texture2D<'b> {
let sdl_color = SDL_Color {
r: color.r,
g: color.g,
b: color.b,
a: color.a
};
let surface_ptr = {
let c_str = CString::new(txt.as_bytes()).unwrap();
let ptr = c_str.as_ptr() as *const i8;
unsafe {
ffi::TTF_RenderUTF8_Blended(self.p as *const ffi::c_void, ptr, sdl_color)
}
};
let tex = unsafe {
surface_ptr.as_ref().expect("Cannot render text.")
};
unsafe {
assert_eq!((*tex.format).format, SDL_PIXELFORMAT_ARGB8888);
}
let texture = Texture2D::new(gl);
unsafe {
gl::BindTexture(gl::TEXTURE_2D, texture.handle.gl_id);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, tex.w, tex.h, 0, gl::BGRA, gl::UNSIGNED_INT_8_8_8_8_REV, tex.pixels as *const _);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
surface::SDL_FreeSurface(surface_ptr as *mut SDL_Surface);
}
texture
}
/// Color the text red.
#[allow(dead_code)]
pub fn red<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0xFF, 0x00, 0x00, 0xFF))
}
/// dark black #333
#[allow(dead_code)]
pub fn dark<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x33, 0x33, 0x33, 0xFF))
}
/// light black #555
#[allow(dead_code)]
pub fn light<'a>(&self, gl: &'a GLContext, txt: &str) -> Texture2D<'a> {
self.render(gl, txt, Color4::of_rgba(0x55, 0x55, 0x55, 0xFF))
}
}
impl Drop for Font {
fn drop(&mut self) {
unsafe { ffi::TTF_CloseFont(self.p) }
}
}
//#[test]
//fn load_and_unload() {
// Font::new(&Path::new("fonts/Open_Sans/OpenSans-Regular.ttf"), 12);
//}
|
{
assert_eq!(ffi::TTF_Init(), 0);
}
|
conditional_block
|
websocket.rs
|
};
use dom::bindings::codegen::UnionTypes::StringOrStringSequence;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString, is_token};
use dom::blob::{Blob, BlobImpl};
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use js::jsapi::JSAutoCompartment;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::MessageData;
use net_traits::request::{RequestInit, RequestMode};
use script_runtime::CommonScriptMsg;
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use servo_url::ServoUrl;
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
use task::{TaskOnce, TaskCanceller};
use task_source::TaskSource;
use task_source::networking::NetworkingTaskSource;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_malloc_size_of = "Defined in std"]
sender: DomRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DomRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<WebSocket> {
reflect_dom_object(Box::new(WebSocket::new_inherited(url)),
global, WebSocketBinding::Wrap)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| {
match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
}
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
let ws = WebSocket::new(global, url_record.clone());
let address = Trusted::new(&*ws);
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(CoreResourceMsg::Fetch(request, channels));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let task_source = global.networking_task_source();
let canceller = global.task_canceller();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source.queue_with_canceller(open_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source.queue_with_canceller(message_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(),
&task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(address.clone(),
&task_source, &canceller, code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask {
address: address,
});
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
.send(CommonScriptMsg::Task(WebSocketEvent, task, Some(pipeline_id)))
.unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let task_source = self.global().networking_task_source();
fail_the_websocket_connection(address, &task_source, &self.global().task_canceller());
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self)
|
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!("MessageReceivedTask::handler({:p}): readyState={:?}", &*ws,
ws.ready_state.get());
// Step 1.
if ws.ready_state.get()!= WebSocketRequestState::Open {
return;
}
// Step 2-5.
let global = ws.global();
// global.get_cx() returns a valid `JSContext` pointer, so this is safe.
unsafe {
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get());
rooted!(in(cx) let mut message = UndefinedValue());
match self.message {
MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()),
MessageData::Binary(data) => {
match ws.binary_type.get() {
BinaryType::Blob => {
let blob = Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned());
blob.to_jsval(cx, message.handle_mut());
}
BinaryType::Arraybuffer => {
rooted!(in(cx) let mut array_buffer = ptr::null_mut());
assert!(ArrayBuffer::create(cx,
CreateWith::Slice(&data),
|
{
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
|
identifier_body
|
websocket.rs
|
};
use dom::bindings::codegen::UnionTypes::StringOrStringSequence;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString, is_token};
use dom::blob::{Blob, BlobImpl};
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use js::jsapi::JSAutoCompartment;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::MessageData;
use net_traits::request::{RequestInit, RequestMode};
use script_runtime::CommonScriptMsg;
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use servo_url::ServoUrl;
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
use task::{TaskOnce, TaskCanceller};
use task_source::TaskSource;
use task_source::networking::NetworkingTaskSource;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_malloc_size_of = "Defined in std"]
sender: DomRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DomRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<WebSocket> {
reflect_dom_object(Box::new(WebSocket::new_inherited(url)),
global, WebSocketBinding::Wrap)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| {
match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
}
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
let ws = WebSocket::new(global, url_record.clone());
let address = Trusted::new(&*ws);
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(CoreResourceMsg::Fetch(request, channels));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let task_source = global.networking_task_source();
let canceller = global.task_canceller();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source.queue_with_canceller(open_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source.queue_with_canceller(message_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(),
&task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(address.clone(),
&task_source, &canceller, code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn
|
(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask {
address: address,
});
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
.send(CommonScriptMsg::Task(WebSocketEvent, task, Some(pipeline_id)))
.unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let task_source = self.global().networking_task_source();
fail_the_websocket_connection(address, &task_source, &self.global().task_canceller());
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self) {
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!("MessageReceivedTask::handler({:p}): readyState={:?}", &*ws,
ws.ready_state.get());
// Step 1.
if ws.ready_state.get()!= WebSocketRequestState::Open {
return;
}
// Step 2-5.
let global = ws.global();
// global.get_cx() returns a valid `JSContext` pointer, so this is safe.
unsafe {
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get());
rooted!(in(cx) let mut message = UndefinedValue());
match self.message {
MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()),
MessageData::Binary(data) => {
match ws.binary_type.get() {
BinaryType::Blob => {
let blob = Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned());
blob.to_jsval(cx, message.handle_mut());
}
BinaryType::Arraybuffer => {
rooted!(in(cx) let mut array_buffer = ptr::null_mut());
assert!(ArrayBuffer::create(cx,
CreateWith::Slice(&data),
|
send_impl
|
identifier_name
|
websocket.rs
|
Methods};
use dom::bindings::codegen::UnionTypes::StringOrStringSequence;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString, is_token};
use dom::blob::{Blob, BlobImpl};
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use js::jsapi::JSAutoCompartment;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::MessageData;
use net_traits::request::{RequestInit, RequestMode};
use script_runtime::CommonScriptMsg;
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use servo_url::ServoUrl;
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
use task::{TaskOnce, TaskCanceller};
use task_source::TaskSource;
use task_source::networking::NetworkingTaskSource;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_malloc_size_of = "Defined in std"]
sender: DomRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DomRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<WebSocket> {
reflect_dom_object(Box::new(WebSocket::new_inherited(url)),
global, WebSocketBinding::Wrap)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| {
match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
}
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
let ws = WebSocket::new(global, url_record.clone());
let address = Trusted::new(&*ws);
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(CoreResourceMsg::Fetch(request, channels));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let task_source = global.networking_task_source();
let canceller = global.task_canceller();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source.queue_with_canceller(open_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source.queue_with_canceller(message_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(),
&task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(address.clone(),
&task_source, &canceller, code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask {
address: address,
});
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
.send(CommonScriptMsg::Task(WebSocketEvent, task, Some(pipeline_id)))
.unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
|
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let task_source = self.global().networking_task_source();
fail_the_websocket_connection(address, &task_source, &self.global().task_canceller());
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self) {
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!("MessageReceivedTask::handler({:p}): readyState={:?}", &*ws,
ws.ready_state.get());
// Step 1.
if ws.ready_state.get()!= WebSocketRequestState::Open {
return;
}
// Step 2-5.
let global = ws.global();
// global.get_cx() returns a valid `JSContext` pointer, so this is safe.
unsafe {
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get());
rooted!(in(cx) let mut message = UndefinedValue());
match self.message {
MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()),
MessageData::Binary(data) => {
match ws.binary_type.get() {
BinaryType::Blob => {
let blob = Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned());
blob.to_jsval(cx, message.handle_mut());
}
BinaryType::Arraybuffer => {
rooted!(in(cx) let mut array_buffer = ptr::null_mut());
assert!(ArrayBuffer::create(cx,
CreateWith::Slice(&data),
|
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
|
random_line_split
|
websocket.rs
|
};
use dom::bindings::codegen::UnionTypes::StringOrStringSequence;
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString, is_token};
use dom::blob::{Blob, BlobImpl};
use dom::closeevent::CloseEvent;
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use js::jsapi::JSAutoCompartment;
use js::jsval::UndefinedValue;
use js::typedarray::{ArrayBuffer, CreateWith};
use net_traits::{CoreResourceMsg, FetchChannels};
use net_traits::{WebSocketDomAction, WebSocketNetworkEvent};
use net_traits::MessageData;
use net_traits::request::{RequestInit, RequestMode};
use script_runtime::CommonScriptMsg;
use script_runtime::ScriptThreadEventCategory::WebSocketEvent;
use servo_url::ServoUrl;
#[allow(unused_imports)] use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::thread;
use task::{TaskOnce, TaskCanceller};
use task_source::TaskSource;
use task_source::networking::NetworkingTaskSource;
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
code: Option<u16>,
reason: String,
) {
let close_task = CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
pub fn fail_the_websocket_connection(
address: Trusted<WebSocket>,
task_source: &NetworkingTaskSource,
canceller: &TaskCanceller,
) {
let close_task = CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
task_source.queue_with_canceller(close_task, &canceller).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: ServoUrl,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_malloc_size_of = "Defined in std"]
sender: DomRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DomRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: ServoUrl) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DomRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DomRefCell::new("".to_owned()),
}
}
fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<WebSocket> {
reflect_dom_object(Box::new(WebSocket::new_inherited(url)),
global, WebSocketBinding::Wrap)
}
/// <https://html.spec.whatwg.org/multipage/#dom-websocket>
pub fn Constructor(global: &GlobalScope,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<DomRoot<WebSocket>> {
// Steps 1-2.
let url_record = ServoUrl::parse(&url).or(Err(Error::Syntax))?;
// Step 3.
match url_record.scheme() {
"ws" | "wss" => {},
_ => return Err(Error::Syntax),
}
// Step 4.
if url_record.fragment().is_some() {
return Err(Error::Syntax);
}
// Step 5.
let protocols = protocols.map_or(vec![], |p| {
match p {
StringOrStringSequence::String(string) => vec![string.into()],
StringOrStringSequence::StringSequence(seq) => {
seq.into_iter().map(String::from).collect()
},
}
});
// Step 6.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
let ws = WebSocket::new(global, url_record.clone());
let address = Trusted::new(&*ws);
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
// Step 8.
let request = RequestInit {
url: url_record,
origin: global.origin().immutable().clone(),
mode: RequestMode::WebSocket { protocols },
..RequestInit::default()
};
let channels = FetchChannels::WebSocket {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(CoreResourceMsg::Fetch(request, channels));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let task_source = global.networking_task_source();
let canceller = global.task_canceller();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use } => {
let open_thread = ConnectionEstablishedTask {
address: address.clone(),
protocol_in_use,
};
task_source.queue_with_canceller(open_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = MessageReceivedTask {
address: address.clone(),
message: message,
};
task_source.queue_with_canceller(message_thread, &canceller).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(address.clone(),
&task_source, &canceller);
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(address.clone(),
&task_source, &canceller, code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = Box::new(BufferedAmountTask {
address: address,
});
let pipeline_id = self.global().pipeline_id();
self.global()
.script_chan()
.send(CommonScriptMsg::Task(WebSocketEvent, task, Some(pipeline_id)))
.unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = self.send_impl(data_byte_len)?;
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_bytes().unwrap_or(vec![]);
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let task_source = self.global().networking_task_source();
fail_the_websocket_connection(address, &task_source, &self.global().task_canceller());
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocol_in_use: Option<String>,
}
impl TaskOnce for ConnectionEstablishedTask {
/// <https://html.spec.whatwg.org/multipage/#feedback-from-the-protocol:concept-websocket-established>
fn run_once(self) {
let ws = self.address.root();
// Step 1.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 2: Extensions.
// TODO: Set extensions to extensions in use.
// Step 3.
if let Some(protocol_name) = self.protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name;
};
// Step 4.
ws.upcast().fire_event(atom!("open"));
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl TaskOnce for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn run_once(self) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl TaskOnce for CloseTask {
fn run_once(self) {
let ws = self.address.root();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_event(atom!("error"));
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(&ws.global(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
code,
reason);
close_event.upcast::<Event>().fire(ws.upcast());
}
}
struct MessageReceivedTask {
address: Trusted<WebSocket>,
message: MessageData,
}
impl TaskOnce for MessageReceivedTask {
#[allow(unsafe_code)]
fn run_once(self) {
let ws = self.address.root();
debug!("MessageReceivedTask::handler({:p}): readyState={:?}", &*ws,
ws.ready_state.get());
// Step 1.
if ws.ready_state.get()!= WebSocketRequestState::Open
|
// Step 2-5.
let global = ws.global();
// global.get_cx() returns a valid `JSContext` pointer, so this is safe.
unsafe {
let cx = global.get_cx();
let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get());
rooted!(in(cx) let mut message = UndefinedValue());
match self.message {
MessageData::Text(text) => text.to_jsval(cx, message.handle_mut()),
MessageData::Binary(data) => {
match ws.binary_type.get() {
BinaryType::Blob => {
let blob = Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned());
blob.to_jsval(cx, message.handle_mut());
}
BinaryType::Arraybuffer => {
rooted!(in(cx) let mut array_buffer = ptr::null_mut());
assert!(ArrayBuffer::create(cx,
CreateWith::Slice(&data),
|
{
return;
}
|
conditional_block
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
use graphql_text_printer::print_fragment;
use graphql_transforms::sort_selections;
use test_schema::TEST_SCHEMA;
pub fn transform_fixture(fixture: &Fixture) -> Result<String, String> {
let file_key = FileKey::new(fixture.file_name);
let ast = parse(fixture.content, file_key).unwrap();
let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap();
let program = Program::from_definitions(&TEST_SCHEMA, ir);
let next_program = sort_selections(&program);
assert_eq!(
next_program.fragments().count(),
|
.map(|def| print_fragment(&TEST_SCHEMA, def))
.collect::<Vec<_>>();
printed.sort();
Ok(printed.join("\n\n"))
}
|
program.fragments().count()
);
let mut printed = next_program
.fragments()
|
random_line_split
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
use graphql_text_printer::print_fragment;
use graphql_transforms::sort_selections;
use test_schema::TEST_SCHEMA;
pub fn transform_fixture(fixture: &Fixture) -> Result<String, String>
|
{
let file_key = FileKey::new(fixture.file_name);
let ast = parse(fixture.content, file_key).unwrap();
let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap();
let program = Program::from_definitions(&TEST_SCHEMA, ir);
let next_program = sort_selections(&program);
assert_eq!(
next_program.fragments().count(),
program.fragments().count()
);
let mut printed = next_program
.fragments()
.map(|def| print_fragment(&TEST_SCHEMA, def))
.collect::<Vec<_>>();
printed.sort();
Ok(printed.join("\n\n"))
}
|
identifier_body
|
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
use graphql_text_printer::print_fragment;
use graphql_transforms::sort_selections;
use test_schema::TEST_SCHEMA;
pub fn
|
(fixture: &Fixture) -> Result<String, String> {
let file_key = FileKey::new(fixture.file_name);
let ast = parse(fixture.content, file_key).unwrap();
let ir = build(&TEST_SCHEMA, &ast.definitions).unwrap();
let program = Program::from_definitions(&TEST_SCHEMA, ir);
let next_program = sort_selections(&program);
assert_eq!(
next_program.fragments().count(),
program.fragments().count()
);
let mut printed = next_program
.fragments()
.map(|def| print_fragment(&TEST_SCHEMA, def))
.collect::<Vec<_>>();
printed.sort();
Ok(printed.join("\n\n"))
}
|
transform_fixture
|
identifier_name
|
11.rs
|
// SPDX-License-Identifier: MIT
use clap::{Arg, App};
static DIRECTIONS : [(i64,i64); 8] = [
(-1,-1), ( 0,-1), ( 1,-1),
(-1, 0), ( 1, 0),
(-1, 1), ( 0, 1), ( 1, 1),
];
#[derive(Clone)]
pub struct Floorplan {
pub map: Vec<Vec<char>>,
}
impl Floorplan {
pub fn
|
() -> Floorplan {
Floorplan { map: Vec::new() }
}
pub fn load(fname: &str) -> Floorplan {
let mut plan = Floorplan::new();
let contents = std::fs::read_to_string(fname)
.unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err));
for line in contents.trim_end_matches('\n').split('\n') {
plan.map.push(line.chars().collect());
}
return plan;
}
pub fn step1(&mut self) -> bool {
let mut add = Vec::new();
let mut rm = Vec::new();
for y in 0..self.map.len() {
for x in 0..self.map[y].len() {
match (self.map[y][x], self.count_neighbors(x, y)) {
('L', 0) => { add.push((x,y)); },
('#', n) if n >= 4 => { rm.push((x,y)); },
_ => { },
}
}
}
if add.is_empty() && rm.is_empty() { return false; }
for (i, j) in add { self.map[j][i] = '#'; }
for (i, j) in rm { self.map[j][i] = 'L'; }
return true;
}
pub fn step2(&mut self) -> bool {
let mut add = Vec::new();
let mut rm = Vec::new();
for y in 0..self.map.len() {
for x in 0..self.map[y].len() {
match (self.map[y][x], self.count_visible(x, y)) {
('L', 0) => { add.push((x,y)); },
('#', n) if n >= 5 => { rm.push((x,y)); },
_ => { },
}
}
}
if add.is_empty() && rm.is_empty() { return false; }
for (i, j) in add { self.map[j][i] = '#'; }
for (i, j) in rm { self.map[j][i] = 'L'; }
return true;
}
#[inline]
pub fn count_neighbors(&self, x: usize, y: usize) -> u8 {
let mut seated = 0;
for (dx, dy) in DIRECTIONS.iter() {
let (x, y) = ((x as i64+dx) as usize, (y as i64+dy) as usize);
if y < self.map.len() {
let row = &self.map[y];
if x < row.len() && '#' == row[x] { seated += 1; }
}
}
return seated;
}
#[inline]
pub fn count_visible(&self, x: usize, y: usize) -> u8 {
let mut seated = 0;
let ymax = self.map.len() as i64;
let xmax = self.map[0].len() as i64;
for (dx, dy) in DIRECTIONS.iter() {
let (mut x, mut y) = (x as i64+dx, y as i64+dy);
while x >= 0 && y >= 0 && x < xmax && y < ymax {
match self.map[y as usize][x as usize] {
'#' => { seated += 1; break; },
'L' => { break; },
_ => { },
}
x += dx; y += dy;
}
}
return seated;
}
#[inline]
pub fn count(&self, ch: &char) -> u64 {
let mut n = 0;
for row in self.map.iter() {
for c in row.iter() {
if c == ch { n += 1; }
}
}
return n;
}
}
impl std::fmt::Display for Floorplan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for row in self.map.iter() {
for c in row.iter() {
write!(f, "{}", c)?;
}
write!(f, "{}", "\n")?;
}
Ok(())
}
}
fn main() {
let matches = App::new("Advent of code 2020, Day 11 Solution")
.arg(Arg::with_name("FILE").help("Input file to process").index(1))
.get_matches();
let fname = matches.value_of("FILE").unwrap_or("11.in");
let mut plan = Floorplan::load(fname);
// println!("{}", plan);
while plan.step1() { }
println!("Part 1: {} occupied seats", plan.count(&'#'));
// println!("{}", plan);
let mut plan = Floorplan::load(fname);
// println!("{}", plan);
while plan.step2() { }
println!("Part 2: {} occupied seats", plan.count(&'#'));
// println!("{}", plan);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
let mut plan = Floorplan::load("11.in");
while plan.step1() { }
assert_eq!(plan.count(&'#'), 2476);
}
#[test]
fn test2() {
let mut plan = Floorplan::load("11.in");
while plan.step2() { }
assert_eq!(plan.count(&'#'), 2257);
}
}
|
new
|
identifier_name
|
11.rs
|
// SPDX-License-Identifier: MIT
use clap::{Arg, App};
static DIRECTIONS : [(i64,i64); 8] = [
(-1,-1), ( 0,-1), ( 1,-1),
(-1, 0), ( 1, 0),
(-1, 1), ( 0, 1), ( 1, 1),
];
#[derive(Clone)]
pub struct Floorplan {
pub map: Vec<Vec<char>>,
}
impl Floorplan {
pub fn new() -> Floorplan {
Floorplan { map: Vec::new() }
}
pub fn load(fname: &str) -> Floorplan {
let mut plan = Floorplan::new();
let contents = std::fs::read_to_string(fname)
.unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err));
for line in contents.trim_end_matches('\n').split('\n') {
plan.map.push(line.chars().collect());
}
return plan;
}
pub fn step1(&mut self) -> bool {
let mut add = Vec::new();
let mut rm = Vec::new();
for y in 0..self.map.len() {
for x in 0..self.map[y].len() {
match (self.map[y][x], self.count_neighbors(x, y)) {
('L', 0) => { add.push((x,y)); },
('#', n) if n >= 4 => { rm.push((x,y)); },
_ => { },
}
}
}
if add.is_empty() && rm.is_empty() { return false; }
for (i, j) in add { self.map[j][i] = '#'; }
for (i, j) in rm { self.map[j][i] = 'L'; }
return true;
}
pub fn step2(&mut self) -> bool {
let mut add = Vec::new();
let mut rm = Vec::new();
for y in 0..self.map.len() {
for x in 0..self.map[y].len() {
match (self.map[y][x], self.count_visible(x, y)) {
('L', 0) => { add.push((x,y)); },
('#', n) if n >= 5 => { rm.push((x,y)); },
_ => { },
}
}
}
if add.is_empty() && rm.is_empty() { return false; }
for (i, j) in add { self.map[j][i] = '#'; }
for (i, j) in rm { self.map[j][i] = 'L'; }
return true;
}
#[inline]
pub fn count_neighbors(&self, x: usize, y: usize) -> u8 {
let mut seated = 0;
for (dx, dy) in DIRECTIONS.iter() {
let (x, y) = ((x as i64+dx) as usize, (y as i64+dy) as usize);
if y < self.map.len() {
let row = &self.map[y];
if x < row.len() && '#' == row[x] { seated += 1; }
}
}
return seated;
}
|
for (dx, dy) in DIRECTIONS.iter() {
let (mut x, mut y) = (x as i64+dx, y as i64+dy);
while x >= 0 && y >= 0 && x < xmax && y < ymax {
match self.map[y as usize][x as usize] {
'#' => { seated += 1; break; },
'L' => { break; },
_ => { },
}
x += dx; y += dy;
}
}
return seated;
}
#[inline]
pub fn count(&self, ch: &char) -> u64 {
let mut n = 0;
for row in self.map.iter() {
for c in row.iter() {
if c == ch { n += 1; }
}
}
return n;
}
}
impl std::fmt::Display for Floorplan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for row in self.map.iter() {
for c in row.iter() {
write!(f, "{}", c)?;
}
write!(f, "{}", "\n")?;
}
Ok(())
}
}
fn main() {
let matches = App::new("Advent of code 2020, Day 11 Solution")
.arg(Arg::with_name("FILE").help("Input file to process").index(1))
.get_matches();
let fname = matches.value_of("FILE").unwrap_or("11.in");
let mut plan = Floorplan::load(fname);
// println!("{}", plan);
while plan.step1() { }
println!("Part 1: {} occupied seats", plan.count(&'#'));
// println!("{}", plan);
let mut plan = Floorplan::load(fname);
// println!("{}", plan);
while plan.step2() { }
println!("Part 2: {} occupied seats", plan.count(&'#'));
// println!("{}", plan);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
let mut plan = Floorplan::load("11.in");
while plan.step1() { }
assert_eq!(plan.count(&'#'), 2476);
}
#[test]
fn test2() {
let mut plan = Floorplan::load("11.in");
while plan.step2() { }
assert_eq!(plan.count(&'#'), 2257);
}
}
|
#[inline]
pub fn count_visible(&self, x: usize, y: usize) -> u8 {
let mut seated = 0;
let ymax = self.map.len() as i64;
let xmax = self.map[0].len() as i64;
|
random_line_split
|
11.rs
|
// SPDX-License-Identifier: MIT
use clap::{Arg, App};
static DIRECTIONS : [(i64,i64); 8] = [
(-1,-1), ( 0,-1), ( 1,-1),
(-1, 0), ( 1, 0),
(-1, 1), ( 0, 1), ( 1, 1),
];
#[derive(Clone)]
pub struct Floorplan {
pub map: Vec<Vec<char>>,
}
impl Floorplan {
pub fn new() -> Floorplan {
Floorplan { map: Vec::new() }
}
pub fn load(fname: &str) -> Floorplan {
let mut plan = Floorplan::new();
let contents = std::fs::read_to_string(fname)
.unwrap_or_else(|err| panic!("Error reading {}: {}", fname, err));
for line in contents.trim_end_matches('\n').split('\n') {
plan.map.push(line.chars().collect());
}
return plan;
}
pub fn step1(&mut self) -> bool {
let mut add = Vec::new();
let mut rm = Vec::new();
for y in 0..self.map.len() {
for x in 0..self.map[y].len() {
match (self.map[y][x], self.count_neighbors(x, y)) {
('L', 0) => { add.push((x,y)); },
('#', n) if n >= 4 => { rm.push((x,y)); },
_ => { },
}
}
}
if add.is_empty() && rm.is_empty() { return false; }
for (i, j) in add { self.map[j][i] = '#'; }
for (i, j) in rm { self.map[j][i] = 'L'; }
return true;
}
pub fn step2(&mut self) -> bool {
let mut add = Vec::new();
let mut rm = Vec::new();
for y in 0..self.map.len() {
for x in 0..self.map[y].len() {
match (self.map[y][x], self.count_visible(x, y)) {
('L', 0) => { add.push((x,y)); },
('#', n) if n >= 5 => { rm.push((x,y)); },
_ => { },
}
}
}
if add.is_empty() && rm.is_empty() { return false; }
for (i, j) in add { self.map[j][i] = '#'; }
for (i, j) in rm { self.map[j][i] = 'L'; }
return true;
}
#[inline]
pub fn count_neighbors(&self, x: usize, y: usize) -> u8 {
let mut seated = 0;
for (dx, dy) in DIRECTIONS.iter() {
let (x, y) = ((x as i64+dx) as usize, (y as i64+dy) as usize);
if y < self.map.len() {
let row = &self.map[y];
if x < row.len() && '#' == row[x] { seated += 1; }
}
}
return seated;
}
#[inline]
pub fn count_visible(&self, x: usize, y: usize) -> u8 {
let mut seated = 0;
let ymax = self.map.len() as i64;
let xmax = self.map[0].len() as i64;
for (dx, dy) in DIRECTIONS.iter() {
let (mut x, mut y) = (x as i64+dx, y as i64+dy);
while x >= 0 && y >= 0 && x < xmax && y < ymax {
match self.map[y as usize][x as usize] {
'#' => { seated += 1; break; },
'L' => { break; },
_ => { },
}
x += dx; y += dy;
}
}
return seated;
}
#[inline]
pub fn count(&self, ch: &char) -> u64 {
let mut n = 0;
for row in self.map.iter() {
for c in row.iter() {
if c == ch { n += 1; }
}
}
return n;
}
}
impl std::fmt::Display for Floorplan {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for row in self.map.iter() {
for c in row.iter() {
write!(f, "{}", c)?;
}
write!(f, "{}", "\n")?;
}
Ok(())
}
}
fn main() {
let matches = App::new("Advent of code 2020, Day 11 Solution")
.arg(Arg::with_name("FILE").help("Input file to process").index(1))
.get_matches();
let fname = matches.value_of("FILE").unwrap_or("11.in");
let mut plan = Floorplan::load(fname);
// println!("{}", plan);
while plan.step1() { }
println!("Part 1: {} occupied seats", plan.count(&'#'));
// println!("{}", plan);
let mut plan = Floorplan::load(fname);
// println!("{}", plan);
while plan.step2() { }
println!("Part 2: {} occupied seats", plan.count(&'#'));
// println!("{}", plan);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1()
|
#[test]
fn test2() {
let mut plan = Floorplan::load("11.in");
while plan.step2() { }
assert_eq!(plan.count(&'#'), 2257);
}
}
|
{
let mut plan = Floorplan::load("11.in");
while plan.step1() { }
assert_eq!(plan.count(&'#'), 2476);
}
|
identifier_body
|
context.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 style is calculated.
#![deny(missing_docs)]
use animation::Animation;
use app_units::Au;
use bloom::StyleBloom;
use data::ElementData;
use dom::{OpaqueNode, TNode, TElement, SendElement};
use error_reporting::ParseErrorReporter;
use euclid::Size2D;
use matching::StyleSharingCandidateCache;
use parking_lot::RwLock;
use selector_parser::PseudoElement;
use selectors::matching::ElementSelectorFlags;
use servo_config::opts;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::ops::Add;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Sender;
use stylist::Stylist;
use thread_state;
use time;
use timer::Timer;
use traversal::DomTraversal;
/// This structure is used to create a local style context from a shared one.
pub struct ThreadLocalStyleContextCreationInfo {
new_animations_sender: Sender<Animation>,
}
impl ThreadLocalStyleContextCreationInfo {
/// Trivially constructs a `ThreadLocalStyleContextCreationInfo`.
pub fn new(animations_sender: Sender<Animation>) -> Self {
ThreadLocalStyleContextCreationInfo {
new_animations_sender: animations_sender,
}
}
}
/// Which quirks mode is this document in.
///
/// See: https://quirks.spec.whatwg.org/
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum QuirksMode {
/// Quirks mode.
Quirks,
/// Limited quirks mode.
LimitedQuirks,
/// No quirks mode.
NoQuirks,
}
/// A shared style context.
///
/// There's exactly one of these during a given restyle traversal, and it's
/// shared among the worker threads.
pub struct SharedStyleContext {
/// The CSS selector stylist.
pub stylist: Arc<Stylist>,
/// The animations that are currently running.
pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
///The CSS error reporter for all CSS loaded in this layout thread
pub error_reporter: Box<ParseErrorReporter>,
/// Data needed to create the thread-local style context from the shared one.
pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>,
/// The current timer for transitions and animations. This is needed to test
/// them.
pub timer: Timer,
/// The QuirksMode state which the document needs to be rendered with
pub quirks_mode: QuirksMode,
}
impl SharedStyleContext {
/// Return a suitable viewport size in order to be used for viewport units.
pub fn viewport_size(&self) -> Size2D<Au> {
self.stylist.device.au_viewport_size()
}
}
/// Information about the current element being processed. We group this together
/// into a single struct within ThreadLocalStyleContext so that we can instantiate
/// and destroy it easily at the beginning and end of element processing.
struct CurrentElementInfo {
/// The element being processed. Currently we use an OpaqueNode since we only
/// use this for identity checks, but we could use SendElement if there were
/// a good reason to.
element: OpaqueNode,
/// Whether the element is being styled for the first time.
is_initial_style: bool,
}
/// Statistics gathered during the traversal. We gather statistics on each thread
/// and then combine them after the threads join via the Add implementation below.
#[derive(Default)]
pub struct TraversalStatistics {
/// The total number of elements traversed.
pub elements_traversed: u32,
/// The number of elements where has_styles() went from false to true.
pub elements_styled: u32,
/// The number of elements for which we performed selector matching.
pub elements_matched: u32,
/// The number of cache hits from the StyleSharingCache.
pub styles_shared: u32,
/// Time spent in the traversal, in milliseconds.
pub traversal_time_ms: f64,
/// Whether this was a parallel traversal.
pub is_parallel: Option<bool>,
}
/// Implementation of Add to aggregate statistics across different threads.
impl<'a> Add for &'a TraversalStatistics {
type Output = TraversalStatistics;
fn add(self, other: Self) -> TraversalStatistics {
debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0,
"traversal_time_ms should be set at the end by the caller");
TraversalStatistics {
elements_traversed: self.elements_traversed + other.elements_traversed,
elements_styled: self.elements_styled + other.elements_styled,
elements_matched: self.elements_matched + other.elements_matched,
styles_shared: self.styles_shared + other.styles_shared,
traversal_time_ms: 0.0,
is_parallel: None,
}
}
}
/// Format the statistics in a way that the performance test harness understands.
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2
impl fmt::Display for TraversalStatistics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time");
try!(writeln!(f, "[PERF] perf block start"));
try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() {
"parallel"
} else {
"sequential"
}));
try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed));
try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled));
try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched));
try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared));
try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms));
writeln!(f, "[PERF] perf block end")
}
}
lazy_static! {
/// Whether to dump style statistics, computed statically. We use an environmental
/// variable so that this is easy to set for Gecko builds, and matches the
/// mechanism we use to dump statistics on the Gecko style system.
static ref DUMP_STYLE_STATISTICS: bool = {
match env::var("DUMP_STYLE_STATISTICS") {
Ok(s) =>!s.is_empty(),
Err(_) => false,
}
};
}
impl TraversalStatistics {
/// Returns whether statistics dumping is enabled.
pub fn should_dump() -> bool {
*DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats
}
/// Computes the traversal time given the start time in seconds.
pub fn finish<E, D>(&mut self, traversal: &D, start: f64)
where E: TElement,
D: DomTraversal<E>,
{
self.is_parallel = Some(traversal.is_parallel());
self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0;
}
}
/// A task to be run in sequential mode on the parent (non-worker) thread. This
/// is used by the style system to queue up work which is not safe to do during
/// the parallel traversal.
pub enum SequentialTask<E: TElement> {
/// Sets selector flags. This is used when we need to set flags on an
/// element that we don't have exclusive access to (i.e. the parent).
SetSelectorFlags(SendElement<E>, ElementSelectorFlags),
/// Marks that we need to create/remove/update CSS animations after the
/// first traversal.
UpdateAnimations(SendElement<E>, Option<PseudoElement>),
}
impl<E: TElement> SequentialTask<E> {
/// Executes this task.
pub fn execute(self) {
use self::SequentialTask::*;
debug_assert!(thread_state::get() == thread_state::LAYOUT);
match self {
SetSelectorFlags(el, flags) => {
unsafe { el.set_selector_flags(flags) };
}
UpdateAnimations(el, pseudo) =>
|
}
}
/// Creates a task to set the selector flags on an element.
pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self {
use self::SequentialTask::*;
SetSelectorFlags(unsafe { SendElement::new(el) }, flags)
}
/// Creates a task to update CSS Animations on a given (pseudo-)element.
pub fn update_animations(el: E, pseudo: Option<PseudoElement>) -> Self {
use self::SequentialTask::*;
UpdateAnimations(unsafe { SendElement::new(el) }, pseudo)
}
}
/// A thread-local style context.
///
/// This context contains data that needs to be used during restyling, but is
/// not required to be unique among worker threads, so we create one per worker
/// thread in order to be able to mutate it without locking.
pub struct ThreadLocalStyleContext<E: TElement> {
/// A cache to share style among siblings.
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>,
/// The bloom filter used to fast-reject selector-matching.
pub bloom_filter: StyleBloom<E>,
/// A channel on which new animations that have been triggered by style
/// recalculation can be sent.
pub new_animations_sender: Sender<Animation>,
/// A set of tasks to be run (on the parent thread) in sequential mode after
/// the rest of the styling is complete. This is useful for infrequently-needed
/// non-threadsafe operations.
pub tasks: Vec<SequentialTask<E>>,
/// Statistics about the traversal.
pub statistics: TraversalStatistics,
/// Information related to the current element, non-None during processing.
current_element_info: Option<CurrentElementInfo>,
}
impl<E: TElement> ThreadLocalStyleContext<E> {
/// Creates a new `ThreadLocalStyleContext` from a shared one.
pub fn new(shared: &SharedStyleContext) -> Self {
ThreadLocalStyleContext {
style_sharing_candidate_cache: StyleSharingCandidateCache::new(),
bloom_filter: StyleBloom::new(),
new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(),
tasks: Vec::new(),
statistics: TraversalStatistics::default(),
current_element_info: None,
}
}
/// Notes when the style system starts traversing an element.
pub fn begin_element(&mut self, element: E, data: &ElementData) {
debug_assert!(self.current_element_info.is_none());
self.current_element_info = Some(CurrentElementInfo {
element: element.as_node().opaque(),
is_initial_style:!data.has_styles(),
});
}
/// Notes when the style system finishes traversing an element.
pub fn end_element(&mut self, element: E) {
debug_assert!(self.current_element_info.is_some());
debug_assert!(self.current_element_info.as_ref().unwrap().element ==
element.as_node().opaque());
self.current_element_info = None;
}
/// Returns true if the current element being traversed is being styled for
/// the first time.
///
/// Panics if called while no element is being traversed.
pub fn is_initial_style(&self) -> bool {
self.current_element_info.as_ref().unwrap().is_initial_style
}
}
impl<E: TElement> Drop for ThreadLocalStyleContext<E> {
fn drop(&mut self) {
debug_assert!(self.current_element_info.is_none());
// Execute any enqueued sequential tasks.
debug_assert!(thread_state::get() == thread_state::LAYOUT);
for task in self.tasks.drain(..) {
task.execute();
}
}
}
/// A `StyleContext` is just a simple container for a immutable reference to a
/// shared style context, and a mutable reference to a local one.
pub struct StyleContext<'a, E: TElement + 'a> {
/// The shared style context reference.
pub shared: &'a SharedStyleContext,
/// The thread-local style context (mutable) reference.
pub thread_local: &'a mut ThreadLocalStyleContext<E>,
}
/// Why we're doing reflow.
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ReflowGoal {
/// We're reflowing in order to send a display list to the screen.
ForDisplay,
/// We're reflowing in order to satisfy a script query. No display list will be created.
ForScriptQuery,
}
|
{
unsafe { el.update_animations(pseudo.as_ref()) };
}
|
conditional_block
|
context.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 style is calculated.
#![deny(missing_docs)]
use animation::Animation;
use app_units::Au;
use bloom::StyleBloom;
use data::ElementData;
use dom::{OpaqueNode, TNode, TElement, SendElement};
use error_reporting::ParseErrorReporter;
use euclid::Size2D;
use matching::StyleSharingCandidateCache;
use parking_lot::RwLock;
use selector_parser::PseudoElement;
use selectors::matching::ElementSelectorFlags;
use servo_config::opts;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::ops::Add;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Sender;
use stylist::Stylist;
use thread_state;
use time;
use timer::Timer;
use traversal::DomTraversal;
/// This structure is used to create a local style context from a shared one.
pub struct ThreadLocalStyleContextCreationInfo {
new_animations_sender: Sender<Animation>,
}
impl ThreadLocalStyleContextCreationInfo {
/// Trivially constructs a `ThreadLocalStyleContextCreationInfo`.
pub fn new(animations_sender: Sender<Animation>) -> Self {
ThreadLocalStyleContextCreationInfo {
new_animations_sender: animations_sender,
}
}
}
/// Which quirks mode is this document in.
///
/// See: https://quirks.spec.whatwg.org/
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum QuirksMode {
/// Quirks mode.
Quirks,
/// Limited quirks mode.
LimitedQuirks,
/// No quirks mode.
NoQuirks,
}
/// A shared style context.
///
/// There's exactly one of these during a given restyle traversal, and it's
/// shared among the worker threads.
pub struct SharedStyleContext {
/// The CSS selector stylist.
pub stylist: Arc<Stylist>,
/// The animations that are currently running.
pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
///The CSS error reporter for all CSS loaded in this layout thread
pub error_reporter: Box<ParseErrorReporter>,
/// Data needed to create the thread-local style context from the shared one.
pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>,
/// The current timer for transitions and animations. This is needed to test
/// them.
pub timer: Timer,
/// The QuirksMode state which the document needs to be rendered with
pub quirks_mode: QuirksMode,
}
impl SharedStyleContext {
/// Return a suitable viewport size in order to be used for viewport units.
pub fn viewport_size(&self) -> Size2D<Au> {
self.stylist.device.au_viewport_size()
}
}
/// Information about the current element being processed. We group this together
/// into a single struct within ThreadLocalStyleContext so that we can instantiate
/// and destroy it easily at the beginning and end of element processing.
struct CurrentElementInfo {
/// The element being processed. Currently we use an OpaqueNode since we only
/// use this for identity checks, but we could use SendElement if there were
/// a good reason to.
element: OpaqueNode,
/// Whether the element is being styled for the first time.
is_initial_style: bool,
}
/// Statistics gathered during the traversal. We gather statistics on each thread
/// and then combine them after the threads join via the Add implementation below.
#[derive(Default)]
pub struct TraversalStatistics {
/// The total number of elements traversed.
pub elements_traversed: u32,
/// The number of elements where has_styles() went from false to true.
pub elements_styled: u32,
/// The number of elements for which we performed selector matching.
pub elements_matched: u32,
/// The number of cache hits from the StyleSharingCache.
pub styles_shared: u32,
/// Time spent in the traversal, in milliseconds.
pub traversal_time_ms: f64,
/// Whether this was a parallel traversal.
pub is_parallel: Option<bool>,
}
/// Implementation of Add to aggregate statistics across different threads.
impl<'a> Add for &'a TraversalStatistics {
type Output = TraversalStatistics;
fn add(self, other: Self) -> TraversalStatistics {
debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0,
"traversal_time_ms should be set at the end by the caller");
TraversalStatistics {
elements_traversed: self.elements_traversed + other.elements_traversed,
elements_styled: self.elements_styled + other.elements_styled,
elements_matched: self.elements_matched + other.elements_matched,
styles_shared: self.styles_shared + other.styles_shared,
traversal_time_ms: 0.0,
is_parallel: None,
}
}
}
/// Format the statistics in a way that the performance test harness understands.
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2
impl fmt::Display for TraversalStatistics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time");
try!(writeln!(f, "[PERF] perf block start"));
try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() {
"parallel"
} else {
"sequential"
}));
try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed));
try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled));
try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched));
try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared));
try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms));
writeln!(f, "[PERF] perf block end")
}
}
lazy_static! {
/// Whether to dump style statistics, computed statically. We use an environmental
/// variable so that this is easy to set for Gecko builds, and matches the
/// mechanism we use to dump statistics on the Gecko style system.
static ref DUMP_STYLE_STATISTICS: bool = {
match env::var("DUMP_STYLE_STATISTICS") {
Ok(s) =>!s.is_empty(),
Err(_) => false,
}
};
}
impl TraversalStatistics {
/// Returns whether statistics dumping is enabled.
pub fn should_dump() -> bool {
*DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats
}
/// Computes the traversal time given the start time in seconds.
pub fn finish<E, D>(&mut self, traversal: &D, start: f64)
where E: TElement,
D: DomTraversal<E>,
{
self.is_parallel = Some(traversal.is_parallel());
self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0;
}
}
/// A task to be run in sequential mode on the parent (non-worker) thread. This
/// is used by the style system to queue up work which is not safe to do during
/// the parallel traversal.
pub enum SequentialTask<E: TElement> {
/// Sets selector flags. This is used when we need to set flags on an
/// element that we don't have exclusive access to (i.e. the parent).
SetSelectorFlags(SendElement<E>, ElementSelectorFlags),
/// Marks that we need to create/remove/update CSS animations after the
/// first traversal.
UpdateAnimations(SendElement<E>, Option<PseudoElement>),
}
impl<E: TElement> SequentialTask<E> {
/// Executes this task.
pub fn execute(self) {
use self::SequentialTask::*;
debug_assert!(thread_state::get() == thread_state::LAYOUT);
match self {
SetSelectorFlags(el, flags) => {
unsafe { el.set_selector_flags(flags) };
}
UpdateAnimations(el, pseudo) => {
unsafe { el.update_animations(pseudo.as_ref()) };
}
}
}
|
SetSelectorFlags(unsafe { SendElement::new(el) }, flags)
}
/// Creates a task to update CSS Animations on a given (pseudo-)element.
pub fn update_animations(el: E, pseudo: Option<PseudoElement>) -> Self {
use self::SequentialTask::*;
UpdateAnimations(unsafe { SendElement::new(el) }, pseudo)
}
}
/// A thread-local style context.
///
/// This context contains data that needs to be used during restyling, but is
/// not required to be unique among worker threads, so we create one per worker
/// thread in order to be able to mutate it without locking.
pub struct ThreadLocalStyleContext<E: TElement> {
/// A cache to share style among siblings.
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>,
/// The bloom filter used to fast-reject selector-matching.
pub bloom_filter: StyleBloom<E>,
/// A channel on which new animations that have been triggered by style
/// recalculation can be sent.
pub new_animations_sender: Sender<Animation>,
/// A set of tasks to be run (on the parent thread) in sequential mode after
/// the rest of the styling is complete. This is useful for infrequently-needed
/// non-threadsafe operations.
pub tasks: Vec<SequentialTask<E>>,
/// Statistics about the traversal.
pub statistics: TraversalStatistics,
/// Information related to the current element, non-None during processing.
current_element_info: Option<CurrentElementInfo>,
}
impl<E: TElement> ThreadLocalStyleContext<E> {
/// Creates a new `ThreadLocalStyleContext` from a shared one.
pub fn new(shared: &SharedStyleContext) -> Self {
ThreadLocalStyleContext {
style_sharing_candidate_cache: StyleSharingCandidateCache::new(),
bloom_filter: StyleBloom::new(),
new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(),
tasks: Vec::new(),
statistics: TraversalStatistics::default(),
current_element_info: None,
}
}
/// Notes when the style system starts traversing an element.
pub fn begin_element(&mut self, element: E, data: &ElementData) {
debug_assert!(self.current_element_info.is_none());
self.current_element_info = Some(CurrentElementInfo {
element: element.as_node().opaque(),
is_initial_style:!data.has_styles(),
});
}
/// Notes when the style system finishes traversing an element.
pub fn end_element(&mut self, element: E) {
debug_assert!(self.current_element_info.is_some());
debug_assert!(self.current_element_info.as_ref().unwrap().element ==
element.as_node().opaque());
self.current_element_info = None;
}
/// Returns true if the current element being traversed is being styled for
/// the first time.
///
/// Panics if called while no element is being traversed.
pub fn is_initial_style(&self) -> bool {
self.current_element_info.as_ref().unwrap().is_initial_style
}
}
impl<E: TElement> Drop for ThreadLocalStyleContext<E> {
fn drop(&mut self) {
debug_assert!(self.current_element_info.is_none());
// Execute any enqueued sequential tasks.
debug_assert!(thread_state::get() == thread_state::LAYOUT);
for task in self.tasks.drain(..) {
task.execute();
}
}
}
/// A `StyleContext` is just a simple container for a immutable reference to a
/// shared style context, and a mutable reference to a local one.
pub struct StyleContext<'a, E: TElement + 'a> {
/// The shared style context reference.
pub shared: &'a SharedStyleContext,
/// The thread-local style context (mutable) reference.
pub thread_local: &'a mut ThreadLocalStyleContext<E>,
}
/// Why we're doing reflow.
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ReflowGoal {
/// We're reflowing in order to send a display list to the screen.
ForDisplay,
/// We're reflowing in order to satisfy a script query. No display list will be created.
ForScriptQuery,
}
|
/// Creates a task to set the selector flags on an element.
pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self {
use self::SequentialTask::*;
|
random_line_split
|
context.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 style is calculated.
#![deny(missing_docs)]
use animation::Animation;
use app_units::Au;
use bloom::StyleBloom;
use data::ElementData;
use dom::{OpaqueNode, TNode, TElement, SendElement};
use error_reporting::ParseErrorReporter;
use euclid::Size2D;
use matching::StyleSharingCandidateCache;
use parking_lot::RwLock;
use selector_parser::PseudoElement;
use selectors::matching::ElementSelectorFlags;
use servo_config::opts;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::ops::Add;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Sender;
use stylist::Stylist;
use thread_state;
use time;
use timer::Timer;
use traversal::DomTraversal;
/// This structure is used to create a local style context from a shared one.
pub struct ThreadLocalStyleContextCreationInfo {
new_animations_sender: Sender<Animation>,
}
impl ThreadLocalStyleContextCreationInfo {
/// Trivially constructs a `ThreadLocalStyleContextCreationInfo`.
pub fn new(animations_sender: Sender<Animation>) -> Self {
ThreadLocalStyleContextCreationInfo {
new_animations_sender: animations_sender,
}
}
}
/// Which quirks mode is this document in.
///
/// See: https://quirks.spec.whatwg.org/
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum QuirksMode {
/// Quirks mode.
Quirks,
/// Limited quirks mode.
LimitedQuirks,
/// No quirks mode.
NoQuirks,
}
/// A shared style context.
///
/// There's exactly one of these during a given restyle traversal, and it's
/// shared among the worker threads.
pub struct SharedStyleContext {
/// The CSS selector stylist.
pub stylist: Arc<Stylist>,
/// The animations that are currently running.
pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
///The CSS error reporter for all CSS loaded in this layout thread
pub error_reporter: Box<ParseErrorReporter>,
/// Data needed to create the thread-local style context from the shared one.
pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>,
/// The current timer for transitions and animations. This is needed to test
/// them.
pub timer: Timer,
/// The QuirksMode state which the document needs to be rendered with
pub quirks_mode: QuirksMode,
}
impl SharedStyleContext {
/// Return a suitable viewport size in order to be used for viewport units.
pub fn viewport_size(&self) -> Size2D<Au> {
self.stylist.device.au_viewport_size()
}
}
/// Information about the current element being processed. We group this together
/// into a single struct within ThreadLocalStyleContext so that we can instantiate
/// and destroy it easily at the beginning and end of element processing.
struct CurrentElementInfo {
/// The element being processed. Currently we use an OpaqueNode since we only
/// use this for identity checks, but we could use SendElement if there were
/// a good reason to.
element: OpaqueNode,
/// Whether the element is being styled for the first time.
is_initial_style: bool,
}
/// Statistics gathered during the traversal. We gather statistics on each thread
/// and then combine them after the threads join via the Add implementation below.
#[derive(Default)]
pub struct
|
{
/// The total number of elements traversed.
pub elements_traversed: u32,
/// The number of elements where has_styles() went from false to true.
pub elements_styled: u32,
/// The number of elements for which we performed selector matching.
pub elements_matched: u32,
/// The number of cache hits from the StyleSharingCache.
pub styles_shared: u32,
/// Time spent in the traversal, in milliseconds.
pub traversal_time_ms: f64,
/// Whether this was a parallel traversal.
pub is_parallel: Option<bool>,
}
/// Implementation of Add to aggregate statistics across different threads.
impl<'a> Add for &'a TraversalStatistics {
type Output = TraversalStatistics;
fn add(self, other: Self) -> TraversalStatistics {
debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0,
"traversal_time_ms should be set at the end by the caller");
TraversalStatistics {
elements_traversed: self.elements_traversed + other.elements_traversed,
elements_styled: self.elements_styled + other.elements_styled,
elements_matched: self.elements_matched + other.elements_matched,
styles_shared: self.styles_shared + other.styles_shared,
traversal_time_ms: 0.0,
is_parallel: None,
}
}
}
/// Format the statistics in a way that the performance test harness understands.
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2
impl fmt::Display for TraversalStatistics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time");
try!(writeln!(f, "[PERF] perf block start"));
try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() {
"parallel"
} else {
"sequential"
}));
try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed));
try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled));
try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched));
try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared));
try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms));
writeln!(f, "[PERF] perf block end")
}
}
lazy_static! {
/// Whether to dump style statistics, computed statically. We use an environmental
/// variable so that this is easy to set for Gecko builds, and matches the
/// mechanism we use to dump statistics on the Gecko style system.
static ref DUMP_STYLE_STATISTICS: bool = {
match env::var("DUMP_STYLE_STATISTICS") {
Ok(s) =>!s.is_empty(),
Err(_) => false,
}
};
}
impl TraversalStatistics {
/// Returns whether statistics dumping is enabled.
pub fn should_dump() -> bool {
*DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats
}
/// Computes the traversal time given the start time in seconds.
pub fn finish<E, D>(&mut self, traversal: &D, start: f64)
where E: TElement,
D: DomTraversal<E>,
{
self.is_parallel = Some(traversal.is_parallel());
self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0;
}
}
/// A task to be run in sequential mode on the parent (non-worker) thread. This
/// is used by the style system to queue up work which is not safe to do during
/// the parallel traversal.
pub enum SequentialTask<E: TElement> {
/// Sets selector flags. This is used when we need to set flags on an
/// element that we don't have exclusive access to (i.e. the parent).
SetSelectorFlags(SendElement<E>, ElementSelectorFlags),
/// Marks that we need to create/remove/update CSS animations after the
/// first traversal.
UpdateAnimations(SendElement<E>, Option<PseudoElement>),
}
impl<E: TElement> SequentialTask<E> {
/// Executes this task.
pub fn execute(self) {
use self::SequentialTask::*;
debug_assert!(thread_state::get() == thread_state::LAYOUT);
match self {
SetSelectorFlags(el, flags) => {
unsafe { el.set_selector_flags(flags) };
}
UpdateAnimations(el, pseudo) => {
unsafe { el.update_animations(pseudo.as_ref()) };
}
}
}
/// Creates a task to set the selector flags on an element.
pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self {
use self::SequentialTask::*;
SetSelectorFlags(unsafe { SendElement::new(el) }, flags)
}
/// Creates a task to update CSS Animations on a given (pseudo-)element.
pub fn update_animations(el: E, pseudo: Option<PseudoElement>) -> Self {
use self::SequentialTask::*;
UpdateAnimations(unsafe { SendElement::new(el) }, pseudo)
}
}
/// A thread-local style context.
///
/// This context contains data that needs to be used during restyling, but is
/// not required to be unique among worker threads, so we create one per worker
/// thread in order to be able to mutate it without locking.
pub struct ThreadLocalStyleContext<E: TElement> {
/// A cache to share style among siblings.
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>,
/// The bloom filter used to fast-reject selector-matching.
pub bloom_filter: StyleBloom<E>,
/// A channel on which new animations that have been triggered by style
/// recalculation can be sent.
pub new_animations_sender: Sender<Animation>,
/// A set of tasks to be run (on the parent thread) in sequential mode after
/// the rest of the styling is complete. This is useful for infrequently-needed
/// non-threadsafe operations.
pub tasks: Vec<SequentialTask<E>>,
/// Statistics about the traversal.
pub statistics: TraversalStatistics,
/// Information related to the current element, non-None during processing.
current_element_info: Option<CurrentElementInfo>,
}
impl<E: TElement> ThreadLocalStyleContext<E> {
/// Creates a new `ThreadLocalStyleContext` from a shared one.
pub fn new(shared: &SharedStyleContext) -> Self {
ThreadLocalStyleContext {
style_sharing_candidate_cache: StyleSharingCandidateCache::new(),
bloom_filter: StyleBloom::new(),
new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(),
tasks: Vec::new(),
statistics: TraversalStatistics::default(),
current_element_info: None,
}
}
/// Notes when the style system starts traversing an element.
pub fn begin_element(&mut self, element: E, data: &ElementData) {
debug_assert!(self.current_element_info.is_none());
self.current_element_info = Some(CurrentElementInfo {
element: element.as_node().opaque(),
is_initial_style:!data.has_styles(),
});
}
/// Notes when the style system finishes traversing an element.
pub fn end_element(&mut self, element: E) {
debug_assert!(self.current_element_info.is_some());
debug_assert!(self.current_element_info.as_ref().unwrap().element ==
element.as_node().opaque());
self.current_element_info = None;
}
/// Returns true if the current element being traversed is being styled for
/// the first time.
///
/// Panics if called while no element is being traversed.
pub fn is_initial_style(&self) -> bool {
self.current_element_info.as_ref().unwrap().is_initial_style
}
}
impl<E: TElement> Drop for ThreadLocalStyleContext<E> {
fn drop(&mut self) {
debug_assert!(self.current_element_info.is_none());
// Execute any enqueued sequential tasks.
debug_assert!(thread_state::get() == thread_state::LAYOUT);
for task in self.tasks.drain(..) {
task.execute();
}
}
}
/// A `StyleContext` is just a simple container for a immutable reference to a
/// shared style context, and a mutable reference to a local one.
pub struct StyleContext<'a, E: TElement + 'a> {
/// The shared style context reference.
pub shared: &'a SharedStyleContext,
/// The thread-local style context (mutable) reference.
pub thread_local: &'a mut ThreadLocalStyleContext<E>,
}
/// Why we're doing reflow.
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ReflowGoal {
/// We're reflowing in order to send a display list to the screen.
ForDisplay,
/// We're reflowing in order to satisfy a script query. No display list will be created.
ForScriptQuery,
}
|
TraversalStatistics
|
identifier_name
|
context.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 style is calculated.
#![deny(missing_docs)]
use animation::Animation;
use app_units::Au;
use bloom::StyleBloom;
use data::ElementData;
use dom::{OpaqueNode, TNode, TElement, SendElement};
use error_reporting::ParseErrorReporter;
use euclid::Size2D;
use matching::StyleSharingCandidateCache;
use parking_lot::RwLock;
use selector_parser::PseudoElement;
use selectors::matching::ElementSelectorFlags;
use servo_config::opts;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::ops::Add;
use std::sync::{Arc, Mutex};
use std::sync::mpsc::Sender;
use stylist::Stylist;
use thread_state;
use time;
use timer::Timer;
use traversal::DomTraversal;
/// This structure is used to create a local style context from a shared one.
pub struct ThreadLocalStyleContextCreationInfo {
new_animations_sender: Sender<Animation>,
}
impl ThreadLocalStyleContextCreationInfo {
/// Trivially constructs a `ThreadLocalStyleContextCreationInfo`.
pub fn new(animations_sender: Sender<Animation>) -> Self {
ThreadLocalStyleContextCreationInfo {
new_animations_sender: animations_sender,
}
}
}
/// Which quirks mode is this document in.
///
/// See: https://quirks.spec.whatwg.org/
#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum QuirksMode {
/// Quirks mode.
Quirks,
/// Limited quirks mode.
LimitedQuirks,
/// No quirks mode.
NoQuirks,
}
/// A shared style context.
///
/// There's exactly one of these during a given restyle traversal, and it's
/// shared among the worker threads.
pub struct SharedStyleContext {
/// The CSS selector stylist.
pub stylist: Arc<Stylist>,
/// The animations that are currently running.
pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
///The CSS error reporter for all CSS loaded in this layout thread
pub error_reporter: Box<ParseErrorReporter>,
/// Data needed to create the thread-local style context from the shared one.
pub local_context_creation_data: Mutex<ThreadLocalStyleContextCreationInfo>,
/// The current timer for transitions and animations. This is needed to test
/// them.
pub timer: Timer,
/// The QuirksMode state which the document needs to be rendered with
pub quirks_mode: QuirksMode,
}
impl SharedStyleContext {
/// Return a suitable viewport size in order to be used for viewport units.
pub fn viewport_size(&self) -> Size2D<Au> {
self.stylist.device.au_viewport_size()
}
}
/// Information about the current element being processed. We group this together
/// into a single struct within ThreadLocalStyleContext so that we can instantiate
/// and destroy it easily at the beginning and end of element processing.
struct CurrentElementInfo {
/// The element being processed. Currently we use an OpaqueNode since we only
/// use this for identity checks, but we could use SendElement if there were
/// a good reason to.
element: OpaqueNode,
/// Whether the element is being styled for the first time.
is_initial_style: bool,
}
/// Statistics gathered during the traversal. We gather statistics on each thread
/// and then combine them after the threads join via the Add implementation below.
#[derive(Default)]
pub struct TraversalStatistics {
/// The total number of elements traversed.
pub elements_traversed: u32,
/// The number of elements where has_styles() went from false to true.
pub elements_styled: u32,
/// The number of elements for which we performed selector matching.
pub elements_matched: u32,
/// The number of cache hits from the StyleSharingCache.
pub styles_shared: u32,
/// Time spent in the traversal, in milliseconds.
pub traversal_time_ms: f64,
/// Whether this was a parallel traversal.
pub is_parallel: Option<bool>,
}
/// Implementation of Add to aggregate statistics across different threads.
impl<'a> Add for &'a TraversalStatistics {
type Output = TraversalStatistics;
fn add(self, other: Self) -> TraversalStatistics {
debug_assert!(self.traversal_time_ms == 0.0 && other.traversal_time_ms == 0.0,
"traversal_time_ms should be set at the end by the caller");
TraversalStatistics {
elements_traversed: self.elements_traversed + other.elements_traversed,
elements_styled: self.elements_styled + other.elements_styled,
elements_matched: self.elements_matched + other.elements_matched,
styles_shared: self.styles_shared + other.styles_shared,
traversal_time_ms: 0.0,
is_parallel: None,
}
}
}
/// Format the statistics in a way that the performance test harness understands.
/// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331856#c2
impl fmt::Display for TraversalStatistics {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
debug_assert!(self.traversal_time_ms!= 0.0, "should have set traversal time");
try!(writeln!(f, "[PERF] perf block start"));
try!(writeln!(f, "[PERF],traversal,{}", if self.is_parallel.unwrap() {
"parallel"
} else {
"sequential"
}));
try!(writeln!(f, "[PERF],elements_traversed,{}", self.elements_traversed));
try!(writeln!(f, "[PERF],elements_styled,{}", self.elements_styled));
try!(writeln!(f, "[PERF],elements_matched,{}", self.elements_matched));
try!(writeln!(f, "[PERF],styles_shared,{}", self.styles_shared));
try!(writeln!(f, "[PERF],traversal_time_ms,{}", self.traversal_time_ms));
writeln!(f, "[PERF] perf block end")
}
}
lazy_static! {
/// Whether to dump style statistics, computed statically. We use an environmental
/// variable so that this is easy to set for Gecko builds, and matches the
/// mechanism we use to dump statistics on the Gecko style system.
static ref DUMP_STYLE_STATISTICS: bool = {
match env::var("DUMP_STYLE_STATISTICS") {
Ok(s) =>!s.is_empty(),
Err(_) => false,
}
};
}
impl TraversalStatistics {
/// Returns whether statistics dumping is enabled.
pub fn should_dump() -> bool {
*DUMP_STYLE_STATISTICS || opts::get().style_sharing_stats
}
/// Computes the traversal time given the start time in seconds.
pub fn finish<E, D>(&mut self, traversal: &D, start: f64)
where E: TElement,
D: DomTraversal<E>,
{
self.is_parallel = Some(traversal.is_parallel());
self.traversal_time_ms = (time::precise_time_s() - start) * 1000.0;
}
}
/// A task to be run in sequential mode on the parent (non-worker) thread. This
/// is used by the style system to queue up work which is not safe to do during
/// the parallel traversal.
pub enum SequentialTask<E: TElement> {
/// Sets selector flags. This is used when we need to set flags on an
/// element that we don't have exclusive access to (i.e. the parent).
SetSelectorFlags(SendElement<E>, ElementSelectorFlags),
/// Marks that we need to create/remove/update CSS animations after the
/// first traversal.
UpdateAnimations(SendElement<E>, Option<PseudoElement>),
}
impl<E: TElement> SequentialTask<E> {
/// Executes this task.
pub fn execute(self) {
use self::SequentialTask::*;
debug_assert!(thread_state::get() == thread_state::LAYOUT);
match self {
SetSelectorFlags(el, flags) => {
unsafe { el.set_selector_flags(flags) };
}
UpdateAnimations(el, pseudo) => {
unsafe { el.update_animations(pseudo.as_ref()) };
}
}
}
/// Creates a task to set the selector flags on an element.
pub fn set_selector_flags(el: E, flags: ElementSelectorFlags) -> Self {
use self::SequentialTask::*;
SetSelectorFlags(unsafe { SendElement::new(el) }, flags)
}
/// Creates a task to update CSS Animations on a given (pseudo-)element.
pub fn update_animations(el: E, pseudo: Option<PseudoElement>) -> Self {
use self::SequentialTask::*;
UpdateAnimations(unsafe { SendElement::new(el) }, pseudo)
}
}
/// A thread-local style context.
///
/// This context contains data that needs to be used during restyling, but is
/// not required to be unique among worker threads, so we create one per worker
/// thread in order to be able to mutate it without locking.
pub struct ThreadLocalStyleContext<E: TElement> {
/// A cache to share style among siblings.
pub style_sharing_candidate_cache: StyleSharingCandidateCache<E>,
/// The bloom filter used to fast-reject selector-matching.
pub bloom_filter: StyleBloom<E>,
/// A channel on which new animations that have been triggered by style
/// recalculation can be sent.
pub new_animations_sender: Sender<Animation>,
/// A set of tasks to be run (on the parent thread) in sequential mode after
/// the rest of the styling is complete. This is useful for infrequently-needed
/// non-threadsafe operations.
pub tasks: Vec<SequentialTask<E>>,
/// Statistics about the traversal.
pub statistics: TraversalStatistics,
/// Information related to the current element, non-None during processing.
current_element_info: Option<CurrentElementInfo>,
}
impl<E: TElement> ThreadLocalStyleContext<E> {
/// Creates a new `ThreadLocalStyleContext` from a shared one.
pub fn new(shared: &SharedStyleContext) -> Self {
ThreadLocalStyleContext {
style_sharing_candidate_cache: StyleSharingCandidateCache::new(),
bloom_filter: StyleBloom::new(),
new_animations_sender: shared.local_context_creation_data.lock().unwrap().new_animations_sender.clone(),
tasks: Vec::new(),
statistics: TraversalStatistics::default(),
current_element_info: None,
}
}
/// Notes when the style system starts traversing an element.
pub fn begin_element(&mut self, element: E, data: &ElementData)
|
/// Notes when the style system finishes traversing an element.
pub fn end_element(&mut self, element: E) {
debug_assert!(self.current_element_info.is_some());
debug_assert!(self.current_element_info.as_ref().unwrap().element ==
element.as_node().opaque());
self.current_element_info = None;
}
/// Returns true if the current element being traversed is being styled for
/// the first time.
///
/// Panics if called while no element is being traversed.
pub fn is_initial_style(&self) -> bool {
self.current_element_info.as_ref().unwrap().is_initial_style
}
}
impl<E: TElement> Drop for ThreadLocalStyleContext<E> {
fn drop(&mut self) {
debug_assert!(self.current_element_info.is_none());
// Execute any enqueued sequential tasks.
debug_assert!(thread_state::get() == thread_state::LAYOUT);
for task in self.tasks.drain(..) {
task.execute();
}
}
}
/// A `StyleContext` is just a simple container for a immutable reference to a
/// shared style context, and a mutable reference to a local one.
pub struct StyleContext<'a, E: TElement + 'a> {
/// The shared style context reference.
pub shared: &'a SharedStyleContext,
/// The thread-local style context (mutable) reference.
pub thread_local: &'a mut ThreadLocalStyleContext<E>,
}
/// Why we're doing reflow.
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ReflowGoal {
/// We're reflowing in order to send a display list to the screen.
ForDisplay,
/// We're reflowing in order to satisfy a script query. No display list will be created.
ForScriptQuery,
}
|
{
debug_assert!(self.current_element_info.is_none());
self.current_element_info = Some(CurrentElementInfo {
element: element.as_node().opaque(),
is_initial_style: !data.has_styles(),
});
}
|
identifier_body
|
mod.rs
|
mod bunser;
mod map;
mod read;
mod reentrant;
mod seq;
mod template;
#[cfg(test)]
mod test;
mod variant;
use std::io;
use std::str;
use serde::de;
use crate::errors::*;
use crate::header::*;
use self::bunser::{Bunser, PduInfo};
use self::read::{DeRead, Reference, SliceRead};
use self::reentrant::ReentrantLimit;
pub struct Deserializer<R> {
bunser: Bunser<R>,
pdu_info: PduInfo,
remaining_depth: ReentrantLimit,
}
macro_rules! make_visit_num {
($fn:ident, $next:ident) => {
#[inline]
fn $fn<V>(&mut self, visitor: V) -> Result<V::Value>
where V: de::Visitor<'de>,
{
visitor.$fn(self.bunser.$next()?)
}
}
}
fn from_trait<'de, R, T>(read: R) -> Result<T>
where
R: DeRead<'de>,
T: de::Deserialize<'de>,
{
let mut d = Deserializer::new(read)?;
let value = de::Deserialize::deserialize(&mut d)?;
// Make sure we saw the expected length.
d.end()?;
Ok(value)
}
pub fn from_slice<'de, T>(slice: &'de [u8]) -> Result<T>
where
T: de::Deserialize<'de>,
{
from_trait(SliceRead::new(slice))
}
pub fn from_reader<R, T>(rdr: R) -> Result<T>
where
R: io::Read,
T: de::DeserializeOwned,
{
from_trait(read::IoRead::new(rdr))
}
impl<'de, R> Deserializer<R>
where
R: DeRead<'de>,
{
pub fn
|
(read: R) -> Result<Self> {
let mut bunser = Bunser::new(read);
let pdu_info = bunser.read_pdu()?;
Ok(Deserializer {
bunser,
pdu_info,
remaining_depth: ReentrantLimit::new(128),
})
}
/// This method must be called after a value has been fully deserialized.
pub fn end(&self) -> Result<()> {
self.bunser.end(&self.pdu_info)
}
#[inline]
pub fn capabilities(&self) -> u32 {
self.pdu_info.bser_capabilities
}
fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_ARRAY => {
let guard = self.remaining_depth.acquire("array")?;
self.bunser.discard();
let nitems = self.bunser.check_next_int()?;
visitor.visit_seq(seq::SeqAccess::new(self, nitems as usize, &guard))
}
BSER_OBJECT => {
let guard = self.remaining_depth.acquire("object")?;
self.bunser.discard();
let nitems = self.bunser.check_next_int()?;
visitor.visit_map(map::MapAccess::new(self, nitems as usize, &guard))
}
BSER_TRUE => self.visit_bool(visitor, true),
BSER_FALSE => self.visit_bool(visitor, false),
BSER_NULL => self.visit_unit(visitor),
BSER_BYTESTRING => self.visit_bytestring(visitor),
BSER_UTF8STRING => self.visit_utf8string(visitor),
BSER_TEMPLATE => {
let guard = self.remaining_depth.acquire("template")?;
self.bunser.discard();
// TODO: handle possible IO interruption better here -- will
// probably need some intermediate states.
let keys = self.template_keys()?;
let nitems = self.bunser.check_next_int()?;
let template = template::Template::new(self, keys, nitems as usize, &guard);
visitor.visit_seq(template)
}
BSER_REAL => self.visit_f64(visitor),
BSER_INT8 => self.visit_i8(visitor),
BSER_INT16 => self.visit_i16(visitor),
BSER_INT32 => self.visit_i32(visitor),
BSER_INT64 => self.visit_i64(visitor),
ch => bail!(ErrorKind::DeInvalidStartByte("next item".into(), ch)),
}
}
make_visit_num!(visit_i8, next_i8);
make_visit_num!(visit_i16, next_i16);
make_visit_num!(visit_i32, next_i32);
make_visit_num!(visit_i64, next_i64);
make_visit_num!(visit_f64, next_f64);
fn template_keys(&mut self) -> Result<Vec<template::Key<'de>>> {
// The list of keys is actually an array, so just use the deserializer
// to process it.
de::Deserialize::deserialize(self)
}
fn visit_bytestring<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
let len = self.bunser.check_next_int()?;
match self.bunser.read_bytes(len)? {
Reference::Borrowed(s) => visitor.visit_borrowed_bytes(s),
Reference::Copied(s) => visitor.visit_bytes(s),
}
}
fn visit_utf8string<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
let len = self.bunser.check_next_int()?;
match self
.bunser
.read_bytes(len)?
.map_result(|x| str::from_utf8(x))?
{
Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
Reference::Copied(s) => visitor.visit_str(s),
}
}
#[inline]
fn visit_bool<V>(&mut self, visitor: V, value: bool) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
visitor.visit_bool(value)
}
#[inline]
fn visit_unit<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
visitor.visit_unit()
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R>
where
R: DeRead<'de>,
{
type Error = Error;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.parse_value(visitor)
}
/// Parse a `null` as a None, and anything else as a `Some(...)`.
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_NULL => {
self.bunser.discard();
visitor.visit_none()
}
_ => visitor.visit_some(self),
}
}
#[inline]
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
// This is e.g. E(T). Ignore the E.
visitor.visit_newtype_struct(self)
}
/// Parse an enum as an object like {key: value}, or a unit variant as just
/// a value.
#[inline]
fn deserialize_enum<V>(
self,
name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_BYTESTRING | BSER_UTF8STRING => {
visitor.visit_enum(variant::UnitVariantAccess::new(self))
}
BSER_OBJECT => {
let guard = self
.remaining_depth
.acquire(format!("object-like enum '{}'", name))?;
self.bunser.discard();
// For enum variants the object must have exactly one entry
// (named the variant, but serde will perform that check).
let nitems = self.bunser.check_next_int()?;
if nitems!= 1 {
return Err(de::Error::invalid_value(
de::Unexpected::Signed(nitems),
&"integer `1`",
));
}
visitor.visit_enum(variant::VariantAccess::new(self, &guard))
}
ch => bail!(ErrorKind::DeInvalidStartByte(
format!("enum '{}'", name),
ch
)),
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf unit unit_struct seq tuple tuple_struct map struct identifier
ignored_any
}
}
|
new
|
identifier_name
|
mod.rs
|
mod bunser;
mod map;
mod read;
mod reentrant;
mod seq;
mod template;
#[cfg(test)]
mod test;
mod variant;
use std::io;
use std::str;
use serde::de;
use crate::errors::*;
use crate::header::*;
use self::bunser::{Bunser, PduInfo};
use self::read::{DeRead, Reference, SliceRead};
use self::reentrant::ReentrantLimit;
pub struct Deserializer<R> {
bunser: Bunser<R>,
pdu_info: PduInfo,
remaining_depth: ReentrantLimit,
}
macro_rules! make_visit_num {
($fn:ident, $next:ident) => {
#[inline]
fn $fn<V>(&mut self, visitor: V) -> Result<V::Value>
where V: de::Visitor<'de>,
{
visitor.$fn(self.bunser.$next()?)
}
}
}
fn from_trait<'de, R, T>(read: R) -> Result<T>
where
R: DeRead<'de>,
T: de::Deserialize<'de>,
{
let mut d = Deserializer::new(read)?;
let value = de::Deserialize::deserialize(&mut d)?;
// Make sure we saw the expected length.
d.end()?;
Ok(value)
}
pub fn from_slice<'de, T>(slice: &'de [u8]) -> Result<T>
where
T: de::Deserialize<'de>,
|
pub fn from_reader<R, T>(rdr: R) -> Result<T>
where
R: io::Read,
T: de::DeserializeOwned,
{
from_trait(read::IoRead::new(rdr))
}
impl<'de, R> Deserializer<R>
where
R: DeRead<'de>,
{
pub fn new(read: R) -> Result<Self> {
let mut bunser = Bunser::new(read);
let pdu_info = bunser.read_pdu()?;
Ok(Deserializer {
bunser,
pdu_info,
remaining_depth: ReentrantLimit::new(128),
})
}
/// This method must be called after a value has been fully deserialized.
pub fn end(&self) -> Result<()> {
self.bunser.end(&self.pdu_info)
}
#[inline]
pub fn capabilities(&self) -> u32 {
self.pdu_info.bser_capabilities
}
fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_ARRAY => {
let guard = self.remaining_depth.acquire("array")?;
self.bunser.discard();
let nitems = self.bunser.check_next_int()?;
visitor.visit_seq(seq::SeqAccess::new(self, nitems as usize, &guard))
}
BSER_OBJECT => {
let guard = self.remaining_depth.acquire("object")?;
self.bunser.discard();
let nitems = self.bunser.check_next_int()?;
visitor.visit_map(map::MapAccess::new(self, nitems as usize, &guard))
}
BSER_TRUE => self.visit_bool(visitor, true),
BSER_FALSE => self.visit_bool(visitor, false),
BSER_NULL => self.visit_unit(visitor),
BSER_BYTESTRING => self.visit_bytestring(visitor),
BSER_UTF8STRING => self.visit_utf8string(visitor),
BSER_TEMPLATE => {
let guard = self.remaining_depth.acquire("template")?;
self.bunser.discard();
// TODO: handle possible IO interruption better here -- will
// probably need some intermediate states.
let keys = self.template_keys()?;
let nitems = self.bunser.check_next_int()?;
let template = template::Template::new(self, keys, nitems as usize, &guard);
visitor.visit_seq(template)
}
BSER_REAL => self.visit_f64(visitor),
BSER_INT8 => self.visit_i8(visitor),
BSER_INT16 => self.visit_i16(visitor),
BSER_INT32 => self.visit_i32(visitor),
BSER_INT64 => self.visit_i64(visitor),
ch => bail!(ErrorKind::DeInvalidStartByte("next item".into(), ch)),
}
}
make_visit_num!(visit_i8, next_i8);
make_visit_num!(visit_i16, next_i16);
make_visit_num!(visit_i32, next_i32);
make_visit_num!(visit_i64, next_i64);
make_visit_num!(visit_f64, next_f64);
fn template_keys(&mut self) -> Result<Vec<template::Key<'de>>> {
// The list of keys is actually an array, so just use the deserializer
// to process it.
de::Deserialize::deserialize(self)
}
fn visit_bytestring<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
let len = self.bunser.check_next_int()?;
match self.bunser.read_bytes(len)? {
Reference::Borrowed(s) => visitor.visit_borrowed_bytes(s),
Reference::Copied(s) => visitor.visit_bytes(s),
}
}
fn visit_utf8string<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
let len = self.bunser.check_next_int()?;
match self
.bunser
.read_bytes(len)?
.map_result(|x| str::from_utf8(x))?
{
Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
Reference::Copied(s) => visitor.visit_str(s),
}
}
#[inline]
fn visit_bool<V>(&mut self, visitor: V, value: bool) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
visitor.visit_bool(value)
}
#[inline]
fn visit_unit<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
visitor.visit_unit()
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R>
where
R: DeRead<'de>,
{
type Error = Error;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.parse_value(visitor)
}
/// Parse a `null` as a None, and anything else as a `Some(...)`.
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_NULL => {
self.bunser.discard();
visitor.visit_none()
}
_ => visitor.visit_some(self),
}
}
#[inline]
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
// This is e.g. E(T). Ignore the E.
visitor.visit_newtype_struct(self)
}
/// Parse an enum as an object like {key: value}, or a unit variant as just
/// a value.
#[inline]
fn deserialize_enum<V>(
self,
name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_BYTESTRING | BSER_UTF8STRING => {
visitor.visit_enum(variant::UnitVariantAccess::new(self))
}
BSER_OBJECT => {
let guard = self
.remaining_depth
.acquire(format!("object-like enum '{}'", name))?;
self.bunser.discard();
// For enum variants the object must have exactly one entry
// (named the variant, but serde will perform that check).
let nitems = self.bunser.check_next_int()?;
if nitems!= 1 {
return Err(de::Error::invalid_value(
de::Unexpected::Signed(nitems),
&"integer `1`",
));
}
visitor.visit_enum(variant::VariantAccess::new(self, &guard))
}
ch => bail!(ErrorKind::DeInvalidStartByte(
format!("enum '{}'", name),
ch
)),
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf unit unit_struct seq tuple tuple_struct map struct identifier
ignored_any
}
}
|
{
from_trait(SliceRead::new(slice))
}
|
identifier_body
|
mod.rs
|
mod bunser;
mod map;
mod read;
mod reentrant;
mod seq;
mod template;
#[cfg(test)]
mod test;
mod variant;
use std::io;
use std::str;
use serde::de;
use crate::errors::*;
use crate::header::*;
use self::bunser::{Bunser, PduInfo};
use self::read::{DeRead, Reference, SliceRead};
use self::reentrant::ReentrantLimit;
pub struct Deserializer<R> {
bunser: Bunser<R>,
pdu_info: PduInfo,
remaining_depth: ReentrantLimit,
}
macro_rules! make_visit_num {
($fn:ident, $next:ident) => {
#[inline]
fn $fn<V>(&mut self, visitor: V) -> Result<V::Value>
where V: de::Visitor<'de>,
{
visitor.$fn(self.bunser.$next()?)
}
}
}
fn from_trait<'de, R, T>(read: R) -> Result<T>
where
R: DeRead<'de>,
T: de::Deserialize<'de>,
{
let mut d = Deserializer::new(read)?;
let value = de::Deserialize::deserialize(&mut d)?;
// Make sure we saw the expected length.
d.end()?;
Ok(value)
}
pub fn from_slice<'de, T>(slice: &'de [u8]) -> Result<T>
where
T: de::Deserialize<'de>,
{
from_trait(SliceRead::new(slice))
}
pub fn from_reader<R, T>(rdr: R) -> Result<T>
where
R: io::Read,
T: de::DeserializeOwned,
{
from_trait(read::IoRead::new(rdr))
}
impl<'de, R> Deserializer<R>
where
R: DeRead<'de>,
{
pub fn new(read: R) -> Result<Self> {
let mut bunser = Bunser::new(read);
let pdu_info = bunser.read_pdu()?;
Ok(Deserializer {
bunser,
|
}
/// This method must be called after a value has been fully deserialized.
pub fn end(&self) -> Result<()> {
self.bunser.end(&self.pdu_info)
}
#[inline]
pub fn capabilities(&self) -> u32 {
self.pdu_info.bser_capabilities
}
fn parse_value<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_ARRAY => {
let guard = self.remaining_depth.acquire("array")?;
self.bunser.discard();
let nitems = self.bunser.check_next_int()?;
visitor.visit_seq(seq::SeqAccess::new(self, nitems as usize, &guard))
}
BSER_OBJECT => {
let guard = self.remaining_depth.acquire("object")?;
self.bunser.discard();
let nitems = self.bunser.check_next_int()?;
visitor.visit_map(map::MapAccess::new(self, nitems as usize, &guard))
}
BSER_TRUE => self.visit_bool(visitor, true),
BSER_FALSE => self.visit_bool(visitor, false),
BSER_NULL => self.visit_unit(visitor),
BSER_BYTESTRING => self.visit_bytestring(visitor),
BSER_UTF8STRING => self.visit_utf8string(visitor),
BSER_TEMPLATE => {
let guard = self.remaining_depth.acquire("template")?;
self.bunser.discard();
// TODO: handle possible IO interruption better here -- will
// probably need some intermediate states.
let keys = self.template_keys()?;
let nitems = self.bunser.check_next_int()?;
let template = template::Template::new(self, keys, nitems as usize, &guard);
visitor.visit_seq(template)
}
BSER_REAL => self.visit_f64(visitor),
BSER_INT8 => self.visit_i8(visitor),
BSER_INT16 => self.visit_i16(visitor),
BSER_INT32 => self.visit_i32(visitor),
BSER_INT64 => self.visit_i64(visitor),
ch => bail!(ErrorKind::DeInvalidStartByte("next item".into(), ch)),
}
}
make_visit_num!(visit_i8, next_i8);
make_visit_num!(visit_i16, next_i16);
make_visit_num!(visit_i32, next_i32);
make_visit_num!(visit_i64, next_i64);
make_visit_num!(visit_f64, next_f64);
fn template_keys(&mut self) -> Result<Vec<template::Key<'de>>> {
// The list of keys is actually an array, so just use the deserializer
// to process it.
de::Deserialize::deserialize(self)
}
fn visit_bytestring<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
let len = self.bunser.check_next_int()?;
match self.bunser.read_bytes(len)? {
Reference::Borrowed(s) => visitor.visit_borrowed_bytes(s),
Reference::Copied(s) => visitor.visit_bytes(s),
}
}
fn visit_utf8string<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
let len = self.bunser.check_next_int()?;
match self
.bunser
.read_bytes(len)?
.map_result(|x| str::from_utf8(x))?
{
Reference::Borrowed(s) => visitor.visit_borrowed_str(s),
Reference::Copied(s) => visitor.visit_str(s),
}
}
#[inline]
fn visit_bool<V>(&mut self, visitor: V, value: bool) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
visitor.visit_bool(value)
}
#[inline]
fn visit_unit<V>(&mut self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.bunser.discard();
visitor.visit_unit()
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut Deserializer<R>
where
R: DeRead<'de>,
{
type Error = Error;
#[inline]
fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
self.parse_value(visitor)
}
/// Parse a `null` as a None, and anything else as a `Some(...)`.
#[inline]
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_NULL => {
self.bunser.discard();
visitor.visit_none()
}
_ => visitor.visit_some(self),
}
}
#[inline]
fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
// This is e.g. E(T). Ignore the E.
visitor.visit_newtype_struct(self)
}
/// Parse an enum as an object like {key: value}, or a unit variant as just
/// a value.
#[inline]
fn deserialize_enum<V>(
self,
name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
where
V: de::Visitor<'de>,
{
match self.bunser.peek()? {
BSER_BYTESTRING | BSER_UTF8STRING => {
visitor.visit_enum(variant::UnitVariantAccess::new(self))
}
BSER_OBJECT => {
let guard = self
.remaining_depth
.acquire(format!("object-like enum '{}'", name))?;
self.bunser.discard();
// For enum variants the object must have exactly one entry
// (named the variant, but serde will perform that check).
let nitems = self.bunser.check_next_int()?;
if nitems!= 1 {
return Err(de::Error::invalid_value(
de::Unexpected::Signed(nitems),
&"integer `1`",
));
}
visitor.visit_enum(variant::VariantAccess::new(self, &guard))
}
ch => bail!(ErrorKind::DeInvalidStartByte(
format!("enum '{}'", name),
ch
)),
}
}
forward_to_deserialize_any! {
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
byte_buf unit unit_struct seq tuple tuple_struct map struct identifier
ignored_any
}
}
|
pdu_info,
remaining_depth: ReentrantLimit::new(128),
})
|
random_line_split
|
shell.rs
|
use std::env;
use std::io::stdin;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
struct Shell {
cmd_prompt: String,
cwd: PathBuf
}
impl Shell {
fn
|
(prompt_str: &str, cwd: PathBuf) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
cwd: cwd
}
}
fn start(&mut self) {
let stdin = stdin();
loop {
println!("{}", self.cmd_prompt);
let mut line = String::new();
stdin.read_line(&mut line).unwrap();
let cmd_line = line.trim().to_owned();
let program = cmd_line.splitn(1,'').nth(0).expect("no program");
match program {
"" => { continue; }
"\u{274c}" => { return; }
_ => { self.cmd(cmd_line.clone()); }
// _ => { println!("You just ran {}", cmd_line) }
}
}
}
fn cmd(&mut self, cmd_line: String) {
let mut arg_vec = Vec::new();
let mut cmd = String::new();
for (index, raw_s) in cmd_line.split("\u{1F345}").enumerate() {
let s = raw_s.trim();
if s == "" { continue; }
if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); }
}
self.run_cmd(cmd, arg_vec);
}
fn run_cmd(&mut self, cmd: String, argv: Vec<String>) {
match &*cmd {
"\u{1F697}" => self.cd(argv),
"\u{1F4CD}" => self.pwd(),
"\u{1F50D}" => self.execute_program("ls".to_string(), argv),
"\u{1F431}" => self.execute_program("cat".to_string(), argv),
"cat" => self.reject("cat"),
"ls" => self.reject("ls"),
"pwd" => self.reject("pwd"),
_ => self.execute_program(cmd, argv)
}
}
fn reject(&mut self, attempted_command: &str) {
println!("Please do not use {}, it is offensive", attempted_command);
}
fn execute_program(&mut self, cmd: String, argv: Vec<String>) {
if self.cmd_exists(&cmd) {
println!("\u{1F3C3} {}", cmd);
let status = Command::new(cmd.clone())
.args(argv)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.current_dir(&self.cwd)
.status()
.expect("Command not found.");
println!("\u{1F6B7} {} \u{27A1} {}", cmd, status);
}
else {
println!("Command {} not found.", cmd);
}
}
fn cd(&mut self, path: Vec<String>) {
if path.len() == 0 {
println!("Please specify a path to \u{1F697} to.");
return;
}
let p = Path::new(&path[0]);
if!p.is_dir() {
println!("\u{1F697} could not find that, \u{1F62D} ")
}
self.cwd = p.to_path_buf();
}
fn pwd(&mut self) {
println!("\u{27A1} {} \u{2B05} \u{1F4CD}", self.cwd.display());
}
fn cmd_exists(&mut self, cmd: &str) -> bool {
let p = Command::new("which")
.arg(cmd.to_owned())
.output()
.expect("failed to execute process");
p.status.success()
}
}
fn main() {
println!("\x1bc");
let path = env::current_dir().unwrap();
Shell::new("\u{1f41a} ", path).start();
}
|
new
|
identifier_name
|
shell.rs
|
use std::env;
use std::io::stdin;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
struct Shell {
cmd_prompt: String,
cwd: PathBuf
}
impl Shell {
fn new(prompt_str: &str, cwd: PathBuf) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
cwd: cwd
}
}
fn start(&mut self) {
let stdin = stdin();
loop {
println!("{}", self.cmd_prompt);
let mut line = String::new();
stdin.read_line(&mut line).unwrap();
let cmd_line = line.trim().to_owned();
let program = cmd_line.splitn(1,'').nth(0).expect("no program");
match program {
"" => { continue; }
"\u{274c}" => { return; }
_ => { self.cmd(cmd_line.clone()); }
// _ => { println!("You just ran {}", cmd_line) }
}
}
}
fn cmd(&mut self, cmd_line: String)
|
fn run_cmd(&mut self, cmd: String, argv: Vec<String>) {
match &*cmd {
"\u{1F697}" => self.cd(argv),
"\u{1F4CD}" => self.pwd(),
"\u{1F50D}" => self.execute_program("ls".to_string(), argv),
"\u{1F431}" => self.execute_program("cat".to_string(), argv),
"cat" => self.reject("cat"),
"ls" => self.reject("ls"),
"pwd" => self.reject("pwd"),
_ => self.execute_program(cmd, argv)
}
}
fn reject(&mut self, attempted_command: &str) {
println!("Please do not use {}, it is offensive", attempted_command);
}
fn execute_program(&mut self, cmd: String, argv: Vec<String>) {
if self.cmd_exists(&cmd) {
println!("\u{1F3C3} {}", cmd);
let status = Command::new(cmd.clone())
.args(argv)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.current_dir(&self.cwd)
.status()
.expect("Command not found.");
println!("\u{1F6B7} {} \u{27A1} {}", cmd, status);
}
else {
println!("Command {} not found.", cmd);
}
}
fn cd(&mut self, path: Vec<String>) {
if path.len() == 0 {
println!("Please specify a path to \u{1F697} to.");
return;
}
let p = Path::new(&path[0]);
if!p.is_dir() {
println!("\u{1F697} could not find that, \u{1F62D} ")
}
self.cwd = p.to_path_buf();
}
fn pwd(&mut self) {
println!("\u{27A1} {} \u{2B05} \u{1F4CD}", self.cwd.display());
}
fn cmd_exists(&mut self, cmd: &str) -> bool {
let p = Command::new("which")
.arg(cmd.to_owned())
.output()
.expect("failed to execute process");
p.status.success()
}
}
fn main() {
println!("\x1bc");
let path = env::current_dir().unwrap();
Shell::new("\u{1f41a} ", path).start();
}
|
{
let mut arg_vec = Vec::new();
let mut cmd = String::new();
for (index, raw_s) in cmd_line.split("\u{1F345}").enumerate() {
let s = raw_s.trim();
if s == "" { continue; }
if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); }
}
self.run_cmd(cmd, arg_vec);
}
|
identifier_body
|
shell.rs
|
use std::env;
use std::io::stdin;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
struct Shell {
cmd_prompt: String,
cwd: PathBuf
}
impl Shell {
fn new(prompt_str: &str, cwd: PathBuf) -> Shell {
Shell {
cmd_prompt: prompt_str.to_owned(),
cwd: cwd
}
}
fn start(&mut self) {
let stdin = stdin();
loop {
println!("{}", self.cmd_prompt);
let mut line = String::new();
stdin.read_line(&mut line).unwrap();
let cmd_line = line.trim().to_owned();
let program = cmd_line.splitn(1,'').nth(0).expect("no program");
match program {
"" => { continue; }
"\u{274c}" => { return; }
_ => { self.cmd(cmd_line.clone()); }
// _ => { println!("You just ran {}", cmd_line) }
}
}
}
fn cmd(&mut self, cmd_line: String) {
let mut arg_vec = Vec::new();
let mut cmd = String::new();
for (index, raw_s) in cmd_line.split("\u{1F345}").enumerate() {
let s = raw_s.trim();
if s == "" { continue; }
if index == 0 { cmd = s.to_owned(); } else { arg_vec.push(s.to_owned()); }
}
self.run_cmd(cmd, arg_vec);
}
fn run_cmd(&mut self, cmd: String, argv: Vec<String>) {
match &*cmd {
"\u{1F697}" => self.cd(argv),
"\u{1F4CD}" => self.pwd(),
"\u{1F50D}" => self.execute_program("ls".to_string(), argv),
"\u{1F431}" => self.execute_program("cat".to_string(), argv),
"cat" => self.reject("cat"),
"ls" => self.reject("ls"),
"pwd" => self.reject("pwd"),
_ => self.execute_program(cmd, argv)
}
}
fn reject(&mut self, attempted_command: &str) {
println!("Please do not use {}, it is offensive", attempted_command);
}
fn execute_program(&mut self, cmd: String, argv: Vec<String>) {
if self.cmd_exists(&cmd) {
println!("\u{1F3C3} {}", cmd);
let status = Command::new(cmd.clone())
.args(argv)
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.current_dir(&self.cwd)
.status()
.expect("Command not found.");
println!("\u{1F6B7} {} \u{27A1} {}", cmd, status);
}
else {
println!("Command {} not found.", cmd);
}
}
fn cd(&mut self, path: Vec<String>) {
if path.len() == 0 {
println!("Please specify a path to \u{1F697} to.");
return;
}
let p = Path::new(&path[0]);
if!p.is_dir() {
println!("\u{1F697} could not find that, \u{1F62D} ")
}
self.cwd = p.to_path_buf();
}
fn pwd(&mut self) {
println!("\u{27A1} {} \u{2B05} \u{1F4CD}", self.cwd.display());
}
fn cmd_exists(&mut self, cmd: &str) -> bool {
let p = Command::new("which")
.arg(cmd.to_owned())
.output()
.expect("failed to execute process");
p.status.success()
}
}
fn main() {
println!("\x1bc");
let path = env::current_dir().unwrap();
|
Shell::new("\u{1f41a} ", path).start();
}
|
random_line_split
|
|
memvis.rs
|
//! Memory visualization
use sdl2;
use sdl2::mouse::MouseButton;
use sdl2::pixels::*;
use sdl2::rect::{Point, Rect};
use sdl2::surface::Surface;
use std::num::Wrapping;
use super::utility::Drawable;
use crate::cpu::constants::CpuState;
use crate::cpu::constants::MemAddr;
use crate::io::constants::*;
//use cpu::memvis::cpuCOLOR_DEPTH;
use crate::cpu::*;
use crate::cpu::memvis::cpumemvis::*;
use crate::disasm;
/// State for the memory visualization system
pub struct MemVisState {
pub mem_val_display_enabled: bool,
// pub texture: sdl2::render::Texture<'a>,
}
impl MemVisState {
pub fn new() -> MemVisState {
MemVisState {
mem_val_display_enabled: true,
//texture: texture,
}
}
/// Returns maybe a memory address given the coordinates of the memory visualization
pub fn screen_coord_to_mem_addr(&self, point: Point) -> Option<MemAddr> {
let x_scaled = point.x() as i32;
let y_scaled = point.y() as i32;
// FIXME this check is not correct
if x_scaled < MEM_DISP_WIDTH && y_scaled < MEM_DISP_HEIGHT + 1 {
Some((x_scaled + y_scaled * MEM_DISP_WIDTH) as u16)
} else {
None
}
}
}
impl Drawable for MemVisState {
fn get_initial_size(&self) -> (u32, u32) {
(MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32)
}
fn draw(&mut self, renderer: &mut sdl2::render::Canvas<Surface>, cpu: &mut Cpu) {
// draw_memory_access(renderer, cpu);
// // FIXME make this take immutable cpu arg
//draw_memory_events(renderer, cpu);
let dst_rect = Rect::new(0, 0, MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32);
if let Some(ref mut logger) = cpu.mem.logger {
let txt_format = sdl2::pixels::PixelFormatEnum::RGBA8888;
let texture_creator = renderer.texture_creator();
let mut texture = texture_creator
.create_texture_streaming(txt_format, MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32)
.unwrap();
let depth = COLOR_DEPTH;
let memvis_pitch = MEM_DISP_WIDTH as usize * depth;
// Draw memory values just by copying them
texture.set_blend_mode(sdl2::render::BlendMode::None);
texture
.update(None, &logger.values[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// Blend access type on top of values
texture.set_blend_mode(sdl2::render::BlendMode::Add);
texture
.update(None, &logger.access_flags[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// FIXME This copy is here to please the Borrow Checker
// God and ideally needs to be removed.
let mut copy = [0; EVENT_LOGGER_TEXTURE_SIZE];
copy[..].clone_from_slice(&logger.access_times[..]);
// Create Surface from values stored in logger
let mut surface = Surface::from_data(
&mut copy,
MEM_DISP_WIDTH as u32,
MEM_DISP_HEIGHT as u32,
memvis_pitch as u32,
txt_format,
)
.unwrap();
// This determines how fast access fades (actual speed
// will depend on the frame rate).
const ACCESS_FADE_ALPHA: u8 = 100;
// Create texture with alpha to do fading effect
let mut blend =
Surface::new(MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32, txt_format).unwrap();
blend
.fill_rect(None, Color::RGBA(0, 0, 0, ACCESS_FADE_ALPHA))
.unwrap();
// Default blend mode works, whatever it is.
blend
.set_blend_mode(sdl2::render::BlendMode::Blend)
.unwrap();
surface
.set_blend_mode(sdl2::render::BlendMode::Add)
.unwrap();
// Do the actual fading effect
blend.blit(None, &mut surface, None).unwrap();
// Store faded values back into logger
// NOTE sizes of textures differ from EVENT_LOGGER_TEXTURE_SIZE
// FIXME there must be a better way to do this without copying
surface.with_lock(|pixels| {
logger.access_times[0..pixels.len()].clone_from_slice(&pixels[0..pixels.len()])
});
let tc = renderer.texture_creator();
// Add access_time texture to make recent accesses brigher
let mut blend_texture = tc.create_texture_from_surface(surface).unwrap();
blend_texture.set_blend_mode(sdl2::render::BlendMode::Add);
renderer.copy(&blend_texture, None, Some(dst_rect)).unwrap();
texture.set_blend_mode(sdl2::render::BlendMode::Add);
texture
.update(None, &logger.access_times[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// Reset blend mode to make other operations faster
renderer.set_blend_mode(sdl2::render::BlendMode::None);
}
// Draw jumps
draw_memory_events(renderer, cpu);
// TODO Draw instant pc, again
}
/// Handle mouse click at pos. Prints some info about clicked
/// address or jumps to it.
fn click(&mut self, button: sdl2::mouse::MouseButton, position: Point, cpu: &mut Cpu) {
match button {
MouseButton::Left => {
if let Some(pc) = self.screen_coord_to_mem_addr(position) {
print_address_info(pc, cpu);
}
}
MouseButton::Right => {
if let Some(pc) = self.screen_coord_to_mem_addr(position) {
info!("Jumping to ${:04X}", pc);
cpu.pc = pc;
if cpu.state!= CpuState::Normal {
info!("CPU state was '{:?}', forcing run.", cpu.state);
cpu.state = CpuState::Normal;
}
}
}
_ => (),
}
}
}
/// Returns point on screen where pixel representing address is drawn.
#[inline]
fn addr_to_point(addr: u16) -> Point {
let x = (addr as i32) % MEM_DISP_WIDTH;
let y = (addr as i32) / MEM_DISP_WIDTH;
Point::new(x as i32, y as i32)
}
/// Clamp i16 value to 0-255 range.
#[inline]
fn clamp_color(v: i16) -> u8 {
if v < 0 {
0
} else if v > 255 {
255
} else {
v as u8
}
}
/// Simple saturating color addition.
#[inline]
fn mix_color(r1: u8, g1: u8, b1: u8, r2: u8, g2: u8, b2: u8) -> (u8, u8, u8) {
// FIXME this is just lazy code
(
clamp_color(r1 as i16 + r2 as i16),
clamp_color(g1 as i16 + g2 as i16),
clamp_color(b1 as i16 + b2 as i16),
)
}
/// Use u8 value to scale other one.
// FIXME this is just lazy code
#[inline]
fn scale_col(scale: u8, color: u8) -> u8 {
clamp_color((color as f32 * (scale as f32 / 255f32)) as i16)
}
/// Draw all memory values represented by pixels. Width is determined
/// by `MEM_DISP_WIDTH`.
pub fn draw_memory_values<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
let mut x = 0;
let mut y = 0;
for i in 0..0xFFFF {
let p = gameboy.mem[i];
use sdl2::pixels::*;
// renderer.set_draw_color(Color::RGB(r,g,b));
// renderer.set_draw_color(Color::RGB(p as u8, p as u8, p as u8));
renderer.set_draw_color(Color::RGB(0 as u8, 0 as u8, p as u8));
// debug!("pixel at {}, {} is {}", x, y, p);
let point = Point::new(x, y);
match renderer.draw_point(point) {
Ok(_) => (),
Err(_) => error!("Could not draw point at {:?}", point),
}
// inc coord
x = (x + 1) % MEM_DISP_WIDTH;
if x == 0 {
y += 1; // % 256; // does this matter?
}
}
// draw current PC
let pc = gameboy.pc;
renderer.set_draw_color(Color::RGB(255, 255, 255));
renderer.draw_point(addr_to_point(pc)).unwrap();
}
/// Draw memory values represented by pixels with colors showing types
/// of access (r/w/x).
pub fn draw_memory_access<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
// TODO replace this function with parts of MemVisState::draw()
let mut x = 0;
let mut y = 0;
let event_logger = match gameboy.mem.logger {
Some(ref logger) => logger,
None => return,
};
for &p in event_logger.values.iter() {
use sdl2::pixels::*;
// let value = gameboy.mem[addr];
let value = p;
// let color = Color::RGB(
// clamp_color(v * ((p & 0x2) >> 1) as i16 + v>>2),
// clamp_color(v * ((p & 0x1) >> 0) as i16 + v>>2),
// clamp_color(v * ((p & 0x4) >> 2) as i16 + v>>2));
let color = if p == 0 {
// Was not accessed
Color::RGB(value, value, value)
} else {
// FIXME The color is determined by value in memory, we
// want to fade max color somewhat (to use bright colors
// by other stuff), but also show at least something
// instead of black.
//
// It will not overflow normally because input value is
// 8bit, and "base" is added to 16bit value, and then the
// value "clamped" so you get "saturating addition(?)"
let base = 32;
let value = (value >> 2) as i16;
let scale = value + base;
Color::RGB(
clamp_color(scale * ((p & FLAG_W) >> 1) as i16),
clamp_color(scale * (p & FLAG_R) as i16),
clamp_color(255 * ((p & FLAG_X) >> 2) as i16),
)
};
renderer.set_draw_color(color);
// let r = event_logger.access_flags[(addr * 4)];
// let g = event_logger.access_flags[(addr * 4) + 1];
// let b = event_logger.access_flags[(addr * 4) + 2];
// renderer.set_draw_color(
// if r == 0 && g == 0 && b == 0 {
// Color::RGB(p,p,p)
// } else {
// Color::RGB(r,g,b)
// });
let point = Point::new(x, y);
match renderer.draw_point(point) {
Ok(_) => (),
Err(_) => error!("Could not draw point at {:?}", point),
}
// inc coord
x = (x + 1) % MEM_DISP_WIDTH;
if x == 0 {
y += 1; // % 256; // does this matter?
}
}
// draw current PC
let pc = gameboy.pc;
renderer.set_draw_color(Color::RGB(255, 0, 255));
renderer.draw_point(addr_to_point(pc)).unwrap();
}
/// Draw all `CpuEvents` that fade depending on current cpu time. When
/// age of event is more that `FADE_DELAY`, event is removed.
pub fn draw_memory_events<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
// TODO: can be used to do partial "smart" redraw, and speed thing up.
// But event logging itself is extremely slow
renderer.set_blend_mode(sdl2::render::BlendMode::Add);
let event_logger = match gameboy.mem.logger {
Some(ref logger) => logger,
None => return,
};
// Draw current events with color determined by age
for entry in &event_logger.events_deq {
let timestamp = entry.timestamp;
let event = &entry.event;
{
let time_diff = (Wrapping(gameboy.cycles) - Wrapping(timestamp)).0;
if time_diff < FADE_DELAY {
let time_norm = 1.0 - (time_diff as f32) / (FADE_DELAY as f32);
let colval = (time_norm * 255.0) as u8;
match *event {
CpuEvent::Read { from: addr } => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(0, colval, 0, scale_col(colval, val / 2), 0, val);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Write { to: addr } => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(colval, 0, 0, 0, scale_col(colval, val / 2), val);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Execute(addr) => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(colval, colval, scale_col(colval, val), 0, 0, 0);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Jump { from: src, to: dst } => {
renderer.set_draw_color(Color::RGBA(200, 200, 0, colval));
let src_point = addr_to_point(src);
let dst_point = addr_to_point(dst);
// Horizontal lines are drawn with scaling but diagonal
// lines ignore it for some reason, which allows us to
// draw lines thinner than memory cells.
if src_point.y()!= dst_point.y() {
match renderer.draw_line(src_point, dst_point) {
Ok(_) => (),
Err(_) => error!(
"Cannot draw line from {:?} to {:?}",
src_point, dst_point
),
}
}
}
_ => (),
}
} else {
break;
}
}
}
renderer.set_blend_mode(sdl2::render::BlendMode::None);
}
fn print_address_info(pc: MemAddr, cpu: &Cpu)
|
{
let pc = pc as usize;
let ref mem = cpu.mem;
let b1 = mem[pc + 1];
let b2 = mem[pc + 2];
let (mnem, _) = disasm::pp_opcode(mem[pc] as u8, b1 as u8, b2 as u8, pc as u16);
let nn = byte_to_u16(b1, b2);
println!(
"${:04X} {:16} 0x{:02X} 0x{:02X} 0x{:02X} 0x{:04X}",
pc, mnem, mem[pc], b1, b2, nn
);
}
|
identifier_body
|
|
memvis.rs
|
//! Memory visualization
use sdl2;
use sdl2::mouse::MouseButton;
use sdl2::pixels::*;
use sdl2::rect::{Point, Rect};
use sdl2::surface::Surface;
use std::num::Wrapping;
use super::utility::Drawable;
use crate::cpu::constants::CpuState;
use crate::cpu::constants::MemAddr;
use crate::io::constants::*;
//use cpu::memvis::cpuCOLOR_DEPTH;
use crate::cpu::*;
use crate::cpu::memvis::cpumemvis::*;
use crate::disasm;
/// State for the memory visualization system
pub struct MemVisState {
pub mem_val_display_enabled: bool,
// pub texture: sdl2::render::Texture<'a>,
}
impl MemVisState {
pub fn new() -> MemVisState {
MemVisState {
mem_val_display_enabled: true,
//texture: texture,
}
}
/// Returns maybe a memory address given the coordinates of the memory visualization
pub fn screen_coord_to_mem_addr(&self, point: Point) -> Option<MemAddr> {
let x_scaled = point.x() as i32;
let y_scaled = point.y() as i32;
// FIXME this check is not correct
if x_scaled < MEM_DISP_WIDTH && y_scaled < MEM_DISP_HEIGHT + 1 {
Some((x_scaled + y_scaled * MEM_DISP_WIDTH) as u16)
} else {
None
}
}
}
impl Drawable for MemVisState {
fn get_initial_size(&self) -> (u32, u32) {
(MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32)
}
fn draw(&mut self, renderer: &mut sdl2::render::Canvas<Surface>, cpu: &mut Cpu) {
// draw_memory_access(renderer, cpu);
// // FIXME make this take immutable cpu arg
//draw_memory_events(renderer, cpu);
let dst_rect = Rect::new(0, 0, MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32);
if let Some(ref mut logger) = cpu.mem.logger {
let txt_format = sdl2::pixels::PixelFormatEnum::RGBA8888;
let texture_creator = renderer.texture_creator();
let mut texture = texture_creator
.create_texture_streaming(txt_format, MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32)
.unwrap();
let depth = COLOR_DEPTH;
let memvis_pitch = MEM_DISP_WIDTH as usize * depth;
// Draw memory values just by copying them
texture.set_blend_mode(sdl2::render::BlendMode::None);
texture
.update(None, &logger.values[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// Blend access type on top of values
texture.set_blend_mode(sdl2::render::BlendMode::Add);
texture
.update(None, &logger.access_flags[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// FIXME This copy is here to please the Borrow Checker
// God and ideally needs to be removed.
let mut copy = [0; EVENT_LOGGER_TEXTURE_SIZE];
copy[..].clone_from_slice(&logger.access_times[..]);
// Create Surface from values stored in logger
let mut surface = Surface::from_data(
&mut copy,
MEM_DISP_WIDTH as u32,
MEM_DISP_HEIGHT as u32,
memvis_pitch as u32,
txt_format,
)
.unwrap();
// This determines how fast access fades (actual speed
// will depend on the frame rate).
const ACCESS_FADE_ALPHA: u8 = 100;
// Create texture with alpha to do fading effect
let mut blend =
Surface::new(MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32, txt_format).unwrap();
blend
.fill_rect(None, Color::RGBA(0, 0, 0, ACCESS_FADE_ALPHA))
.unwrap();
// Default blend mode works, whatever it is.
blend
.set_blend_mode(sdl2::render::BlendMode::Blend)
.unwrap();
surface
.set_blend_mode(sdl2::render::BlendMode::Add)
.unwrap();
// Do the actual fading effect
blend.blit(None, &mut surface, None).unwrap();
// Store faded values back into logger
// NOTE sizes of textures differ from EVENT_LOGGER_TEXTURE_SIZE
// FIXME there must be a better way to do this without copying
surface.with_lock(|pixels| {
logger.access_times[0..pixels.len()].clone_from_slice(&pixels[0..pixels.len()])
});
let tc = renderer.texture_creator();
// Add access_time texture to make recent accesses brigher
let mut blend_texture = tc.create_texture_from_surface(surface).unwrap();
blend_texture.set_blend_mode(sdl2::render::BlendMode::Add);
renderer.copy(&blend_texture, None, Some(dst_rect)).unwrap();
texture.set_blend_mode(sdl2::render::BlendMode::Add);
texture
.update(None, &logger.access_times[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// Reset blend mode to make other operations faster
renderer.set_blend_mode(sdl2::render::BlendMode::None);
}
// Draw jumps
draw_memory_events(renderer, cpu);
// TODO Draw instant pc, again
}
/// Handle mouse click at pos. Prints some info about clicked
/// address or jumps to it.
fn click(&mut self, button: sdl2::mouse::MouseButton, position: Point, cpu: &mut Cpu) {
match button {
MouseButton::Left => {
if let Some(pc) = self.screen_coord_to_mem_addr(position) {
print_address_info(pc, cpu);
}
}
MouseButton::Right => {
if let Some(pc) = self.screen_coord_to_mem_addr(position) {
info!("Jumping to ${:04X}", pc);
cpu.pc = pc;
if cpu.state!= CpuState::Normal {
info!("CPU state was '{:?}', forcing run.", cpu.state);
cpu.state = CpuState::Normal;
}
}
}
_ => (),
}
}
}
/// Returns point on screen where pixel representing address is drawn.
#[inline]
fn addr_to_point(addr: u16) -> Point {
let x = (addr as i32) % MEM_DISP_WIDTH;
let y = (addr as i32) / MEM_DISP_WIDTH;
Point::new(x as i32, y as i32)
}
/// Clamp i16 value to 0-255 range.
#[inline]
fn clamp_color(v: i16) -> u8 {
if v < 0 {
0
} else if v > 255 {
255
} else {
v as u8
}
}
/// Simple saturating color addition.
#[inline]
fn mix_color(r1: u8, g1: u8, b1: u8, r2: u8, g2: u8, b2: u8) -> (u8, u8, u8) {
// FIXME this is just lazy code
(
clamp_color(r1 as i16 + r2 as i16),
clamp_color(g1 as i16 + g2 as i16),
clamp_color(b1 as i16 + b2 as i16),
)
}
/// Use u8 value to scale other one.
// FIXME this is just lazy code
#[inline]
fn scale_col(scale: u8, color: u8) -> u8 {
clamp_color((color as f32 * (scale as f32 / 255f32)) as i16)
}
/// Draw all memory values represented by pixels. Width is determined
/// by `MEM_DISP_WIDTH`.
pub fn draw_memory_values<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
let mut x = 0;
let mut y = 0;
for i in 0..0xFFFF {
let p = gameboy.mem[i];
use sdl2::pixels::*;
// renderer.set_draw_color(Color::RGB(r,g,b));
// renderer.set_draw_color(Color::RGB(p as u8, p as u8, p as u8));
renderer.set_draw_color(Color::RGB(0 as u8, 0 as u8, p as u8));
// debug!("pixel at {}, {} is {}", x, y, p);
let point = Point::new(x, y);
match renderer.draw_point(point) {
Ok(_) => (),
Err(_) => error!("Could not draw point at {:?}", point),
}
// inc coord
x = (x + 1) % MEM_DISP_WIDTH;
if x == 0 {
y += 1; // % 256; // does this matter?
}
}
// draw current PC
let pc = gameboy.pc;
renderer.set_draw_color(Color::RGB(255, 255, 255));
renderer.draw_point(addr_to_point(pc)).unwrap();
}
/// Draw memory values represented by pixels with colors showing types
/// of access (r/w/x).
pub fn draw_memory_access<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
// TODO replace this function with parts of MemVisState::draw()
let mut x = 0;
let mut y = 0;
let event_logger = match gameboy.mem.logger {
Some(ref logger) => logger,
None => return,
};
for &p in event_logger.values.iter() {
use sdl2::pixels::*;
// let value = gameboy.mem[addr];
let value = p;
// let color = Color::RGB(
// clamp_color(v * ((p & 0x2) >> 1) as i16 + v>>2),
// clamp_color(v * ((p & 0x1) >> 0) as i16 + v>>2),
// clamp_color(v * ((p & 0x4) >> 2) as i16 + v>>2));
let color = if p == 0 {
// Was not accessed
Color::RGB(value, value, value)
} else {
// FIXME The color is determined by value in memory, we
// want to fade max color somewhat (to use bright colors
// by other stuff), but also show at least something
// instead of black.
//
// It will not overflow normally because input value is
// 8bit, and "base" is added to 16bit value, and then the
// value "clamped" so you get "saturating addition(?)"
let base = 32;
let value = (value >> 2) as i16;
let scale = value + base;
Color::RGB(
clamp_color(scale * ((p & FLAG_W) >> 1) as i16),
clamp_color(scale * (p & FLAG_R) as i16),
clamp_color(255 * ((p & FLAG_X) >> 2) as i16),
)
};
renderer.set_draw_color(color);
// let r = event_logger.access_flags[(addr * 4)];
// let g = event_logger.access_flags[(addr * 4) + 1];
// let b = event_logger.access_flags[(addr * 4) + 2];
// renderer.set_draw_color(
// if r == 0 && g == 0 && b == 0 {
// Color::RGB(p,p,p)
// } else {
// Color::RGB(r,g,b)
// });
let point = Point::new(x, y);
match renderer.draw_point(point) {
Ok(_) => (),
Err(_) => error!("Could not draw point at {:?}", point),
}
// inc coord
x = (x + 1) % MEM_DISP_WIDTH;
if x == 0 {
y += 1; // % 256; // does this matter?
}
}
// draw current PC
let pc = gameboy.pc;
renderer.set_draw_color(Color::RGB(255, 0, 255));
renderer.draw_point(addr_to_point(pc)).unwrap();
}
/// Draw all `CpuEvents` that fade depending on current cpu time. When
/// age of event is more that `FADE_DELAY`, event is removed.
pub fn draw_memory_events<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
// TODO: can be used to do partial "smart" redraw, and speed thing up.
// But event logging itself is extremely slow
renderer.set_blend_mode(sdl2::render::BlendMode::Add);
let event_logger = match gameboy.mem.logger {
Some(ref logger) => logger,
None => return,
};
// Draw current events with color determined by age
for entry in &event_logger.events_deq {
let timestamp = entry.timestamp;
let event = &entry.event;
{
let time_diff = (Wrapping(gameboy.cycles) - Wrapping(timestamp)).0;
if time_diff < FADE_DELAY {
let time_norm = 1.0 - (time_diff as f32) / (FADE_DELAY as f32);
let colval = (time_norm * 255.0) as u8;
match *event {
CpuEvent::Read { from: addr } => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(0, colval, 0, scale_col(colval, val / 2), 0, val);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Write { to: addr } => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(colval, 0, 0, 0, scale_col(colval, val / 2), val);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Execute(addr) => {
let val = gameboy.mem[addr as usize] as u8;
|
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Jump { from: src, to: dst } => {
renderer.set_draw_color(Color::RGBA(200, 200, 0, colval));
let src_point = addr_to_point(src);
let dst_point = addr_to_point(dst);
// Horizontal lines are drawn with scaling but diagonal
// lines ignore it for some reason, which allows us to
// draw lines thinner than memory cells.
if src_point.y()!= dst_point.y() {
match renderer.draw_line(src_point, dst_point) {
Ok(_) => (),
Err(_) => error!(
"Cannot draw line from {:?} to {:?}",
src_point, dst_point
),
}
}
}
_ => (),
}
} else {
break;
}
}
}
renderer.set_blend_mode(sdl2::render::BlendMode::None);
}
fn print_address_info(pc: MemAddr, cpu: &Cpu) {
let pc = pc as usize;
let ref mem = cpu.mem;
let b1 = mem[pc + 1];
let b2 = mem[pc + 2];
let (mnem, _) = disasm::pp_opcode(mem[pc] as u8, b1 as u8, b2 as u8, pc as u16);
let nn = byte_to_u16(b1, b2);
println!(
"${:04X} {:16} 0x{:02X} 0x{:02X} 0x{:02X} 0x{:04X}",
pc, mnem, mem[pc], b1, b2, nn
);
}
|
let (r, g, b) = mix_color(colval, colval, scale_col(colval, val), 0, 0, 0);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
|
random_line_split
|
memvis.rs
|
//! Memory visualization
use sdl2;
use sdl2::mouse::MouseButton;
use sdl2::pixels::*;
use sdl2::rect::{Point, Rect};
use sdl2::surface::Surface;
use std::num::Wrapping;
use super::utility::Drawable;
use crate::cpu::constants::CpuState;
use crate::cpu::constants::MemAddr;
use crate::io::constants::*;
//use cpu::memvis::cpuCOLOR_DEPTH;
use crate::cpu::*;
use crate::cpu::memvis::cpumemvis::*;
use crate::disasm;
/// State for the memory visualization system
pub struct MemVisState {
pub mem_val_display_enabled: bool,
// pub texture: sdl2::render::Texture<'a>,
}
impl MemVisState {
pub fn new() -> MemVisState {
MemVisState {
mem_val_display_enabled: true,
//texture: texture,
}
}
/// Returns maybe a memory address given the coordinates of the memory visualization
pub fn screen_coord_to_mem_addr(&self, point: Point) -> Option<MemAddr> {
let x_scaled = point.x() as i32;
let y_scaled = point.y() as i32;
// FIXME this check is not correct
if x_scaled < MEM_DISP_WIDTH && y_scaled < MEM_DISP_HEIGHT + 1 {
Some((x_scaled + y_scaled * MEM_DISP_WIDTH) as u16)
} else {
None
}
}
}
impl Drawable for MemVisState {
fn get_initial_size(&self) -> (u32, u32) {
(MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32)
}
fn draw(&mut self, renderer: &mut sdl2::render::Canvas<Surface>, cpu: &mut Cpu) {
// draw_memory_access(renderer, cpu);
// // FIXME make this take immutable cpu arg
//draw_memory_events(renderer, cpu);
let dst_rect = Rect::new(0, 0, MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32);
if let Some(ref mut logger) = cpu.mem.logger {
let txt_format = sdl2::pixels::PixelFormatEnum::RGBA8888;
let texture_creator = renderer.texture_creator();
let mut texture = texture_creator
.create_texture_streaming(txt_format, MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32)
.unwrap();
let depth = COLOR_DEPTH;
let memvis_pitch = MEM_DISP_WIDTH as usize * depth;
// Draw memory values just by copying them
texture.set_blend_mode(sdl2::render::BlendMode::None);
texture
.update(None, &logger.values[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// Blend access type on top of values
texture.set_blend_mode(sdl2::render::BlendMode::Add);
texture
.update(None, &logger.access_flags[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// FIXME This copy is here to please the Borrow Checker
// God and ideally needs to be removed.
let mut copy = [0; EVENT_LOGGER_TEXTURE_SIZE];
copy[..].clone_from_slice(&logger.access_times[..]);
// Create Surface from values stored in logger
let mut surface = Surface::from_data(
&mut copy,
MEM_DISP_WIDTH as u32,
MEM_DISP_HEIGHT as u32,
memvis_pitch as u32,
txt_format,
)
.unwrap();
// This determines how fast access fades (actual speed
// will depend on the frame rate).
const ACCESS_FADE_ALPHA: u8 = 100;
// Create texture with alpha to do fading effect
let mut blend =
Surface::new(MEM_DISP_WIDTH as u32, MEM_DISP_HEIGHT as u32, txt_format).unwrap();
blend
.fill_rect(None, Color::RGBA(0, 0, 0, ACCESS_FADE_ALPHA))
.unwrap();
// Default blend mode works, whatever it is.
blend
.set_blend_mode(sdl2::render::BlendMode::Blend)
.unwrap();
surface
.set_blend_mode(sdl2::render::BlendMode::Add)
.unwrap();
// Do the actual fading effect
blend.blit(None, &mut surface, None).unwrap();
// Store faded values back into logger
// NOTE sizes of textures differ from EVENT_LOGGER_TEXTURE_SIZE
// FIXME there must be a better way to do this without copying
surface.with_lock(|pixels| {
logger.access_times[0..pixels.len()].clone_from_slice(&pixels[0..pixels.len()])
});
let tc = renderer.texture_creator();
// Add access_time texture to make recent accesses brigher
let mut blend_texture = tc.create_texture_from_surface(surface).unwrap();
blend_texture.set_blend_mode(sdl2::render::BlendMode::Add);
renderer.copy(&blend_texture, None, Some(dst_rect)).unwrap();
texture.set_blend_mode(sdl2::render::BlendMode::Add);
texture
.update(None, &logger.access_times[..], memvis_pitch)
.unwrap();
renderer.copy(&texture, None, Some(dst_rect)).unwrap();
// Reset blend mode to make other operations faster
renderer.set_blend_mode(sdl2::render::BlendMode::None);
}
// Draw jumps
draw_memory_events(renderer, cpu);
// TODO Draw instant pc, again
}
/// Handle mouse click at pos. Prints some info about clicked
/// address or jumps to it.
fn click(&mut self, button: sdl2::mouse::MouseButton, position: Point, cpu: &mut Cpu) {
match button {
MouseButton::Left => {
if let Some(pc) = self.screen_coord_to_mem_addr(position) {
print_address_info(pc, cpu);
}
}
MouseButton::Right => {
if let Some(pc) = self.screen_coord_to_mem_addr(position) {
info!("Jumping to ${:04X}", pc);
cpu.pc = pc;
if cpu.state!= CpuState::Normal {
info!("CPU state was '{:?}', forcing run.", cpu.state);
cpu.state = CpuState::Normal;
}
}
}
_ => (),
}
}
}
/// Returns point on screen where pixel representing address is drawn.
#[inline]
fn addr_to_point(addr: u16) -> Point {
let x = (addr as i32) % MEM_DISP_WIDTH;
let y = (addr as i32) / MEM_DISP_WIDTH;
Point::new(x as i32, y as i32)
}
/// Clamp i16 value to 0-255 range.
#[inline]
fn clamp_color(v: i16) -> u8 {
if v < 0 {
0
} else if v > 255 {
255
} else {
v as u8
}
}
/// Simple saturating color addition.
#[inline]
fn mix_color(r1: u8, g1: u8, b1: u8, r2: u8, g2: u8, b2: u8) -> (u8, u8, u8) {
// FIXME this is just lazy code
(
clamp_color(r1 as i16 + r2 as i16),
clamp_color(g1 as i16 + g2 as i16),
clamp_color(b1 as i16 + b2 as i16),
)
}
/// Use u8 value to scale other one.
// FIXME this is just lazy code
#[inline]
fn scale_col(scale: u8, color: u8) -> u8 {
clamp_color((color as f32 * (scale as f32 / 255f32)) as i16)
}
/// Draw all memory values represented by pixels. Width is determined
/// by `MEM_DISP_WIDTH`.
pub fn draw_memory_values<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
let mut x = 0;
let mut y = 0;
for i in 0..0xFFFF {
let p = gameboy.mem[i];
use sdl2::pixels::*;
// renderer.set_draw_color(Color::RGB(r,g,b));
// renderer.set_draw_color(Color::RGB(p as u8, p as u8, p as u8));
renderer.set_draw_color(Color::RGB(0 as u8, 0 as u8, p as u8));
// debug!("pixel at {}, {} is {}", x, y, p);
let point = Point::new(x, y);
match renderer.draw_point(point) {
Ok(_) => (),
Err(_) => error!("Could not draw point at {:?}", point),
}
// inc coord
x = (x + 1) % MEM_DISP_WIDTH;
if x == 0 {
y += 1; // % 256; // does this matter?
}
}
// draw current PC
let pc = gameboy.pc;
renderer.set_draw_color(Color::RGB(255, 255, 255));
renderer.draw_point(addr_to_point(pc)).unwrap();
}
/// Draw memory values represented by pixels with colors showing types
/// of access (r/w/x).
pub fn draw_memory_access<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
// TODO replace this function with parts of MemVisState::draw()
let mut x = 0;
let mut y = 0;
let event_logger = match gameboy.mem.logger {
Some(ref logger) => logger,
None => return,
};
for &p in event_logger.values.iter() {
use sdl2::pixels::*;
// let value = gameboy.mem[addr];
let value = p;
// let color = Color::RGB(
// clamp_color(v * ((p & 0x2) >> 1) as i16 + v>>2),
// clamp_color(v * ((p & 0x1) >> 0) as i16 + v>>2),
// clamp_color(v * ((p & 0x4) >> 2) as i16 + v>>2));
let color = if p == 0 {
// Was not accessed
Color::RGB(value, value, value)
} else {
// FIXME The color is determined by value in memory, we
// want to fade max color somewhat (to use bright colors
// by other stuff), but also show at least something
// instead of black.
//
// It will not overflow normally because input value is
// 8bit, and "base" is added to 16bit value, and then the
// value "clamped" so you get "saturating addition(?)"
let base = 32;
let value = (value >> 2) as i16;
let scale = value + base;
Color::RGB(
clamp_color(scale * ((p & FLAG_W) >> 1) as i16),
clamp_color(scale * (p & FLAG_R) as i16),
clamp_color(255 * ((p & FLAG_X) >> 2) as i16),
)
};
renderer.set_draw_color(color);
// let r = event_logger.access_flags[(addr * 4)];
// let g = event_logger.access_flags[(addr * 4) + 1];
// let b = event_logger.access_flags[(addr * 4) + 2];
// renderer.set_draw_color(
// if r == 0 && g == 0 && b == 0 {
// Color::RGB(p,p,p)
// } else {
// Color::RGB(r,g,b)
// });
let point = Point::new(x, y);
match renderer.draw_point(point) {
Ok(_) => (),
Err(_) => error!("Could not draw point at {:?}", point),
}
// inc coord
x = (x + 1) % MEM_DISP_WIDTH;
if x == 0 {
y += 1; // % 256; // does this matter?
}
}
// draw current PC
let pc = gameboy.pc;
renderer.set_draw_color(Color::RGB(255, 0, 255));
renderer.draw_point(addr_to_point(pc)).unwrap();
}
/// Draw all `CpuEvents` that fade depending on current cpu time. When
/// age of event is more that `FADE_DELAY`, event is removed.
pub fn
|
<T>(renderer: &mut sdl2::render::Canvas<T>, gameboy: &Cpu)
where
T: sdl2::render::RenderTarget,
{
// TODO: can be used to do partial "smart" redraw, and speed thing up.
// But event logging itself is extremely slow
renderer.set_blend_mode(sdl2::render::BlendMode::Add);
let event_logger = match gameboy.mem.logger {
Some(ref logger) => logger,
None => return,
};
// Draw current events with color determined by age
for entry in &event_logger.events_deq {
let timestamp = entry.timestamp;
let event = &entry.event;
{
let time_diff = (Wrapping(gameboy.cycles) - Wrapping(timestamp)).0;
if time_diff < FADE_DELAY {
let time_norm = 1.0 - (time_diff as f32) / (FADE_DELAY as f32);
let colval = (time_norm * 255.0) as u8;
match *event {
CpuEvent::Read { from: addr } => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(0, colval, 0, scale_col(colval, val / 2), 0, val);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Write { to: addr } => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(colval, 0, 0, 0, scale_col(colval, val / 2), val);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Execute(addr) => {
let val = gameboy.mem[addr as usize] as u8;
let (r, g, b) = mix_color(colval, colval, scale_col(colval, val), 0, 0, 0);
renderer.set_draw_color(Color::RGB(r, g, b));
match renderer.draw_point(addr_to_point(addr)) {
Ok(_) => (),
Err(_) => error!("Cannot draw point at {:?}", addr_to_point(addr)),
}
}
CpuEvent::Jump { from: src, to: dst } => {
renderer.set_draw_color(Color::RGBA(200, 200, 0, colval));
let src_point = addr_to_point(src);
let dst_point = addr_to_point(dst);
// Horizontal lines are drawn with scaling but diagonal
// lines ignore it for some reason, which allows us to
// draw lines thinner than memory cells.
if src_point.y()!= dst_point.y() {
match renderer.draw_line(src_point, dst_point) {
Ok(_) => (),
Err(_) => error!(
"Cannot draw line from {:?} to {:?}",
src_point, dst_point
),
}
}
}
_ => (),
}
} else {
break;
}
}
}
renderer.set_blend_mode(sdl2::render::BlendMode::None);
}
fn print_address_info(pc: MemAddr, cpu: &Cpu) {
let pc = pc as usize;
let ref mem = cpu.mem;
let b1 = mem[pc + 1];
let b2 = mem[pc + 2];
let (mnem, _) = disasm::pp_opcode(mem[pc] as u8, b1 as u8, b2 as u8, pc as u16);
let nn = byte_to_u16(b1, b2);
println!(
"${:04X} {:16} 0x{:02X} 0x{:02X} 0x{:02X} 0x{:04X}",
pc, mnem, mem[pc], b1, b2, nn
);
}
|
draw_memory_events
|
identifier_name
|
lib.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Logger for parity executables
extern crate ethcore_util as util;
#[macro_use]
extern crate log as rlog;
extern crate isatty;
extern crate regex;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate lazy_static;
use std::{env, thread};
use std::sync::Arc;
use std::fs::File;
use std::io::Write;
use isatty::{stderr_isatty, stdout_isatty};
use env_logger::LogBuilder;
use regex::Regex;
use util::RotatingLogger;
use util::log::Colour;
#[derive(Debug, PartialEq)]
pub struct Config {
pub mode: Option<String>,
pub color: bool,
pub file: Option<String>,
}
impl Default for Config {
fn default() -> Self {
Config {
mode: None,
color:!cfg!(windows),
file: None,
}
}
}
/// Sets up the logger
pub fn setup_log(config: &Config) -> Result<Arc<RotatingLogger>, String> {
use rlog::*;
let mut levels = String::new();
let mut builder = LogBuilder::new();
// Disable ws info logging by default.
builder.filter(Some("ws"), LogLevelFilter::Warn);
// Disable rustls info logging by default.
builder.filter(Some("rustls"), LogLevelFilter::Warn);
builder.filter(None, LogLevelFilter::Info);
if let Ok(lvl) = env::var("RUST_LOG") {
levels.push_str(&lvl);
levels.push_str(",");
builder.parse(&lvl);
}
if let Some(ref s) = config.mode {
levels.push_str(s);
builder.parse(s);
}
let isatty = stderr_isatty();
let enable_color = config.color && isatty;
let logs = Arc::new(RotatingLogger::new(levels));
let logger = logs.clone();
let maybe_file = match config.file.as_ref() {
Some(f) => Some(try!(File::create(f).map_err(|_| format!("Cannot write to log file given: {}", f)))),
None => None,
};
let format = move |record: &LogRecord| {
let timestamp = time::strftime("%Y-%m-%d %H:%M:%S %Z", &time::now()).unwrap();
let with_color = if max_log_level() <= LogLevelFilter::Info {
format!("{} {}", Colour::Black.bold().paint(timestamp), record.args())
} else {
let name = thread::current().name().map_or_else(Default::default, |x| format!("{}", Colour::Blue.bold().paint(x)));
format!("{} {} {} {} {}", Colour::Black.bold().paint(timestamp), name, record.level(), record.target(), record.args())
};
let removed_color = kill_color(with_color.as_ref());
let ret = match enable_color {
true => with_color,
false => removed_color.clone(),
};
if let Some(mut file) = maybe_file.as_ref() {
// ignore errors - there's nothing we can do
let _ = file.write_all(removed_color.as_bytes());
let _ = file.write_all(b"\n");
}
logger.append(removed_color);
if!isatty && record.level() <= LogLevel::Info && stdout_isatty() {
// duplicate INFO/WARN output to console
println!("{}", ret);
}
ret
};
builder.format(format);
builder.init().expect("Logger initialized only once.");
Ok(logs)
}
fn kill_color(s: &str) -> String {
lazy_static! {
static ref RE: Regex = Regex::new("\x1b\\[[^m]+m").unwrap();
}
RE.replace_all(s, "")
}
#[test]
fn should_remove_colour() {
let before = "test";
let after = kill_color(&Colour::Red.bold().paint(before));
assert_eq!(after, "test");
}
#[test]
fn should_remove_multiple_colour()
|
{
let t = format!("{} {}", Colour::Red.bold().paint("test"), Colour::White.normal().paint("again"));
let after = kill_color(&t);
assert_eq!(after, "test again");
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.