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 |
---|---|---|---|---|
p115.rs
|
//! [Problem 115](https://projecteuler.net/problem=115) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt(n: usize, m: usize, map: &mut HashMap<(usize, usize), usize>) -> usize {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
|
sum += get_cnt(n - (len + i) - 1, m, map); // red block and black block
} else {
sum += 1;
}
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String {
let mut map = HashMap::new();
(1..).filter(|&n| get_cnt(n, 50, &mut map) > 1000000)
.next()
.unwrap()
.to_string()
}
problem!("168", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt(1, 3, &mut map));
assert_eq!(1, get_cnt(2, 3, &mut map));
assert_eq!(2, get_cnt(3, 3, &mut map));
assert_eq!(4, get_cnt(4, 3, &mut map));
assert_eq!(17, get_cnt(7, 3, &mut map));
assert_eq!(673135, get_cnt(29, 3, &mut map));
assert_eq!(1089155, get_cnt(30, 3, &mut map));
assert_eq!(880711, get_cnt(56, 10, &mut map));
assert_eq!(1148904, get_cnt(57, 10, &mut map));
}
}
|
random_line_split
|
|
p115.rs
|
//! [Problem 115](https://projecteuler.net/problem=115) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn
|
(n: usize, m: usize, map: &mut HashMap<(usize, usize), usize>) -> usize {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt(n - (len + i) - 1, m, map); // red block and black block
} else {
sum += 1;
}
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String {
let mut map = HashMap::new();
(1..).filter(|&n| get_cnt(n, 50, &mut map) > 1000000)
.next()
.unwrap()
.to_string()
}
problem!("168", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt(1, 3, &mut map));
assert_eq!(1, get_cnt(2, 3, &mut map));
assert_eq!(2, get_cnt(3, 3, &mut map));
assert_eq!(4, get_cnt(4, 3, &mut map));
assert_eq!(17, get_cnt(7, 3, &mut map));
assert_eq!(673135, get_cnt(29, 3, &mut map));
assert_eq!(1089155, get_cnt(30, 3, &mut map));
assert_eq!(880711, get_cnt(56, 10, &mut map));
assert_eq!(1148904, get_cnt(57, 10, &mut map));
}
}
|
get_cnt
|
identifier_name
|
p115.rs
|
//! [Problem 115](https://projecteuler.net/problem=115) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt(n: usize, m: usize, map: &mut HashMap<(usize, usize), usize>) -> usize {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt(n - (len + i) - 1, m, map); // red block and black block
} else
|
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String {
let mut map = HashMap::new();
(1..).filter(|&n| get_cnt(n, 50, &mut map) > 1000000)
.next()
.unwrap()
.to_string()
}
problem!("168", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt(1, 3, &mut map));
assert_eq!(1, get_cnt(2, 3, &mut map));
assert_eq!(2, get_cnt(3, 3, &mut map));
assert_eq!(4, get_cnt(4, 3, &mut map));
assert_eq!(17, get_cnt(7, 3, &mut map));
assert_eq!(673135, get_cnt(29, 3, &mut map));
assert_eq!(1089155, get_cnt(30, 3, &mut map));
assert_eq!(880711, get_cnt(56, 10, &mut map));
assert_eq!(1148904, get_cnt(57, 10, &mut map));
}
}
|
{
sum += 1;
}
|
conditional_block
|
p115.rs
|
//! [Problem 115](https://projecteuler.net/problem=115) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#![feature(range_inclusive)]
#[macro_use(problem)] extern crate common;
use std::iter;
use std::collections::HashMap;
fn get_cnt(n: usize, m: usize, map: &mut HashMap<(usize, usize), usize>) -> usize {
if let Some(&x) = map.get(&(n, m)) {
return x
}
if n < m { let _ = map.insert((n, m), 1); return 1; }
let mut sum = 0;
for len in iter::range_inclusive(m, n) { // most left red block length
for i in iter::range_inclusive(0, n - len) { // most left red block position
if n > len + i {
sum += get_cnt(n - (len + i) - 1, m, map); // red block and black block
} else {
sum += 1;
}
}
}
sum += 1; // all black block
let _ = map.insert((n, m), sum);
sum
}
fn solve() -> String
|
problem!("168", solve);
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::get_cnt;
#[test]
fn small_len() {
let mut map = HashMap::new();
assert_eq!(1, get_cnt(1, 3, &mut map));
assert_eq!(1, get_cnt(2, 3, &mut map));
assert_eq!(2, get_cnt(3, 3, &mut map));
assert_eq!(4, get_cnt(4, 3, &mut map));
assert_eq!(17, get_cnt(7, 3, &mut map));
assert_eq!(673135, get_cnt(29, 3, &mut map));
assert_eq!(1089155, get_cnt(30, 3, &mut map));
assert_eq!(880711, get_cnt(56, 10, &mut map));
assert_eq!(1148904, get_cnt(57, 10, &mut map));
}
}
|
{
let mut map = HashMap::new();
(1..).filter(|&n| get_cnt(n, 50, &mut map) > 1000000)
.next()
.unwrap()
.to_string()
}
|
identifier_body
|
conditional-compile.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.
// Crate use statements
#[cfg(bogus)]
use flippity;
#[cfg(bogus)]
static b: bool = false;
static b: bool = true;
mod rustrt {
#[cfg(bogus)]
extern {
// This symbol doesn't exist and would be a link error if this
// module was translated
pub fn bogus();
}
extern {}
}
#[cfg(bogus)]
type t = isize;
type t = bool;
#[cfg(bogus)]
enum tg { foo, }
enum tg { bar, }
#[cfg(bogus)]
struct r {
i: isize,
}
#[cfg(bogus)]
fn r(i:isize) -> r {
r {
i: i
}
}
struct r {
i: isize,
}
fn r(i:isize) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the top-level
// module, so let's make sure this jazz works here as well
#[cfg(bogus)]
pub fn f() { }
pub fn f() { }
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main()
|
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
// if they had the bogus definition
assert!((b));
let _x: t = true;
let _y: tg = tg::bar;
test_in_fn_ctxt();
}
fn test_in_fn_ctxt() {
#[cfg(bogus)]
fn f() { panic!() }
fn f() { }
f();
#[cfg(bogus)]
static i: isize = 0;
static i: isize = 1;
assert_eq!(i, 1);
}
mod test_foreign_items {
pub mod rustrt {
extern {
#[cfg(bogus)]
pub fn write() -> String;
pub fn write() -> String;
}
}
}
mod test_use_statements {
#[cfg(bogus)]
use flippity_foo;
}
mod test_methods {
struct Foo {
bar: usize
}
impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) { }
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
}
|
{ panic!() }
|
identifier_body
|
conditional-compile.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.
// Crate use statements
#[cfg(bogus)]
use flippity;
#[cfg(bogus)]
static b: bool = false;
static b: bool = true;
mod rustrt {
#[cfg(bogus)]
extern {
// This symbol doesn't exist and would be a link error if this
// module was translated
pub fn bogus();
}
extern {}
}
#[cfg(bogus)]
type t = isize;
type t = bool;
#[cfg(bogus)]
enum tg { foo, }
enum tg { bar, }
#[cfg(bogus)]
struct r {
i: isize,
}
#[cfg(bogus)]
fn r(i:isize) -> r {
r {
i: i
}
}
struct r {
i: isize,
}
fn r(i:isize) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the top-level
// module, so let's make sure this jazz works here as well
#[cfg(bogus)]
pub fn f() { }
pub fn f() { }
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn
|
() { panic!() }
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
// if they had the bogus definition
assert!((b));
let _x: t = true;
let _y: tg = tg::bar;
test_in_fn_ctxt();
}
fn test_in_fn_ctxt() {
#[cfg(bogus)]
fn f() { panic!() }
fn f() { }
f();
#[cfg(bogus)]
static i: isize = 0;
static i: isize = 1;
assert_eq!(i, 1);
}
mod test_foreign_items {
pub mod rustrt {
extern {
#[cfg(bogus)]
pub fn write() -> String;
pub fn write() -> String;
}
}
}
mod test_use_statements {
#[cfg(bogus)]
use flippity_foo;
}
mod test_methods {
struct Foo {
bar: usize
}
impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) { }
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
}
|
main
|
identifier_name
|
conditional-compile.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.
// Crate use statements
#[cfg(bogus)]
use flippity;
#[cfg(bogus)]
static b: bool = false;
static b: bool = true;
mod rustrt {
#[cfg(bogus)]
extern {
// This symbol doesn't exist and would be a link error if this
// module was translated
pub fn bogus();
}
extern {}
}
#[cfg(bogus)]
type t = isize;
type t = bool;
#[cfg(bogus)]
enum tg { foo, }
enum tg { bar, }
#[cfg(bogus)]
struct r {
i: isize,
}
|
r {
i: i
}
}
struct r {
i: isize,
}
fn r(i:isize) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the top-level
// module, so let's make sure this jazz works here as well
#[cfg(bogus)]
pub fn f() { }
pub fn f() { }
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main() { panic!() }
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
// if they had the bogus definition
assert!((b));
let _x: t = true;
let _y: tg = tg::bar;
test_in_fn_ctxt();
}
fn test_in_fn_ctxt() {
#[cfg(bogus)]
fn f() { panic!() }
fn f() { }
f();
#[cfg(bogus)]
static i: isize = 0;
static i: isize = 1;
assert_eq!(i, 1);
}
mod test_foreign_items {
pub mod rustrt {
extern {
#[cfg(bogus)]
pub fn write() -> String;
pub fn write() -> String;
}
}
}
mod test_use_statements {
#[cfg(bogus)]
use flippity_foo;
}
mod test_methods {
struct Foo {
bar: usize
}
impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) { }
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
}
|
#[cfg(bogus)]
fn r(i:isize) -> r {
|
random_line_split
|
main.rs
|
use anyhow::Result;
use std::str::FromStr;
fn parse_fish(name: &str) -> Result<Vec<u64>>
|
fn step(fish: &mut [u64]) {
let fish_0 = fish[0];
for i in 1..9 {
fish[i - 1] = fish[i];
}
fish[8] = fish_0;
fish[6] += fish_0;
}
fn lantern_fish(fish: &[u64], steps: u64) -> u64 {
let mut new = [0; 9];
new[..].clone_from_slice(fish);
for _ in 0..steps {
step(&mut new);
}
new.iter().sum()
}
fn main() {
let fish = parse_fish("input.txt").expect("Error in parsing.");
println!("{}", lantern_fish(&fish, 80));
println!("{}", lantern_fish(&fish, 256));
}
|
{
let raw = std::fs::read_to_string(name)?;
let mut fish = vec![0; 9];
for s in raw.split(',') {
let i = usize::from_str(s)?;
fish[i] += 1;
}
Ok(fish)
}
|
identifier_body
|
main.rs
|
use anyhow::Result;
use std::str::FromStr;
fn parse_fish(name: &str) -> Result<Vec<u64>> {
let raw = std::fs::read_to_string(name)?;
let mut fish = vec![0; 9];
for s in raw.split(',') {
let i = usize::from_str(s)?;
fish[i] += 1;
}
Ok(fish)
}
fn step(fish: &mut [u64]) {
let fish_0 = fish[0];
|
for i in 1..9 {
fish[i - 1] = fish[i];
}
fish[8] = fish_0;
fish[6] += fish_0;
}
fn lantern_fish(fish: &[u64], steps: u64) -> u64 {
let mut new = [0; 9];
new[..].clone_from_slice(fish);
for _ in 0..steps {
step(&mut new);
}
new.iter().sum()
}
fn main() {
let fish = parse_fish("input.txt").expect("Error in parsing.");
println!("{}", lantern_fish(&fish, 80));
println!("{}", lantern_fish(&fish, 256));
}
|
random_line_split
|
|
main.rs
|
use anyhow::Result;
use std::str::FromStr;
fn parse_fish(name: &str) -> Result<Vec<u64>> {
let raw = std::fs::read_to_string(name)?;
let mut fish = vec![0; 9];
for s in raw.split(',') {
let i = usize::from_str(s)?;
fish[i] += 1;
}
Ok(fish)
}
fn
|
(fish: &mut [u64]) {
let fish_0 = fish[0];
for i in 1..9 {
fish[i - 1] = fish[i];
}
fish[8] = fish_0;
fish[6] += fish_0;
}
fn lantern_fish(fish: &[u64], steps: u64) -> u64 {
let mut new = [0; 9];
new[..].clone_from_slice(fish);
for _ in 0..steps {
step(&mut new);
}
new.iter().sum()
}
fn main() {
let fish = parse_fish("input.txt").expect("Error in parsing.");
println!("{}", lantern_fish(&fish, 80));
println!("{}", lantern_fish(&fish, 256));
}
|
step
|
identifier_name
|
linker.rs
|
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
fn main() {
let mut dst = env::current_exe().unwrap();
dst.pop();
dst.push("linker-arguments1");
if dst.exists() {
dst.pop();
dst.push("linker-arguments2");
assert!(!dst.exists());
}
let mut out = String::new();
for arg in env::args().skip(1) {
let path = Path::new(&arg);
if!path.is_file() {
out.push_str(&arg);
out.push_str("\n");
continue
}
let mut contents = Vec::new();
File::open(path).unwrap().read_to_end(&mut contents).unwrap();
out.push_str(&format!("{}: {}\n", arg, hash(&contents)));
|
File::create(dst).unwrap().write_all(out.as_bytes()).unwrap();
}
// fnv hash for now
fn hash(contents: &[u8]) -> u64 {
let mut hash = 0xcbf29ce484222325;
for byte in contents {
hash = hash ^ (*byte as u64);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
|
}
|
random_line_split
|
linker.rs
|
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
fn
|
() {
let mut dst = env::current_exe().unwrap();
dst.pop();
dst.push("linker-arguments1");
if dst.exists() {
dst.pop();
dst.push("linker-arguments2");
assert!(!dst.exists());
}
let mut out = String::new();
for arg in env::args().skip(1) {
let path = Path::new(&arg);
if!path.is_file() {
out.push_str(&arg);
out.push_str("\n");
continue
}
let mut contents = Vec::new();
File::open(path).unwrap().read_to_end(&mut contents).unwrap();
out.push_str(&format!("{}: {}\n", arg, hash(&contents)));
}
File::create(dst).unwrap().write_all(out.as_bytes()).unwrap();
}
// fnv hash for now
fn hash(contents: &[u8]) -> u64 {
let mut hash = 0xcbf29ce484222325;
for byte in contents {
hash = hash ^ (*byte as u64);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
|
main
|
identifier_name
|
linker.rs
|
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
fn main() {
let mut dst = env::current_exe().unwrap();
dst.pop();
dst.push("linker-arguments1");
if dst.exists() {
dst.pop();
dst.push("linker-arguments2");
assert!(!dst.exists());
}
let mut out = String::new();
for arg in env::args().skip(1) {
let path = Path::new(&arg);
if!path.is_file()
|
let mut contents = Vec::new();
File::open(path).unwrap().read_to_end(&mut contents).unwrap();
out.push_str(&format!("{}: {}\n", arg, hash(&contents)));
}
File::create(dst).unwrap().write_all(out.as_bytes()).unwrap();
}
// fnv hash for now
fn hash(contents: &[u8]) -> u64 {
let mut hash = 0xcbf29ce484222325;
for byte in contents {
hash = hash ^ (*byte as u64);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
|
{
out.push_str(&arg);
out.push_str("\n");
continue
}
|
conditional_block
|
linker.rs
|
use std::env;
use std::path::Path;
use std::fs::File;
use std::io::{Read, Write};
fn main() {
let mut dst = env::current_exe().unwrap();
dst.pop();
dst.push("linker-arguments1");
if dst.exists() {
dst.pop();
dst.push("linker-arguments2");
assert!(!dst.exists());
}
let mut out = String::new();
for arg in env::args().skip(1) {
let path = Path::new(&arg);
if!path.is_file() {
out.push_str(&arg);
out.push_str("\n");
continue
}
let mut contents = Vec::new();
File::open(path).unwrap().read_to_end(&mut contents).unwrap();
out.push_str(&format!("{}: {}\n", arg, hash(&contents)));
}
File::create(dst).unwrap().write_all(out.as_bytes()).unwrap();
}
// fnv hash for now
fn hash(contents: &[u8]) -> u64
|
{
let mut hash = 0xcbf29ce484222325;
for byte in contents {
hash = hash ^ (*byte as u64);
hash = hash.wrapping_mul(0x100000001b3);
}
hash
}
|
identifier_body
|
|
b.rs
|
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;
fn decompress<'a>(decompressed: &mut String, characters: &'a mut Vec<char>,
dec_marker: String) {
let mut split = dec_marker.split('x');
let mut repeat_buf: Vec<char> = Vec::new();
let mut repeat_str = String::new();
let count: u16 = split.next().unwrap().parse().unwrap();
let repeat: u16 = split.next().unwrap().parse().unwrap();
for _ in 0..count {
repeat_buf.push(characters.pop().unwrap());
}
repeat_buf.reverse();
parse_characters(repeat_buf, &mut repeat_str);
for _ in 0..repeat {
decompressed.push_str(repeat_str.as_str());
}
}
fn parse_characters(mut characters: Vec<char>, mut decompressed: &mut String) {
while let Some(character) = characters.pop() {
if character!= '(' {
decompressed.push(character);
} else
|
}
}
fn main() {
let f = File::open("input.txt").unwrap();
let reader = BufReader::new(f);
let mut compressed = String::new();
let mut decompressed = String::new();
for line in reader.lines() {
let line: String = line.unwrap();
if!line.is_empty() {
compressed.push_str(line.trim());
}
}
let mut characters: Vec<char> = compressed.chars().collect();
characters.reverse();
parse_characters(characters, &mut decompressed);
println!("length: {}", decompressed.len());
}
|
{
let mut dec_marker = String::new();
let mut next = characters.pop().unwrap();
while next != ')' {
dec_marker.push(next);
next = characters.pop().unwrap();
}
decompress(&mut decompressed, &mut characters, dec_marker);
}
|
conditional_block
|
b.rs
|
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;
fn
|
<'a>(decompressed: &mut String, characters: &'a mut Vec<char>,
dec_marker: String) {
let mut split = dec_marker.split('x');
let mut repeat_buf: Vec<char> = Vec::new();
let mut repeat_str = String::new();
let count: u16 = split.next().unwrap().parse().unwrap();
let repeat: u16 = split.next().unwrap().parse().unwrap();
for _ in 0..count {
repeat_buf.push(characters.pop().unwrap());
}
repeat_buf.reverse();
parse_characters(repeat_buf, &mut repeat_str);
for _ in 0..repeat {
decompressed.push_str(repeat_str.as_str());
}
}
fn parse_characters(mut characters: Vec<char>, mut decompressed: &mut String) {
while let Some(character) = characters.pop() {
if character!= '(' {
decompressed.push(character);
} else {
let mut dec_marker = String::new();
let mut next = characters.pop().unwrap();
while next!= ')' {
dec_marker.push(next);
next = characters.pop().unwrap();
}
decompress(&mut decompressed, &mut characters, dec_marker);
}
}
}
fn main() {
let f = File::open("input.txt").unwrap();
let reader = BufReader::new(f);
let mut compressed = String::new();
let mut decompressed = String::new();
for line in reader.lines() {
let line: String = line.unwrap();
if!line.is_empty() {
compressed.push_str(line.trim());
}
}
let mut characters: Vec<char> = compressed.chars().collect();
characters.reverse();
parse_characters(characters, &mut decompressed);
println!("length: {}", decompressed.len());
}
|
decompress
|
identifier_name
|
b.rs
|
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;
fn decompress<'a>(decompressed: &mut String, characters: &'a mut Vec<char>,
dec_marker: String) {
let mut split = dec_marker.split('x');
let mut repeat_buf: Vec<char> = Vec::new();
let mut repeat_str = String::new();
let count: u16 = split.next().unwrap().parse().unwrap();
let repeat: u16 = split.next().unwrap().parse().unwrap();
for _ in 0..count {
repeat_buf.push(characters.pop().unwrap());
}
repeat_buf.reverse();
parse_characters(repeat_buf, &mut repeat_str);
for _ in 0..repeat {
decompressed.push_str(repeat_str.as_str());
}
}
fn parse_characters(mut characters: Vec<char>, mut decompressed: &mut String) {
while let Some(character) = characters.pop() {
if character!= '(' {
decompressed.push(character);
} else {
let mut dec_marker = String::new();
let mut next = characters.pop().unwrap();
while next!= ')' {
dec_marker.push(next);
next = characters.pop().unwrap();
}
decompress(&mut decompressed, &mut characters, dec_marker);
}
}
}
fn main()
|
{
let f = File::open("input.txt").unwrap();
let reader = BufReader::new(f);
let mut compressed = String::new();
let mut decompressed = String::new();
for line in reader.lines() {
let line: String = line.unwrap();
if !line.is_empty() {
compressed.push_str(line.trim());
}
}
let mut characters: Vec<char> = compressed.chars().collect();
characters.reverse();
parse_characters(characters, &mut decompressed);
println!("length: {}", decompressed.len());
}
|
identifier_body
|
|
b.rs
|
use std::io::prelude::*;
use std::fs::File;
use std::io::BufReader;
fn decompress<'a>(decompressed: &mut String, characters: &'a mut Vec<char>,
dec_marker: String) {
let mut split = dec_marker.split('x');
let mut repeat_buf: Vec<char> = Vec::new();
let mut repeat_str = String::new();
let count: u16 = split.next().unwrap().parse().unwrap();
let repeat: u16 = split.next().unwrap().parse().unwrap();
for _ in 0..count {
repeat_buf.push(characters.pop().unwrap());
}
repeat_buf.reverse();
parse_characters(repeat_buf, &mut repeat_str);
for _ in 0..repeat {
decompressed.push_str(repeat_str.as_str());
}
}
fn parse_characters(mut characters: Vec<char>, mut decompressed: &mut String) {
while let Some(character) = characters.pop() {
if character!= '(' {
decompressed.push(character);
} else {
let mut dec_marker = String::new();
let mut next = characters.pop().unwrap();
while next!= ')' {
dec_marker.push(next);
next = characters.pop().unwrap();
}
decompress(&mut decompressed, &mut characters, dec_marker);
}
}
}
fn main() {
let f = File::open("input.txt").unwrap();
|
let line: String = line.unwrap();
if!line.is_empty() {
compressed.push_str(line.trim());
}
}
let mut characters: Vec<char> = compressed.chars().collect();
characters.reverse();
parse_characters(characters, &mut decompressed);
println!("length: {}", decompressed.len());
}
|
let reader = BufReader::new(f);
let mut compressed = String::new();
let mut decompressed = String::new();
for line in reader.lines() {
|
random_line_split
|
firsts.rs
|
use std::collections::{BTreeMap, BTreeSet};
use crate::utils::{change_iter, change_loop, WasChanged};
use crate::{
grammar::{Elem, ElemTypes},
utils::CollectMap,
};
use super::nullable::{self, Nullable};
use super::Pass;
#[derive(thiserror::Error, Debug)]
pub enum FirstsError {
#[error(transparent)]
NullableError(#[from] nullable::NullableError),
}
pub struct Firsts;
impl<E> Pass<E> for Firsts
where
E: ElemTypes,
{
type Value = BTreeMap<E::NonTerm, BTreeSet<E::Term>>;
type Error = FirstsError;
fn run_pass<'a>(
pass_map: &super::PassMap<'a, E>,
) -> Result<Self::Value, FirstsError> {
let gram = pass_map.grammar();
let nullables = pass_map.get_pass::<Nullable>()?;
let mut firsts = CollectMap::new();
change_loop(|| {
change_iter(gram.prods(), |prod| {
let mut changed = WasChanged::Unchanged;
for elem in prod.elements() {
match elem {
Elem::Term(t) =>
|
Elem::NonTerm(nt) => {
changed.merge(firsts.insert_from_key_set(prod.head(), nt));
if!nullables.is_nullable(nt) {
break;
}
}
}
}
changed
})
});
Ok(
firsts
.into_inner()
.into_iter()
.map(|(k, v)| (k.clone(), v.into_iter().cloned().collect()))
.collect(),
)
}
}
|
{
changed.merge(firsts.insert(prod.head(), t));
break;
}
|
conditional_block
|
firsts.rs
|
use std::collections::{BTreeMap, BTreeSet};
use crate::utils::{change_iter, change_loop, WasChanged};
use crate::{
grammar::{Elem, ElemTypes},
utils::CollectMap,
};
use super::nullable::{self, Nullable};
use super::Pass;
#[derive(thiserror::Error, Debug)]
pub enum FirstsError {
#[error(transparent)]
NullableError(#[from] nullable::NullableError),
}
pub struct Firsts;
impl<E> Pass<E> for Firsts
where
E: ElemTypes,
{
type Value = BTreeMap<E::NonTerm, BTreeSet<E::Term>>;
type Error = FirstsError;
fn
|
<'a>(
pass_map: &super::PassMap<'a, E>,
) -> Result<Self::Value, FirstsError> {
let gram = pass_map.grammar();
let nullables = pass_map.get_pass::<Nullable>()?;
let mut firsts = CollectMap::new();
change_loop(|| {
change_iter(gram.prods(), |prod| {
let mut changed = WasChanged::Unchanged;
for elem in prod.elements() {
match elem {
Elem::Term(t) => {
changed.merge(firsts.insert(prod.head(), t));
break;
}
Elem::NonTerm(nt) => {
changed.merge(firsts.insert_from_key_set(prod.head(), nt));
if!nullables.is_nullable(nt) {
break;
}
}
}
}
changed
})
});
Ok(
firsts
.into_inner()
.into_iter()
.map(|(k, v)| (k.clone(), v.into_iter().cloned().collect()))
.collect(),
)
}
}
|
run_pass
|
identifier_name
|
firsts.rs
|
use std::collections::{BTreeMap, BTreeSet};
use crate::utils::{change_iter, change_loop, WasChanged};
use crate::{
grammar::{Elem, ElemTypes},
utils::CollectMap,
};
use super::nullable::{self, Nullable};
use super::Pass;
#[derive(thiserror::Error, Debug)]
pub enum FirstsError {
#[error(transparent)]
NullableError(#[from] nullable::NullableError),
}
pub struct Firsts;
impl<E> Pass<E> for Firsts
where
|
type Value = BTreeMap<E::NonTerm, BTreeSet<E::Term>>;
type Error = FirstsError;
fn run_pass<'a>(
pass_map: &super::PassMap<'a, E>,
) -> Result<Self::Value, FirstsError> {
let gram = pass_map.grammar();
let nullables = pass_map.get_pass::<Nullable>()?;
let mut firsts = CollectMap::new();
change_loop(|| {
change_iter(gram.prods(), |prod| {
let mut changed = WasChanged::Unchanged;
for elem in prod.elements() {
match elem {
Elem::Term(t) => {
changed.merge(firsts.insert(prod.head(), t));
break;
}
Elem::NonTerm(nt) => {
changed.merge(firsts.insert_from_key_set(prod.head(), nt));
if!nullables.is_nullable(nt) {
break;
}
}
}
}
changed
})
});
Ok(
firsts
.into_inner()
.into_iter()
.map(|(k, v)| (k.clone(), v.into_iter().cloned().collect()))
.collect(),
)
}
}
|
E: ElemTypes,
{
|
random_line_split
|
ndarray.rs
|
use std::iter::Iterator;
use std::iter::Extendable; // for Array construction
use std::vec::Vec;
use std::num::{Zero, One};
// for serialization:
use std::path::Path;
use std::io::IoResult;
use std::io::fs::File;
use std::io::Open;
use std::io::Write;
// Array functionality, including the N-dimensional array.
/// A multidimensional array. The last index is the column index, and the
/// second-last is the row index.
/// TODO generic NDArray<T> for ints, floats including f128, and bool
#[deriving(Show)]
pub struct Array
{
_inner: Vec<f64>, // must never grow!
_shape: Vec<uint>, // product equals _inner.len()
_size: uint // equals product of _shape and _inner.len()
}
// TODO This typedef is backwards! Make Array = NDArray<T>!
type NDArray = Array;
/// A utility function for the NDArray implementation.
trait Dot {
fn dot(left: Vec<Self>, right: Vec<Self>) -> Self;
}
impl Dot for f64 {
#[inline]
fn dot(left: Vec<f64>, right: Vec<f64>) -> f64
{
left.iter().zip(right.iter()).fold(0f64, |b, (&a1, &a2)| b + a1*a2)
}
}
trait Prod {
fn prod(vector: &Vec<Self>) -> Self;
}
impl Prod for f64
{
#[inline]
fn prod(vector: &Vec<f64>) -> f64
{
vector.iter().fold(1f64, |b, &a| a * b)
}
}
impl Array
{
/* CONSTRUCTORS */
/// Constructs a 3x3 demo array.
pub fn square_demo() -> Array
{
let p = Array::with_slice(&[0f64,1f64,2f64,3f64,4f64,5f64,6f64,7f64,8f64]);
let q = p.reshape(&[3,3]);
q
}
/// Constructs a 0-dimensional array.
pub fn empty() -> Array
{
Array {
_inner: Vec::new(),
_shape: vec!(0),
_size: 0
}
}
/// Constructs a singleton array with 1 element.
pub fn with_scalar(scalar: f64) -> Array
{
Array {
_inner: vec!(scalar),
_shape: vec!(1),
_size: 1
}
}
/// Constructs a 1D array with contents of slice.
pub fn with_slice(sl: &[f64]) -> Array
{
let capacity = sl.len();
Array {
_inner: sl.to_vec(), // TODO is this correct?
_shape: vec!(capacity),
_size: capacity
}
}
// TODO pub fn with_slice_2(sl: &[[f64]]) -> Array
// TODO pub fn with_slice_3(sl: &[[[f64]]]) -> Array
// TODO etc
/// Constructs a 1D array with contents of Vec.
pub fn with_vec(vector: Vec<f64>) -> Array
{
let capacity = vector.len();
Array {
_inner: vector.clone(),
_shape: vec!(capacity),
_size: capacity
}
}
/// Constructs an array with given vector's contents, and given shape.
pub fn with_vec_shape(vector: Vec<f64>, shape: &[uint]) -> Array
{
let array = Array::with_vec(vector);
array.reshape(shape);
array
}
/// Internally allocates an ND array with given shape.
fn alloc_with_shape(shape: &[uint]) -> Array
{
let capacity = shape.iter().fold(1u, |b, &a| a * b);
Array {
_inner: Vec::with_capacity(capacity),
_shape: shape.to_vec(),
_size: capacity
}
}
/// Internally allocates an ND array with shape of given array
fn alloc_with_shape_of(other: &Array) -> Array
{
assert!(other._inner.len() == other._size, "Array is inconsistent.");
Array {
_inner: Vec::with_capacity(other._size),
_shape: other._shape.clone(),
_size: other._size
}
}
/// Constructs an array of zeros, with given shape.
pub fn zeros(shape: &[uint]) -> Array
{
let mut a = Array::alloc_with_shape(shape);
a._inner.grow(a._size, &0f64);
a
}
/// Constructs an array of ones, with given shape.
pub fn ones(shape: &[uint]) -> Array
{
let mut a = Array::alloc_with_shape(shape);
a._inner.grow(a._size, &1f64);
a
}
/* SIZE */
/// Returns a slice containing the array's dimensions.
#[inline]
pub fn shape<'a>(&'a self) -> &'a [uint]
{
self._shape.as_slice()
}
/// Returns the number of dimensions of the array.
#[inline]
pub fn ndim(&self) -> uint
{
self._shape.len()
}
/// Returns the number of elements in the array. This is equal to the
/// product of the array's shape
pub fn size(&self) -> uint
{
self._shape.iter().fold(1u, |b, &a| a * b)
}
/* ELEMENT ACCESS */
fn index_to_flat(&self, index: &[uint]) -> uint
{
let offset: uint = *index.last().unwrap();
let ind_it = index.iter().take(index.len()-1);
let shp_it = self._shape.iter().skip(1);
ind_it.zip(shp_it).fold(offset,
|b, (&a1, &a2)| b + a1*a2)
}
/// Gets the n-th element of the array, wrapping over rows/columns/etc.
#[inline]
pub fn get_flat(&self, index: uint) -> f64
{
*self._inner.get(index)
}
/// Gets a scalar element, given a multiindex. Fails if index isn't valid.
pub fn get(&self, index: &[uint]) -> f64
{
assert!(index.len() == self._shape.len())
self.get_flat(self.index_to_flat(index))
}
/// Gets a particular row-vector, column-vector, page-vector, etc.
/// The index for the axis dimension is ignored.
/// TODO DST
pub fn get_vector_axis(&self, index: &[uint], axis: uint) -> Vec<f64>
{
let mut slice = index.to_vec();
let mut it = range(0u, *self._shape.get(axis)).map(|a| {
*slice.get_mut(axis) = a;
self.get(slice.as_slice())
});
it.collect()
}
/// Gets a particular row-vector, column-vector, page-vector, etc.
/// Specify (-1 as uint) for the desired dimension! Fails otherwise.
pub fn get_vector(&self, index: &[uint]) -> Vec<f64>
{
let axis: uint = *index.iter().find(|&&a| (a == -1i as uint)).unwrap();
self.get_vector_axis(index, axis)
}
// TODO sub-array iteration
/* ELEMENT ASSIGNMENT */
pub fn set_flat(&mut self, index: uint, value: f64)
{
*self._inner.get_mut(index) = value;
}
pub fn set(&mut self, index: &[uint], value: f64)
{
assert!(index.len() == self._shape.len());
let flat = self.index_to_flat(index);
self.set_flat(flat, value);
}
// TODO single-element assignment
// TODO sub-array assignment
/* BROADCASTING OPERATIONS */
/// Returns array obtained by applying function to every element.
pub fn apply(&self, func: fn(f64) -> f64) -> Array
{
let it = self._inner.iter().map(|&a| func(a));
let mut empty_array = Array::alloc_with_shape_of(self);
empty_array._inner.extend(it);
empty_array
}
/* SHAPE OPERATIONS */
/// Returns a new array with shifted boundaries. Fails if sizes differ.
/// ATM, this trivially reflows the the array.
/// TODO offer option to pad with zeros?
pub fn reshape(&self, shape: &[uint]) -> Array
{
/* If size == product of new lengths, assign
* else if size is divisible by product, add one dimension, and assign
* else fail.
*/
let capacity = shape.iter().fold(1u, |b, &a| a * b);
assert!(self._size % capacity == 0,
"Array::reshape: self.size must be divisible by shape.prod()!")
if self._size == capacity
{
Array {
_inner: self._inner.clone(),
_shape: shape.to_vec(),
_size: self._size
}
}
else /* self._size % capacity == 0 */
{
let mut full_shape = shape.to_vec();
full_shape.push(self._size / capacity);
Array {
_inner: self._inner.clone(),
_shape: full_shape,
_size: self._size
}
}
}
/* CONTRACTING OPERATIONS */
/// like AdditiveIterator
/// Currently sums every element in array
pub fn sum(&self /*, axis/axes */) -> Array
{
let ref v: Vec<f64> = self._inner;
let sum_f = v.iter().fold(0f64, |b, &a| a + b);
Array {
_inner: vec!(sum_f),
_shape: vec!(1),
_size: 1
}
}
/// like MultiplicativeIterator
/// Currently multiplies every elment in array
pub fn prod(&self /*, axis/axes */) -> Array
{
let prod_f = Prod::prod(&self._inner);
Array {
_inner: vec!(prod_f),
_shape: vec!(1),
_size: 1
}
}
/// Dot product
/// Array dotting essentially treats NDArrays as collections of matrices.
/// Dot acts on last axis (row index) of LHS, and second-last axis of RHS
/// --> dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
///
/// TODO if arrays aren't identically shaped (except last 2 dims)
pub fn dot(&self, rhs: &Array) -> Array
{
let l_ndim: uint = self.ndim();
let r_ndim: uint = rhs.ndim();
assert!(l_ndim > 0 && r_ndim > 0, "Cannot dot an empty array!");
let v_len: uint = *self._shape.get(l_ndim-1);
if l_ndim == 1 && r_ndim == 1
{
if r_ndim == 1
{
assert!(v_len == *rhs._shape.get(r_ndim-1),
"Lengths of dottend vectors must be the same!");
let dot_f = self._inner.iter().zip(rhs._inner.iter()).fold(0f64,
|b, (&a1, &a2)| b + a1*a2);
Array {
_inner: vec!(dot_f),
_shape: vec!(1),
_size: 1
}
}
else /* LHS := row vector, RHS := column vectors or matrix */
{
assert!(v_len == *rhs._shape.get(r_ndim-2),
"Row length of LHS must equal column length of RHS!");
let mut new_dim: Vec<uint> = rhs.shape().slice(0, r_ndim-2).to_vec();
new_dim.push(1); // Only 1 column
new_dim.push(*self.shape().get(r_ndim-1).unwrap());
let new_size = new_dim.iter().fold(1u, |b, &a| a * b);
let mut new_inner = Vec::with_capacity(new_size);
new_inner.push(1f64);
// Do half of iteration below.
fail!(":( This should be incorporated into array broadcasting");
}
}
else /* LHS := row vectors or matrix */
{
assert!(r_ndim > 1, "RHS must have column vectors, consider transposing.");
assert!(v_len == *rhs._shape.get(r_ndim-2),
"Row length of LHS must equal column length of RHS!");
assert!(self.shape().as_slice().slice(0, l_ndim-1) ==
rhs.shape().as_slice().slice(0, r_ndim-1),
"All dimensions of RHS and LHS except last 2 must be equal!");
// ^^^^ at the moment, we only support identic
// TODO broadcast smaller array onto larger one!
// All but last 2 dims of both,
// 2nd last dim of left,
// last dim of right
let mut new_dim: Vec<uint> = self.shape().slice(0, l_ndim-1).to_vec();
new_dim.push(*self.shape().get(r_ndim-1).unwrap());
let new_size = new_dim.iter().fold(1u, |b, &a| a * b);
let mut new_inner = Vec::with_capacity(new_size);
|
let mut _offset = vec!(1u);
for d in new_dim.iter().rev().take(new_dim.len()-1)
{
let _last_offset = *_offset.last().unwrap();
_offset.push(d * _last_offset)
}
_offset.reverse(); // WARNING expensive
_offset
};
// if new_dim = [2, 2, 3, 3], two stacks of two pages of 3x3 matrices
// then offsets = [2*3*3, 3*3, 3, 1]
// dot a multi_index with an offsets to obtain a flat_index
// equivalently, flat_index % offset[i] / new_dim[i] == multi_index[i]
// iterate over elements of new array
for i in range(0u, new_size)
{
let multi_index: Vec<uint> = offsets.iter().zip(new_dim.iter()).map(
|(&offset, &dim)| i / offset % dim).collect();
let l_axis = l_ndim-1;
let r_axis = r_ndim-2;
let mut l_index = multi_index.clone();
let mut r_index = multi_index.clone();
// let new_val = vl.zip(vr).fold(0f64, |b, (&l, &r)| b + l*r);
let mut new_val: f64 = 0f64;
for j in range(0u, v_len)
{
*l_index.get_mut(l_axis) = j; // row vectors from left
*r_index.get_mut(r_axis) = j; // col vectors from right
new_val += self.get(l_index.as_slice()) * rhs.get(r_index.as_slice());
}
new_inner.push(new_val);
}
Array {
_inner: new_inner,
_shape: new_dim,
_size: new_size
}
}
}
/// Writes the array into the specified file.
/// TODO is this idiomatic?
pub fn write_to(&self, path: &str) -> IoResult<()>
{
match File::open_mode(&Path::new(path), Open, Write)
{
Ok(mut file) => {
match file.write_le_u64(self._shape.len() as u64)
{
Ok(_) => {
for &dim in self._shape.iter()
{
match file.write_le_u64(dim as u64) {
Ok(_) => (),
Err(io_err) => return Err(io_err)
}
}
match file.write_le_u64(self._inner.len() as u64)
{
Ok(_) => {
for &element in self._inner.iter()
{
match file.write_le_f64(element) {
Ok(_) => (),
Err(io_err) => return Err(io_err)
}
}
file.write_u8(0)
},
Err(io_err) => Err(io_err)
}
},
Err(io_err) => Err(io_err)
}
},
Err(io_err) => Err(io_err)
}
}
/// Writes the array into the specified file.
/// TODO is this idiomatic?
pub fn read_from(path: &str) -> IoResult<Array>
{
match File::open(&Path::new(path))
{
Ok(mut file) => {
match file.read_le_u64() {
Ok(ndim) => {
let mut _shape = Vec::with_capacity(ndim as uint);
for _ in range(0u, ndim as uint) {
match file.read_le_u64() {
Ok(len) => _shape.push(len as uint),
Err(io_err) => return Err(io_err)
}
}
match file.read_le_u64() {
Ok(_size) => {
let mut _inner = Vec::with_capacity(_size as uint);
for _ in range(0u, _size as uint) {
match file.read_le_f64() {
Ok(element) => _inner.push(element),
Err(io_err) => return Err(io_err)
}
}
Ok(Array {
_inner: _inner,
_shape: _shape,
_size: _size as uint
})
},
Err(io_err) => return Err(io_err)
}
},
Err(io_err) => return Err(io_err)
}
},
Err(io_err) => return Err(io_err)
}
}
// TODO broadcasting of fn(f64) functions
// TODO pretty printing of arrays
}
/* TODO subarray indexing */
// impl Index<uint, Array> for Array {
// fn index(&self, index: &uint) -> Array
// {
// self._inner.get(index)
// }
// }
/// Broadcast addition over all elements. Fail if shapes differ.
impl Add<Array, Array> for Array {
fn add(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 + a2
));
p
}
}
}
impl Sub<Array, Array> for Array {
fn sub(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 - a2
));
p
}
}
}
impl Mul<Array, Array> for Array {
fn mul(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 * a2
));
p
}
}
}
impl Div<Array, Array> for Array {
fn div(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 / a2
));
p
}
}
}
impl Rem<Array, Array> for Array {
fn rem(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 % a2
));
p
}
}
}
impl Neg<Array> for Array {
fn neg(&self) -> Array
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter();
p._inner.extend(arg_it.map(|&a1|
-a1
));
p
}
}
// impl Zero for Array {
// fn zero() -> Array {
// Array::zeros(&[0])
// }
// fn is_zero(&self) -> bool {
// }
// }
impl One for Array {
fn one() -> Array {
Array::ones(&[1])
}
}
/* TODO generic ops for all NDArray<T> */
// impl Not<Array> for Array {
// fn not(&self) -> Array
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter();
// p._inner.extend(arg_it.map(|&a1|
// !a1
// ));
// p
// }
// }
// impl BitAnd<Array, Array> for Array {
// fn bitand(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 & a2
// ));
// p
// }
// }
// }
// impl BitOr<Array, Array> for Array {
// fn bitor(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 | a2
// ));
// p
// }
// }
// }
// impl BitXor<Array, Array> for Array {
// fn bitxor(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 ^ a2
// ));
// p
// }
// }
// }
// impl Shl<Array, Array> for Array {
// fn shl(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 << (a2 as uint)
// ));
// p
// }
// }
// }
// impl Shr<Array, Array> for Array {
// fn shr(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 >> (a2 as uint)
// ));
// p
// }
// }
// }
|
// let iters = new_dim.iter().map(|length| range(0u, length));
// TODO idiomatic way to tensor-multiply the iterators
let offsets: Vec<uint> = {
|
random_line_split
|
ndarray.rs
|
use std::iter::Iterator;
use std::iter::Extendable; // for Array construction
use std::vec::Vec;
use std::num::{Zero, One};
// for serialization:
use std::path::Path;
use std::io::IoResult;
use std::io::fs::File;
use std::io::Open;
use std::io::Write;
// Array functionality, including the N-dimensional array.
/// A multidimensional array. The last index is the column index, and the
/// second-last is the row index.
/// TODO generic NDArray<T> for ints, floats including f128, and bool
#[deriving(Show)]
pub struct Array
{
_inner: Vec<f64>, // must never grow!
_shape: Vec<uint>, // product equals _inner.len()
_size: uint // equals product of _shape and _inner.len()
}
// TODO This typedef is backwards! Make Array = NDArray<T>!
type NDArray = Array;
/// A utility function for the NDArray implementation.
trait Dot {
fn dot(left: Vec<Self>, right: Vec<Self>) -> Self;
}
impl Dot for f64 {
#[inline]
fn dot(left: Vec<f64>, right: Vec<f64>) -> f64
{
left.iter().zip(right.iter()).fold(0f64, |b, (&a1, &a2)| b + a1*a2)
}
}
trait Prod {
fn prod(vector: &Vec<Self>) -> Self;
}
impl Prod for f64
{
#[inline]
fn prod(vector: &Vec<f64>) -> f64
{
vector.iter().fold(1f64, |b, &a| a * b)
}
}
impl Array
{
/* CONSTRUCTORS */
/// Constructs a 3x3 demo array.
pub fn square_demo() -> Array
{
let p = Array::with_slice(&[0f64,1f64,2f64,3f64,4f64,5f64,6f64,7f64,8f64]);
let q = p.reshape(&[3,3]);
q
}
/// Constructs a 0-dimensional array.
pub fn empty() -> Array
{
Array {
_inner: Vec::new(),
_shape: vec!(0),
_size: 0
}
}
/// Constructs a singleton array with 1 element.
pub fn with_scalar(scalar: f64) -> Array
{
Array {
_inner: vec!(scalar),
_shape: vec!(1),
_size: 1
}
}
/// Constructs a 1D array with contents of slice.
pub fn with_slice(sl: &[f64]) -> Array
{
let capacity = sl.len();
Array {
_inner: sl.to_vec(), // TODO is this correct?
_shape: vec!(capacity),
_size: capacity
}
}
// TODO pub fn with_slice_2(sl: &[[f64]]) -> Array
// TODO pub fn with_slice_3(sl: &[[[f64]]]) -> Array
// TODO etc
/// Constructs a 1D array with contents of Vec.
pub fn with_vec(vector: Vec<f64>) -> Array
{
let capacity = vector.len();
Array {
_inner: vector.clone(),
_shape: vec!(capacity),
_size: capacity
}
}
/// Constructs an array with given vector's contents, and given shape.
pub fn with_vec_shape(vector: Vec<f64>, shape: &[uint]) -> Array
{
let array = Array::with_vec(vector);
array.reshape(shape);
array
}
/// Internally allocates an ND array with given shape.
fn alloc_with_shape(shape: &[uint]) -> Array
{
let capacity = shape.iter().fold(1u, |b, &a| a * b);
Array {
_inner: Vec::with_capacity(capacity),
_shape: shape.to_vec(),
_size: capacity
}
}
/// Internally allocates an ND array with shape of given array
fn alloc_with_shape_of(other: &Array) -> Array
{
assert!(other._inner.len() == other._size, "Array is inconsistent.");
Array {
_inner: Vec::with_capacity(other._size),
_shape: other._shape.clone(),
_size: other._size
}
}
/// Constructs an array of zeros, with given shape.
pub fn zeros(shape: &[uint]) -> Array
{
let mut a = Array::alloc_with_shape(shape);
a._inner.grow(a._size, &0f64);
a
}
/// Constructs an array of ones, with given shape.
pub fn
|
(shape: &[uint]) -> Array
{
let mut a = Array::alloc_with_shape(shape);
a._inner.grow(a._size, &1f64);
a
}
/* SIZE */
/// Returns a slice containing the array's dimensions.
#[inline]
pub fn shape<'a>(&'a self) -> &'a [uint]
{
self._shape.as_slice()
}
/// Returns the number of dimensions of the array.
#[inline]
pub fn ndim(&self) -> uint
{
self._shape.len()
}
/// Returns the number of elements in the array. This is equal to the
/// product of the array's shape
pub fn size(&self) -> uint
{
self._shape.iter().fold(1u, |b, &a| a * b)
}
/* ELEMENT ACCESS */
fn index_to_flat(&self, index: &[uint]) -> uint
{
let offset: uint = *index.last().unwrap();
let ind_it = index.iter().take(index.len()-1);
let shp_it = self._shape.iter().skip(1);
ind_it.zip(shp_it).fold(offset,
|b, (&a1, &a2)| b + a1*a2)
}
/// Gets the n-th element of the array, wrapping over rows/columns/etc.
#[inline]
pub fn get_flat(&self, index: uint) -> f64
{
*self._inner.get(index)
}
/// Gets a scalar element, given a multiindex. Fails if index isn't valid.
pub fn get(&self, index: &[uint]) -> f64
{
assert!(index.len() == self._shape.len())
self.get_flat(self.index_to_flat(index))
}
/// Gets a particular row-vector, column-vector, page-vector, etc.
/// The index for the axis dimension is ignored.
/// TODO DST
pub fn get_vector_axis(&self, index: &[uint], axis: uint) -> Vec<f64>
{
let mut slice = index.to_vec();
let mut it = range(0u, *self._shape.get(axis)).map(|a| {
*slice.get_mut(axis) = a;
self.get(slice.as_slice())
});
it.collect()
}
/// Gets a particular row-vector, column-vector, page-vector, etc.
/// Specify (-1 as uint) for the desired dimension! Fails otherwise.
pub fn get_vector(&self, index: &[uint]) -> Vec<f64>
{
let axis: uint = *index.iter().find(|&&a| (a == -1i as uint)).unwrap();
self.get_vector_axis(index, axis)
}
// TODO sub-array iteration
/* ELEMENT ASSIGNMENT */
pub fn set_flat(&mut self, index: uint, value: f64)
{
*self._inner.get_mut(index) = value;
}
pub fn set(&mut self, index: &[uint], value: f64)
{
assert!(index.len() == self._shape.len());
let flat = self.index_to_flat(index);
self.set_flat(flat, value);
}
// TODO single-element assignment
// TODO sub-array assignment
/* BROADCASTING OPERATIONS */
/// Returns array obtained by applying function to every element.
pub fn apply(&self, func: fn(f64) -> f64) -> Array
{
let it = self._inner.iter().map(|&a| func(a));
let mut empty_array = Array::alloc_with_shape_of(self);
empty_array._inner.extend(it);
empty_array
}
/* SHAPE OPERATIONS */
/// Returns a new array with shifted boundaries. Fails if sizes differ.
/// ATM, this trivially reflows the the array.
/// TODO offer option to pad with zeros?
pub fn reshape(&self, shape: &[uint]) -> Array
{
/* If size == product of new lengths, assign
* else if size is divisible by product, add one dimension, and assign
* else fail.
*/
let capacity = shape.iter().fold(1u, |b, &a| a * b);
assert!(self._size % capacity == 0,
"Array::reshape: self.size must be divisible by shape.prod()!")
if self._size == capacity
{
Array {
_inner: self._inner.clone(),
_shape: shape.to_vec(),
_size: self._size
}
}
else /* self._size % capacity == 0 */
{
let mut full_shape = shape.to_vec();
full_shape.push(self._size / capacity);
Array {
_inner: self._inner.clone(),
_shape: full_shape,
_size: self._size
}
}
}
/* CONTRACTING OPERATIONS */
/// like AdditiveIterator
/// Currently sums every element in array
pub fn sum(&self /*, axis/axes */) -> Array
{
let ref v: Vec<f64> = self._inner;
let sum_f = v.iter().fold(0f64, |b, &a| a + b);
Array {
_inner: vec!(sum_f),
_shape: vec!(1),
_size: 1
}
}
/// like MultiplicativeIterator
/// Currently multiplies every elment in array
pub fn prod(&self /*, axis/axes */) -> Array
{
let prod_f = Prod::prod(&self._inner);
Array {
_inner: vec!(prod_f),
_shape: vec!(1),
_size: 1
}
}
/// Dot product
/// Array dotting essentially treats NDArrays as collections of matrices.
/// Dot acts on last axis (row index) of LHS, and second-last axis of RHS
/// --> dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])
///
/// TODO if arrays aren't identically shaped (except last 2 dims)
pub fn dot(&self, rhs: &Array) -> Array
{
let l_ndim: uint = self.ndim();
let r_ndim: uint = rhs.ndim();
assert!(l_ndim > 0 && r_ndim > 0, "Cannot dot an empty array!");
let v_len: uint = *self._shape.get(l_ndim-1);
if l_ndim == 1 && r_ndim == 1
{
if r_ndim == 1
{
assert!(v_len == *rhs._shape.get(r_ndim-1),
"Lengths of dottend vectors must be the same!");
let dot_f = self._inner.iter().zip(rhs._inner.iter()).fold(0f64,
|b, (&a1, &a2)| b + a1*a2);
Array {
_inner: vec!(dot_f),
_shape: vec!(1),
_size: 1
}
}
else /* LHS := row vector, RHS := column vectors or matrix */
{
assert!(v_len == *rhs._shape.get(r_ndim-2),
"Row length of LHS must equal column length of RHS!");
let mut new_dim: Vec<uint> = rhs.shape().slice(0, r_ndim-2).to_vec();
new_dim.push(1); // Only 1 column
new_dim.push(*self.shape().get(r_ndim-1).unwrap());
let new_size = new_dim.iter().fold(1u, |b, &a| a * b);
let mut new_inner = Vec::with_capacity(new_size);
new_inner.push(1f64);
// Do half of iteration below.
fail!(":( This should be incorporated into array broadcasting");
}
}
else /* LHS := row vectors or matrix */
{
assert!(r_ndim > 1, "RHS must have column vectors, consider transposing.");
assert!(v_len == *rhs._shape.get(r_ndim-2),
"Row length of LHS must equal column length of RHS!");
assert!(self.shape().as_slice().slice(0, l_ndim-1) ==
rhs.shape().as_slice().slice(0, r_ndim-1),
"All dimensions of RHS and LHS except last 2 must be equal!");
// ^^^^ at the moment, we only support identic
// TODO broadcast smaller array onto larger one!
// All but last 2 dims of both,
// 2nd last dim of left,
// last dim of right
let mut new_dim: Vec<uint> = self.shape().slice(0, l_ndim-1).to_vec();
new_dim.push(*self.shape().get(r_ndim-1).unwrap());
let new_size = new_dim.iter().fold(1u, |b, &a| a * b);
let mut new_inner = Vec::with_capacity(new_size);
// let iters = new_dim.iter().map(|length| range(0u, length));
// TODO idiomatic way to tensor-multiply the iterators
let offsets: Vec<uint> = {
let mut _offset = vec!(1u);
for d in new_dim.iter().rev().take(new_dim.len()-1)
{
let _last_offset = *_offset.last().unwrap();
_offset.push(d * _last_offset)
}
_offset.reverse(); // WARNING expensive
_offset
};
// if new_dim = [2, 2, 3, 3], two stacks of two pages of 3x3 matrices
// then offsets = [2*3*3, 3*3, 3, 1]
// dot a multi_index with an offsets to obtain a flat_index
// equivalently, flat_index % offset[i] / new_dim[i] == multi_index[i]
// iterate over elements of new array
for i in range(0u, new_size)
{
let multi_index: Vec<uint> = offsets.iter().zip(new_dim.iter()).map(
|(&offset, &dim)| i / offset % dim).collect();
let l_axis = l_ndim-1;
let r_axis = r_ndim-2;
let mut l_index = multi_index.clone();
let mut r_index = multi_index.clone();
// let new_val = vl.zip(vr).fold(0f64, |b, (&l, &r)| b + l*r);
let mut new_val: f64 = 0f64;
for j in range(0u, v_len)
{
*l_index.get_mut(l_axis) = j; // row vectors from left
*r_index.get_mut(r_axis) = j; // col vectors from right
new_val += self.get(l_index.as_slice()) * rhs.get(r_index.as_slice());
}
new_inner.push(new_val);
}
Array {
_inner: new_inner,
_shape: new_dim,
_size: new_size
}
}
}
/// Writes the array into the specified file.
/// TODO is this idiomatic?
pub fn write_to(&self, path: &str) -> IoResult<()>
{
match File::open_mode(&Path::new(path), Open, Write)
{
Ok(mut file) => {
match file.write_le_u64(self._shape.len() as u64)
{
Ok(_) => {
for &dim in self._shape.iter()
{
match file.write_le_u64(dim as u64) {
Ok(_) => (),
Err(io_err) => return Err(io_err)
}
}
match file.write_le_u64(self._inner.len() as u64)
{
Ok(_) => {
for &element in self._inner.iter()
{
match file.write_le_f64(element) {
Ok(_) => (),
Err(io_err) => return Err(io_err)
}
}
file.write_u8(0)
},
Err(io_err) => Err(io_err)
}
},
Err(io_err) => Err(io_err)
}
},
Err(io_err) => Err(io_err)
}
}
/// Writes the array into the specified file.
/// TODO is this idiomatic?
pub fn read_from(path: &str) -> IoResult<Array>
{
match File::open(&Path::new(path))
{
Ok(mut file) => {
match file.read_le_u64() {
Ok(ndim) => {
let mut _shape = Vec::with_capacity(ndim as uint);
for _ in range(0u, ndim as uint) {
match file.read_le_u64() {
Ok(len) => _shape.push(len as uint),
Err(io_err) => return Err(io_err)
}
}
match file.read_le_u64() {
Ok(_size) => {
let mut _inner = Vec::with_capacity(_size as uint);
for _ in range(0u, _size as uint) {
match file.read_le_f64() {
Ok(element) => _inner.push(element),
Err(io_err) => return Err(io_err)
}
}
Ok(Array {
_inner: _inner,
_shape: _shape,
_size: _size as uint
})
},
Err(io_err) => return Err(io_err)
}
},
Err(io_err) => return Err(io_err)
}
},
Err(io_err) => return Err(io_err)
}
}
// TODO broadcasting of fn(f64) functions
// TODO pretty printing of arrays
}
/* TODO subarray indexing */
// impl Index<uint, Array> for Array {
// fn index(&self, index: &uint) -> Array
// {
// self._inner.get(index)
// }
// }
/// Broadcast addition over all elements. Fail if shapes differ.
impl Add<Array, Array> for Array {
fn add(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 + a2
));
p
}
}
}
impl Sub<Array, Array> for Array {
fn sub(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 - a2
));
p
}
}
}
impl Mul<Array, Array> for Array {
fn mul(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 * a2
));
p
}
}
}
impl Div<Array, Array> for Array {
fn div(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 / a2
));
p
}
}
}
impl Rem<Array, Array> for Array {
fn rem(&self, other: &Array) -> Array
{
assert!(self._shape == other._shape, "Array shapes must be equal!");
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter().zip(other._inner.iter());
p._inner.extend(arg_it.map(|(&a1, &a2)|
a1 % a2
));
p
}
}
}
impl Neg<Array> for Array {
fn neg(&self) -> Array
{
let mut p = Array::alloc_with_shape(self.shape());
let arg_it = self._inner.iter();
p._inner.extend(arg_it.map(|&a1|
-a1
));
p
}
}
// impl Zero for Array {
// fn zero() -> Array {
// Array::zeros(&[0])
// }
// fn is_zero(&self) -> bool {
// }
// }
impl One for Array {
fn one() -> Array {
Array::ones(&[1])
}
}
/* TODO generic ops for all NDArray<T> */
// impl Not<Array> for Array {
// fn not(&self) -> Array
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter();
// p._inner.extend(arg_it.map(|&a1|
// !a1
// ));
// p
// }
// }
// impl BitAnd<Array, Array> for Array {
// fn bitand(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 & a2
// ));
// p
// }
// }
// }
// impl BitOr<Array, Array> for Array {
// fn bitor(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 | a2
// ));
// p
// }
// }
// }
// impl BitXor<Array, Array> for Array {
// fn bitxor(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 ^ a2
// ));
// p
// }
// }
// }
// impl Shl<Array, Array> for Array {
// fn shl(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 << (a2 as uint)
// ));
// p
// }
// }
// }
// impl Shr<Array, Array> for Array {
// fn shr(&self, other: &Array) -> Array
// {
// assert!(self._shape == other._shape, "Array shapes must be equal!");
// {
// let mut p = Array::alloc_with_shape(self.shape());
// let arg_it = self._inner.iter().zip(other._inner.iter());
// p._inner.extend(arg_it.map(|(&a1, &a2)|
// a1 >> (a2 as uint)
// ));
// p
// }
// }
// }
|
ones
|
identifier_name
|
issue-52059-report-when-borrow-and-drop-conflict.rs
|
// rust-lang/rust#52059: Regardless of whether you are moving out of a
// Drop type or just introducing an inadvertent alias via a borrow of
// one of its fields, it is useful to be reminded of the significance
// of the fact that the type implements Drop.
#![feature(nll)]
#![allow(dead_code)]
pub struct S<'a> { url: &'a mut String }
impl<'a> Drop for S<'a> { fn drop(&mut self) { } }
fn finish_1(s: S) -> &mut String {
s.url
}
//~^^ ERROR borrow may still be in use when destructor runs
|
fn finish_2(s: S) -> &mut String {
let p = &mut *s.url; p
}
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_3(s: S) -> &mut String {
let p: &mut _ = s.url; p
}
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_4(s: S) -> &mut String {
let p = s.url; p
}
//~^^ ERROR cannot move out of type `S<'_>`, which implements the `Drop` trait
fn main() {}
|
random_line_split
|
|
issue-52059-report-when-borrow-and-drop-conflict.rs
|
// rust-lang/rust#52059: Regardless of whether you are moving out of a
// Drop type or just introducing an inadvertent alias via a borrow of
// one of its fields, it is useful to be reminded of the significance
// of the fact that the type implements Drop.
#![feature(nll)]
#![allow(dead_code)]
pub struct S<'a> { url: &'a mut String }
impl<'a> Drop for S<'a> { fn drop(&mut self) { } }
fn finish_1(s: S) -> &mut String {
s.url
}
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_2(s: S) -> &mut String {
let p = &mut *s.url; p
}
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_3(s: S) -> &mut String {
let p: &mut _ = s.url; p
}
//~^^ ERROR borrow may still be in use when destructor runs
fn
|
(s: S) -> &mut String {
let p = s.url; p
}
//~^^ ERROR cannot move out of type `S<'_>`, which implements the `Drop` trait
fn main() {}
|
finish_4
|
identifier_name
|
issue-52059-report-when-borrow-and-drop-conflict.rs
|
// rust-lang/rust#52059: Regardless of whether you are moving out of a
// Drop type or just introducing an inadvertent alias via a borrow of
// one of its fields, it is useful to be reminded of the significance
// of the fact that the type implements Drop.
#![feature(nll)]
#![allow(dead_code)]
pub struct S<'a> { url: &'a mut String }
impl<'a> Drop for S<'a> { fn drop(&mut self) { } }
fn finish_1(s: S) -> &mut String {
s.url
}
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_2(s: S) -> &mut String {
let p = &mut *s.url; p
}
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_3(s: S) -> &mut String
|
//~^^ ERROR borrow may still be in use when destructor runs
fn finish_4(s: S) -> &mut String {
let p = s.url; p
}
//~^^ ERROR cannot move out of type `S<'_>`, which implements the `Drop` trait
fn main() {}
|
{
let p: &mut _ = s.url; p
}
|
identifier_body
|
ui.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! UI redirections
use hyper::StatusCode;
use futures::future;
use endpoint::{Endpoint, Request, Response, EndpointPath};
use {handlers, Embeddable};
/// Redirection to UI server.
pub struct Redirection {
embeddable_on: Embeddable,
}
impl Redirection {
pub fn
|
(
embeddable_on: Embeddable,
) -> Self {
Redirection {
embeddable_on,
}
}
}
impl Endpoint for Redirection {
fn respond(&self, _path: EndpointPath, req: Request) -> Response {
Box::new(future::ok(if let Some(ref frame) = self.embeddable_on {
trace!(target: "dapps", "Redirecting to signer interface.");
let protocol = req.uri().scheme().unwrap_or("http");
handlers::Redirection::new(format!("{}://{}:{}", protocol, &frame.host, frame.port)).into()
} else {
trace!(target: "dapps", "Signer disabled, returning 404.");
handlers::ContentHandler::error(
StatusCode::NotFound,
"404 Not Found",
"Your homepage is not available when Trusted Signer is disabled.",
Some("You can still access dapps by writing a correct address, though. Re-enable Signer to get your homepage back."),
None,
).into()
}))
}
}
|
new
|
identifier_name
|
ui.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! UI redirections
use hyper::StatusCode;
use futures::future;
use endpoint::{Endpoint, Request, Response, EndpointPath};
use {handlers, Embeddable};
/// Redirection to UI server.
pub struct Redirection {
embeddable_on: Embeddable,
}
impl Redirection {
pub fn new(
embeddable_on: Embeddable,
) -> Self {
Redirection {
embeddable_on,
}
}
}
impl Endpoint for Redirection {
fn respond(&self, _path: EndpointPath, req: Request) -> Response {
Box::new(future::ok(if let Some(ref frame) = self.embeddable_on {
trace!(target: "dapps", "Redirecting to signer interface.");
let protocol = req.uri().scheme().unwrap_or("http");
handlers::Redirection::new(format!("{}://{}:{}", protocol, &frame.host, frame.port)).into()
} else
|
))
}
}
|
{
trace!(target: "dapps", "Signer disabled, returning 404.");
handlers::ContentHandler::error(
StatusCode::NotFound,
"404 Not Found",
"Your homepage is not available when Trusted Signer is disabled.",
Some("You can still access dapps by writing a correct address, though. Re-enable Signer to get your homepage back."),
None,
).into()
}
|
conditional_block
|
ui.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! UI redirections
use hyper::StatusCode;
use futures::future;
use endpoint::{Endpoint, Request, Response, EndpointPath};
use {handlers, Embeddable};
/// Redirection to UI server.
pub struct Redirection {
embeddable_on: Embeddable,
|
impl Redirection {
pub fn new(
embeddable_on: Embeddable,
) -> Self {
Redirection {
embeddable_on,
}
}
}
impl Endpoint for Redirection {
fn respond(&self, _path: EndpointPath, req: Request) -> Response {
Box::new(future::ok(if let Some(ref frame) = self.embeddable_on {
trace!(target: "dapps", "Redirecting to signer interface.");
let protocol = req.uri().scheme().unwrap_or("http");
handlers::Redirection::new(format!("{}://{}:{}", protocol, &frame.host, frame.port)).into()
} else {
trace!(target: "dapps", "Signer disabled, returning 404.");
handlers::ContentHandler::error(
StatusCode::NotFound,
"404 Not Found",
"Your homepage is not available when Trusted Signer is disabled.",
Some("You can still access dapps by writing a correct address, though. Re-enable Signer to get your homepage back."),
None,
).into()
}))
}
}
|
}
|
random_line_split
|
namespaces.rs
|
use crate::{library, nameutil, version::Version};
use std::ops::Index;
pub type NsId = u16;
pub const MAIN: NsId = library::MAIN_NAMESPACE;
pub const INTERNAL: NsId = library::INTERNAL_NAMESPACE;
#[derive(Debug)]
pub struct Namespace {
pub name: String,
pub crate_name: String,
pub sys_crate_name: String,
pub higher_crate_name: String,
pub package_name: Option<String>,
pub symbol_prefixes: Vec<String>,
pub shared_libs: Vec<String>,
pub versions: Vec<Version>,
}
#[derive(Debug)]
pub struct Info {
namespaces: Vec<Namespace>,
pub is_glib_crate: bool,
pub glib_ns_id: NsId,
}
impl Info {
pub fn main(&self) -> &Namespace {
&self[MAIN]
}
}
impl Index<NsId> for Info {
type Output = Namespace;
fn index(&self, index: NsId) -> &Namespace
|
}
pub fn run(gir: &library::Library) -> Info {
let mut namespaces = Vec::with_capacity(gir.namespaces.len());
let mut is_glib_crate = false;
let mut glib_ns_id = None;
for (ns_id, ns) in gir.namespaces.iter().enumerate() {
let ns_id = ns_id as NsId;
let crate_name = nameutil::crate_name(&ns.name);
let sys_crate_name = format!("{}_sys", crate_name);
let higher_crate_name = match &crate_name[..] {
"gobject" => "glib".to_owned(),
_ => crate_name.clone(),
};
namespaces.push(Namespace {
name: ns.name.clone(),
crate_name,
sys_crate_name,
higher_crate_name,
package_name: ns.package_name.clone(),
symbol_prefixes: ns.symbol_prefixes.clone(),
shared_libs: ns.shared_library.clone(),
versions: ns.versions.iter().cloned().collect(),
});
if ns.name == "GLib" {
glib_ns_id = Some(ns_id);
if ns_id == MAIN {
is_glib_crate = true;
}
} else if ns.name == "GObject" && ns_id == MAIN {
is_glib_crate = true;
}
}
Info {
namespaces,
is_glib_crate,
glib_ns_id: glib_ns_id.expect("Missing `GLib` namespace!"),
}
}
|
{
&self.namespaces[index as usize]
}
|
identifier_body
|
namespaces.rs
|
use crate::{library, nameutil, version::Version};
use std::ops::Index;
pub type NsId = u16;
pub const MAIN: NsId = library::MAIN_NAMESPACE;
pub const INTERNAL: NsId = library::INTERNAL_NAMESPACE;
#[derive(Debug)]
pub struct Namespace {
pub name: String,
pub crate_name: String,
pub sys_crate_name: String,
pub higher_crate_name: String,
pub package_name: Option<String>,
pub symbol_prefixes: Vec<String>,
pub shared_libs: Vec<String>,
pub versions: Vec<Version>,
}
#[derive(Debug)]
pub struct Info {
namespaces: Vec<Namespace>,
pub is_glib_crate: bool,
pub glib_ns_id: NsId,
}
impl Info {
pub fn main(&self) -> &Namespace {
&self[MAIN]
}
}
impl Index<NsId> for Info {
type Output = Namespace;
fn index(&self, index: NsId) -> &Namespace {
&self.namespaces[index as usize]
}
}
pub fn
|
(gir: &library::Library) -> Info {
let mut namespaces = Vec::with_capacity(gir.namespaces.len());
let mut is_glib_crate = false;
let mut glib_ns_id = None;
for (ns_id, ns) in gir.namespaces.iter().enumerate() {
let ns_id = ns_id as NsId;
let crate_name = nameutil::crate_name(&ns.name);
let sys_crate_name = format!("{}_sys", crate_name);
let higher_crate_name = match &crate_name[..] {
"gobject" => "glib".to_owned(),
_ => crate_name.clone(),
};
namespaces.push(Namespace {
name: ns.name.clone(),
crate_name,
sys_crate_name,
higher_crate_name,
package_name: ns.package_name.clone(),
symbol_prefixes: ns.symbol_prefixes.clone(),
shared_libs: ns.shared_library.clone(),
versions: ns.versions.iter().cloned().collect(),
});
if ns.name == "GLib" {
glib_ns_id = Some(ns_id);
if ns_id == MAIN {
is_glib_crate = true;
}
} else if ns.name == "GObject" && ns_id == MAIN {
is_glib_crate = true;
}
}
Info {
namespaces,
is_glib_crate,
glib_ns_id: glib_ns_id.expect("Missing `GLib` namespace!"),
}
}
|
run
|
identifier_name
|
namespaces.rs
|
use crate::{library, nameutil, version::Version};
use std::ops::Index;
pub type NsId = u16;
pub const MAIN: NsId = library::MAIN_NAMESPACE;
pub const INTERNAL: NsId = library::INTERNAL_NAMESPACE;
#[derive(Debug)]
pub struct Namespace {
pub name: String,
pub crate_name: String,
pub sys_crate_name: String,
pub higher_crate_name: String,
pub package_name: Option<String>,
pub symbol_prefixes: Vec<String>,
pub shared_libs: Vec<String>,
pub versions: Vec<Version>,
}
#[derive(Debug)]
pub struct Info {
namespaces: Vec<Namespace>,
pub is_glib_crate: bool,
pub glib_ns_id: NsId,
}
impl Info {
pub fn main(&self) -> &Namespace {
&self[MAIN]
}
}
impl Index<NsId> for Info {
type Output = Namespace;
fn index(&self, index: NsId) -> &Namespace {
&self.namespaces[index as usize]
}
}
|
for (ns_id, ns) in gir.namespaces.iter().enumerate() {
let ns_id = ns_id as NsId;
let crate_name = nameutil::crate_name(&ns.name);
let sys_crate_name = format!("{}_sys", crate_name);
let higher_crate_name = match &crate_name[..] {
"gobject" => "glib".to_owned(),
_ => crate_name.clone(),
};
namespaces.push(Namespace {
name: ns.name.clone(),
crate_name,
sys_crate_name,
higher_crate_name,
package_name: ns.package_name.clone(),
symbol_prefixes: ns.symbol_prefixes.clone(),
shared_libs: ns.shared_library.clone(),
versions: ns.versions.iter().cloned().collect(),
});
if ns.name == "GLib" {
glib_ns_id = Some(ns_id);
if ns_id == MAIN {
is_glib_crate = true;
}
} else if ns.name == "GObject" && ns_id == MAIN {
is_glib_crate = true;
}
}
Info {
namespaces,
is_glib_crate,
glib_ns_id: glib_ns_id.expect("Missing `GLib` namespace!"),
}
}
|
pub fn run(gir: &library::Library) -> Info {
let mut namespaces = Vec::with_capacity(gir.namespaces.len());
let mut is_glib_crate = false;
let mut glib_ns_id = None;
|
random_line_split
|
types.rs
|
use serde_json::Value;
pub(crate) const STATUS_OK: &str = "ok";
pub(crate) const REGISTER_RESULTS: &str = "REGISTER_RESULTS";
pub(crate) const ROUND_DATA: &str = "ROUND_DATA";
pub(crate) const NOTIFICATION: &str = "NOTIFICATION";
|
Notification { server_token: String, event_id: u32, localized_notification: Value },
}
#[derive(Serialize)]
pub(crate) struct GameDataResponse<'a> {
pub(crate) t: &'a str,
pub(crate) status: &'a str,
pub(crate) data: &'a Value
}
#[derive(Serialize)]
pub(crate) struct RegDataResponse<'a> {
pub(crate) t: &'a str,
pub(crate) status: &'a str
}
#[derive(Serialize)]
pub(crate) struct NotificationResponse<'a> {
pub(crate) t: &'a str,
pub(crate) localized_notification: &'a Value
}
|
#[derive(Deserialize)]
#[serde(tag = "t", content = "d")]
pub(crate) enum GenericIncomingRequest {
Register { game_hash: String, event_id: u32 },
GameState { server_token: String, game_hash: String, data: Value },
|
random_line_split
|
types.rs
|
use serde_json::Value;
pub(crate) const STATUS_OK: &str = "ok";
pub(crate) const REGISTER_RESULTS: &str = "REGISTER_RESULTS";
pub(crate) const ROUND_DATA: &str = "ROUND_DATA";
pub(crate) const NOTIFICATION: &str = "NOTIFICATION";
#[derive(Deserialize)]
#[serde(tag = "t", content = "d")]
pub(crate) enum GenericIncomingRequest {
Register { game_hash: String, event_id: u32 },
GameState { server_token: String, game_hash: String, data: Value },
Notification { server_token: String, event_id: u32, localized_notification: Value },
}
#[derive(Serialize)]
pub(crate) struct
|
<'a> {
pub(crate) t: &'a str,
pub(crate) status: &'a str,
pub(crate) data: &'a Value
}
#[derive(Serialize)]
pub(crate) struct RegDataResponse<'a> {
pub(crate) t: &'a str,
pub(crate) status: &'a str
}
#[derive(Serialize)]
pub(crate) struct NotificationResponse<'a> {
pub(crate) t: &'a str,
pub(crate) localized_notification: &'a Value
}
|
GameDataResponse
|
identifier_name
|
status.rs
|
use config::{Config, OutputFormat};
use utils::console::*;
use utils::output;
use clap::{App, Arg, ArgMatches, SubCommand};
use hyper::Client;
use serde_json;
use std::io::Read;
use std::str;
use webbrowser;
pub const NAME: &'static str = "status";
error_chain! {
errors {
CenterDeviceStatusFailed {
description("failed to get CenterDevice status")
display("failed to get CenterDevice status")
}
}
}
#[derive(Deserialize, Debug)]
enum Status {
Okay,
Warning,
Failed,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct Rest {
Status: Status,
Timestamp: String,
NotificationQueueClientPool: bool,
FolderHealthCheckSensor: bool,
DocumentQueueClientPool: bool,
MetadataStoreResource: bool,
NotificationStoreResource: bool,
SearchEngineResource: bool,
SecurityDataStoreResource: bool,
SendEmailQueueClientPool: bool,
UserdataStoreResource: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct Auth {
Status: Status,
Timestamp: String,
AuthServer: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct WebClient {
Status: Status,
Timestamp: String,
NotificationAlertingService: bool,
RestServerSensor: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct PublicLink {
Status: Status,
Timestamp: String,
PublicLinkClient: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct DistributorConsole {
Status: Status,
Timestamp: String,
RestServerSensor: bool,
}
#[allow(non_camel_case_types)]
#[derive(Deserialize, Debug)]
enum PingDomStatus {
up,
down,
}
#[derive(Deserialize, Debug)]
struct Checks {
checks: Vec<Vec<Check>>,
}
#[derive(Deserialize, Debug)]
struct Check {
hostname: String,
status: PingDomStatus,
lasttesttime: String,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct PingDom {
Status: Status,
Timestamp: String,
Checks: Checks,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct CenterDeviceStatus {
Status: Status,
Rest: Rest,
Auth: Auth,
WebClient: WebClient,
PublicLink: PublicLink,
DistributorConsole: DistributorConsole,
PingDom: PingDom,
}
pub fn build_sub_cli() -> App<'static,'static> {
SubCommand::with_name(NAME)
.about("Gets public centerdevice status from status server")
.arg(Arg::with_name("details")
.long("details")
.help("Show detailed output"))
.arg(Arg::with_name("browser")
.long("browser")
.help("Open status in web browser"))
}
pub fn call(args: Option<&ArgMatches>, config: &Config) -> Result<()> {
let details = args.ok_or(false).unwrap().is_present("details");
let browser = args.ok_or(false).unwrap().is_present("browser");
if browser {
info("Opening CenterDevice Status in default browser...");
browse(config, details).chain_err(|| ErrorKind::CenterDeviceStatusFailed)
} else
|
}
fn browse(config: &Config, details: bool) -> Result<()> {
if details {
webbrowser::open("http://status.centerdevice.de/details.html")
} else {
webbrowser::open("http://status.centerdevice.de")
}.chain_err(|| "Failed to open default browser")?;
if config.general.output_format == OutputFormat::JSON { msgln("{}"); }
Ok(())
}
fn status(config: &Config, details: bool) -> Result<()> {
let json = get_centerdevice_status_json()?;
output(&json, &config.general.output_format, details)
}
fn get_centerdevice_status_json() -> Result<String> {
let url = "http://status.centerdevice.de/details.json";
let mut response = Client::new()
.get(url)
.send()
.chain_err(|| ErrorKind::CenterDeviceStatusFailed)?;
let mut buffer = Vec::new();
response.read_to_end(&mut buffer).chain_err(|| "Failed to read HTTP response")?;
let json = str::from_utf8(&buffer).chain_err(|| "Failed to parse JSON")?;
Ok(json.to_string())
}
fn output(json: &str, format: &OutputFormat, details: bool) -> Result<()> {
match *format {
OutputFormat::HUMAN => output_human(json, details),
OutputFormat::JSON => output::as_json(json)
.chain_err(|| ErrorKind::CenterDeviceStatusFailed),
}
}
fn output_human(json: &str, details: bool) -> Result<()> {
let status: CenterDeviceStatus = serde_json::from_str(json).chain_err(|| "JSON parsing failed")?;
match (&status.Status, details) {
(&Status::Okay, false) =>
msgln(format!("CenterDevice status is {:?}.", status.Status)),
(&Status::Okay, true) | (&Status::Warning, _) | (&Status::Failed, _) => {
msgln(format!("CenterDevice status is {:?}.", status.Status));
msgln(format!("+ Rest: {:?}", status.Rest.Status));
msgln(format!("+ Auth: {:?}", status.Auth.Status));
msgln(format!("+ WebClient: {:?}", status.WebClient.Status));
msgln(format!("+ PublicLink: {:?}", status.PublicLink.Status));
msgln(format!("+ DistributorConsole: {:?}", status.DistributorConsole.Status));
msgln(format!("+ PingDom: {:?}", status.PingDom.Status));
}
}
Ok(())
}
|
{
info("Getting CenterDevice Status ...");
status(config, details).chain_err(|| ErrorKind::CenterDeviceStatusFailed)
}
|
conditional_block
|
status.rs
|
use config::{Config, OutputFormat};
use utils::console::*;
use utils::output;
use clap::{App, Arg, ArgMatches, SubCommand};
use hyper::Client;
use serde_json;
use std::io::Read;
use std::str;
use webbrowser;
pub const NAME: &'static str = "status";
error_chain! {
errors {
CenterDeviceStatusFailed {
description("failed to get CenterDevice status")
display("failed to get CenterDevice status")
}
}
}
#[derive(Deserialize, Debug)]
enum Status {
Okay,
Warning,
Failed,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct Rest {
Status: Status,
Timestamp: String,
NotificationQueueClientPool: bool,
FolderHealthCheckSensor: bool,
DocumentQueueClientPool: bool,
MetadataStoreResource: bool,
NotificationStoreResource: bool,
SearchEngineResource: bool,
SecurityDataStoreResource: bool,
SendEmailQueueClientPool: bool,
UserdataStoreResource: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct Auth {
Status: Status,
Timestamp: String,
AuthServer: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct WebClient {
Status: Status,
Timestamp: String,
NotificationAlertingService: bool,
RestServerSensor: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct PublicLink {
Status: Status,
Timestamp: String,
PublicLinkClient: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct DistributorConsole {
Status: Status,
Timestamp: String,
RestServerSensor: bool,
}
#[allow(non_camel_case_types)]
#[derive(Deserialize, Debug)]
enum PingDomStatus {
up,
down,
}
#[derive(Deserialize, Debug)]
struct Checks {
checks: Vec<Vec<Check>>,
}
#[derive(Deserialize, Debug)]
struct Check {
hostname: String,
status: PingDomStatus,
lasttesttime: String,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct PingDom {
Status: Status,
Timestamp: String,
Checks: Checks,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct CenterDeviceStatus {
Status: Status,
Rest: Rest,
Auth: Auth,
WebClient: WebClient,
PublicLink: PublicLink,
DistributorConsole: DistributorConsole,
PingDom: PingDom,
}
pub fn
|
() -> App<'static,'static> {
SubCommand::with_name(NAME)
.about("Gets public centerdevice status from status server")
.arg(Arg::with_name("details")
.long("details")
.help("Show detailed output"))
.arg(Arg::with_name("browser")
.long("browser")
.help("Open status in web browser"))
}
pub fn call(args: Option<&ArgMatches>, config: &Config) -> Result<()> {
let details = args.ok_or(false).unwrap().is_present("details");
let browser = args.ok_or(false).unwrap().is_present("browser");
if browser {
info("Opening CenterDevice Status in default browser...");
browse(config, details).chain_err(|| ErrorKind::CenterDeviceStatusFailed)
} else {
info("Getting CenterDevice Status...");
status(config, details).chain_err(|| ErrorKind::CenterDeviceStatusFailed)
}
}
fn browse(config: &Config, details: bool) -> Result<()> {
if details {
webbrowser::open("http://status.centerdevice.de/details.html")
} else {
webbrowser::open("http://status.centerdevice.de")
}.chain_err(|| "Failed to open default browser")?;
if config.general.output_format == OutputFormat::JSON { msgln("{}"); }
Ok(())
}
fn status(config: &Config, details: bool) -> Result<()> {
let json = get_centerdevice_status_json()?;
output(&json, &config.general.output_format, details)
}
fn get_centerdevice_status_json() -> Result<String> {
let url = "http://status.centerdevice.de/details.json";
let mut response = Client::new()
.get(url)
.send()
.chain_err(|| ErrorKind::CenterDeviceStatusFailed)?;
let mut buffer = Vec::new();
response.read_to_end(&mut buffer).chain_err(|| "Failed to read HTTP response")?;
let json = str::from_utf8(&buffer).chain_err(|| "Failed to parse JSON")?;
Ok(json.to_string())
}
fn output(json: &str, format: &OutputFormat, details: bool) -> Result<()> {
match *format {
OutputFormat::HUMAN => output_human(json, details),
OutputFormat::JSON => output::as_json(json)
.chain_err(|| ErrorKind::CenterDeviceStatusFailed),
}
}
fn output_human(json: &str, details: bool) -> Result<()> {
let status: CenterDeviceStatus = serde_json::from_str(json).chain_err(|| "JSON parsing failed")?;
match (&status.Status, details) {
(&Status::Okay, false) =>
msgln(format!("CenterDevice status is {:?}.", status.Status)),
(&Status::Okay, true) | (&Status::Warning, _) | (&Status::Failed, _) => {
msgln(format!("CenterDevice status is {:?}.", status.Status));
msgln(format!("+ Rest: {:?}", status.Rest.Status));
msgln(format!("+ Auth: {:?}", status.Auth.Status));
msgln(format!("+ WebClient: {:?}", status.WebClient.Status));
msgln(format!("+ PublicLink: {:?}", status.PublicLink.Status));
msgln(format!("+ DistributorConsole: {:?}", status.DistributorConsole.Status));
msgln(format!("+ PingDom: {:?}", status.PingDom.Status));
}
}
Ok(())
}
|
build_sub_cli
|
identifier_name
|
status.rs
|
use config::{Config, OutputFormat};
use utils::console::*;
use utils::output;
use clap::{App, Arg, ArgMatches, SubCommand};
use hyper::Client;
use serde_json;
use std::io::Read;
use std::str;
use webbrowser;
pub const NAME: &'static str = "status";
error_chain! {
errors {
CenterDeviceStatusFailed {
description("failed to get CenterDevice status")
display("failed to get CenterDevice status")
}
}
}
#[derive(Deserialize, Debug)]
enum Status {
Okay,
Warning,
Failed,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct Rest {
Status: Status,
Timestamp: String,
NotificationQueueClientPool: bool,
FolderHealthCheckSensor: bool,
DocumentQueueClientPool: bool,
MetadataStoreResource: bool,
NotificationStoreResource: bool,
SearchEngineResource: bool,
SecurityDataStoreResource: bool,
SendEmailQueueClientPool: bool,
UserdataStoreResource: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct Auth {
Status: Status,
Timestamp: String,
AuthServer: bool,
}
|
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct WebClient {
Status: Status,
Timestamp: String,
NotificationAlertingService: bool,
RestServerSensor: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct PublicLink {
Status: Status,
Timestamp: String,
PublicLinkClient: bool,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct DistributorConsole {
Status: Status,
Timestamp: String,
RestServerSensor: bool,
}
#[allow(non_camel_case_types)]
#[derive(Deserialize, Debug)]
enum PingDomStatus {
up,
down,
}
#[derive(Deserialize, Debug)]
struct Checks {
checks: Vec<Vec<Check>>,
}
#[derive(Deserialize, Debug)]
struct Check {
hostname: String,
status: PingDomStatus,
lasttesttime: String,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct PingDom {
Status: Status,
Timestamp: String,
Checks: Checks,
}
#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
struct CenterDeviceStatus {
Status: Status,
Rest: Rest,
Auth: Auth,
WebClient: WebClient,
PublicLink: PublicLink,
DistributorConsole: DistributorConsole,
PingDom: PingDom,
}
pub fn build_sub_cli() -> App<'static,'static> {
SubCommand::with_name(NAME)
.about("Gets public centerdevice status from status server")
.arg(Arg::with_name("details")
.long("details")
.help("Show detailed output"))
.arg(Arg::with_name("browser")
.long("browser")
.help("Open status in web browser"))
}
pub fn call(args: Option<&ArgMatches>, config: &Config) -> Result<()> {
let details = args.ok_or(false).unwrap().is_present("details");
let browser = args.ok_or(false).unwrap().is_present("browser");
if browser {
info("Opening CenterDevice Status in default browser...");
browse(config, details).chain_err(|| ErrorKind::CenterDeviceStatusFailed)
} else {
info("Getting CenterDevice Status...");
status(config, details).chain_err(|| ErrorKind::CenterDeviceStatusFailed)
}
}
fn browse(config: &Config, details: bool) -> Result<()> {
if details {
webbrowser::open("http://status.centerdevice.de/details.html")
} else {
webbrowser::open("http://status.centerdevice.de")
}.chain_err(|| "Failed to open default browser")?;
if config.general.output_format == OutputFormat::JSON { msgln("{}"); }
Ok(())
}
fn status(config: &Config, details: bool) -> Result<()> {
let json = get_centerdevice_status_json()?;
output(&json, &config.general.output_format, details)
}
fn get_centerdevice_status_json() -> Result<String> {
let url = "http://status.centerdevice.de/details.json";
let mut response = Client::new()
.get(url)
.send()
.chain_err(|| ErrorKind::CenterDeviceStatusFailed)?;
let mut buffer = Vec::new();
response.read_to_end(&mut buffer).chain_err(|| "Failed to read HTTP response")?;
let json = str::from_utf8(&buffer).chain_err(|| "Failed to parse JSON")?;
Ok(json.to_string())
}
fn output(json: &str, format: &OutputFormat, details: bool) -> Result<()> {
match *format {
OutputFormat::HUMAN => output_human(json, details),
OutputFormat::JSON => output::as_json(json)
.chain_err(|| ErrorKind::CenterDeviceStatusFailed),
}
}
fn output_human(json: &str, details: bool) -> Result<()> {
let status: CenterDeviceStatus = serde_json::from_str(json).chain_err(|| "JSON parsing failed")?;
match (&status.Status, details) {
(&Status::Okay, false) =>
msgln(format!("CenterDevice status is {:?}.", status.Status)),
(&Status::Okay, true) | (&Status::Warning, _) | (&Status::Failed, _) => {
msgln(format!("CenterDevice status is {:?}.", status.Status));
msgln(format!("+ Rest: {:?}", status.Rest.Status));
msgln(format!("+ Auth: {:?}", status.Auth.Status));
msgln(format!("+ WebClient: {:?}", status.WebClient.Status));
msgln(format!("+ PublicLink: {:?}", status.PublicLink.Status));
msgln(format!("+ DistributorConsole: {:?}", status.DistributorConsole.Status));
msgln(format!("+ PingDom: {:?}", status.PingDom.Status));
}
}
Ok(())
}
|
random_line_split
|
|
basic.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and
//! position, how to add a `button` to this `window` and how to connect signals with
//! actions.
extern crate gio;
extern crate gtk;
use gio::prelude::*;
use gtk::prelude::*;
use std::env::args;
fn
|
(application: >k::Application) {
let window = gtk::ApplicationWindow::new(application);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
let button = gtk::Button::with_label("Click me!");
window.add(&button);
window.show_all();
}
fn main() {
let application =
gtk::Application::new(Some("com.github.gtk-rs.examples.basic"), Default::default())
.expect("Initialization failed...");
application.connect_activate(|app| {
build_ui(app);
});
application.run(&args().collect::<Vec<_>>());
}
|
build_ui
|
identifier_name
|
basic.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and
//! position, how to add a `button` to this `window` and how to connect signals with
//! actions.
extern crate gio;
extern crate gtk;
use gio::prelude::*;
use gtk::prelude::*;
use std::env::args;
fn build_ui(application: >k::Application) {
let window = gtk::ApplicationWindow::new(application);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
let button = gtk::Button::with_label("Click me!");
window.add(&button);
window.show_all();
}
fn main()
|
{
let application =
gtk::Application::new(Some("com.github.gtk-rs.examples.basic"), Default::default())
.expect("Initialization failed...");
application.connect_activate(|app| {
build_ui(app);
});
application.run(&args().collect::<Vec<_>>());
}
|
identifier_body
|
|
basic.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and
//! position, how to add a `button` to this `window` and how to connect signals with
//! actions.
extern crate gio;
extern crate gtk;
use gio::prelude::*;
use gtk::prelude::*;
use std::env::args;
fn build_ui(application: >k::Application) {
let window = gtk::ApplicationWindow::new(application);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
let button = gtk::Button::with_label("Click me!");
window.add(&button);
window.show_all();
}
fn main() {
let application =
gtk::Application::new(Some("com.github.gtk-rs.examples.basic"), Default::default())
.expect("Initialization failed...");
application.connect_activate(|app| {
build_ui(app);
});
|
}
|
application.run(&args().collect::<Vec<_>>());
|
random_line_split
|
issue-11881.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.
#![feature(old_orphan_check)]
extern crate rbml;
extern crate serialize;
use std::io::Cursor;
use std::io::prelude::*;
use std::fmt;
use std::slice;
use serialize::{Encodable, Encoder};
use serialize::json;
use rbml::writer;
#[derive(Encodable)]
struct Foo {
baz: bool,
}
#[derive(Encodable)]
struct Bar {
froboz: uint,
}
enum WireProtocol {
|
JSON,
RBML,
//...
}
fn encode_json<T: Encodable>(val: &T, wr: &mut Cursor<Vec<u8>>) {
write!(wr, "{}", json::as_json(val));
}
fn encode_rbml<T: Encodable>(val: &T, wr: &mut Cursor<Vec<u8>>) {
let mut encoder = writer::Encoder::new(wr);
val.encode(&mut encoder);
}
pub fn main() {
let target = Foo{baz: false,};
let mut wr = Cursor::new(Vec::new());
let proto = WireProtocol::JSON;
match proto {
WireProtocol::JSON => encode_json(&target, &mut wr),
WireProtocol::RBML => encode_rbml(&target, &mut wr)
}
}
|
random_line_split
|
|
issue-11881.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.
#![feature(old_orphan_check)]
extern crate rbml;
extern crate serialize;
use std::io::Cursor;
use std::io::prelude::*;
use std::fmt;
use std::slice;
use serialize::{Encodable, Encoder};
use serialize::json;
use rbml::writer;
#[derive(Encodable)]
struct Foo {
baz: bool,
}
#[derive(Encodable)]
struct Bar {
froboz: uint,
}
enum
|
{
JSON,
RBML,
//...
}
fn encode_json<T: Encodable>(val: &T, wr: &mut Cursor<Vec<u8>>) {
write!(wr, "{}", json::as_json(val));
}
fn encode_rbml<T: Encodable>(val: &T, wr: &mut Cursor<Vec<u8>>) {
let mut encoder = writer::Encoder::new(wr);
val.encode(&mut encoder);
}
pub fn main() {
let target = Foo{baz: false,};
let mut wr = Cursor::new(Vec::new());
let proto = WireProtocol::JSON;
match proto {
WireProtocol::JSON => encode_json(&target, &mut wr),
WireProtocol::RBML => encode_rbml(&target, &mut wr)
}
}
|
WireProtocol
|
identifier_name
|
test_cargo_freshness.rs
|
use std::io::{fs, File};
use support::{project, execs, path2url};
use support::{COMPILING, cargo_dir, ResultTest};
use support::paths::PathExt;
use hamcrest::{assert_that, existing_file};
fn setup()
|
test!(modifying_and_moving {
let p = project("foo")
.file("Cargo.toml", r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
"#)
.file("src/main.rs", r#"
mod a; fn main() {}
"#)
.file("src/a.rs", "");
assert_that(p.cargo_process("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(0).with_stdout(""));
p.root().move_into_the_past().assert();
File::create(&p.root().join("src/a.rs")).write_str("fn main() {}").assert();
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
fs::rename(&p.root().join("src/a.rs"), &p.root().join("src/b.rs")).assert();
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(101));
})
test!(modify_only_some_files {
let p = project("foo")
.file("Cargo.toml", r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
"#)
.file("src/lib.rs", "mod a;")
.file("src/a.rs", "")
.file("src/main.rs", r#"
mod b;
fn main() {}
"#)
.file("src/b.rs", "")
.file("tests/test.rs", "");
assert_that(p.cargo_process("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(p.process(cargo_dir().join("cargo")).arg("test"),
execs().with_status(0));
assert_that(&p.bin("foo"), existing_file());
let lib = p.root().join("src/lib.rs");
let bin = p.root().join("src/b.rs");
File::create(&lib).write_str("invalid rust code").assert();
lib.move_into_the_past().assert();
p.root().move_into_the_past().assert();
File::create(&bin).write_str("fn foo() {}").assert();
// Make sure the binary is rebuilt, not the lib
assert_that(p.process(cargo_dir().join("cargo")).arg("build")
.env("RUST_LOG", Some("cargo::ops::cargo_rustc::fingerprint")),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(&p.bin("foo"), existing_file());
})
|
{}
|
identifier_body
|
test_cargo_freshness.rs
|
use std::io::{fs, File};
use support::{project, execs, path2url};
use support::{COMPILING, cargo_dir, ResultTest};
use support::paths::PathExt;
use hamcrest::{assert_that, existing_file};
fn setup() {}
test!(modifying_and_moving {
let p = project("foo")
.file("Cargo.toml", r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
"#)
.file("src/main.rs", r#"
mod a; fn main() {}
"#)
.file("src/a.rs", "");
assert_that(p.cargo_process("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(0).with_stdout(""));
p.root().move_into_the_past().assert();
File::create(&p.root().join("src/a.rs")).write_str("fn main() {}").assert();
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
fs::rename(&p.root().join("src/a.rs"), &p.root().join("src/b.rs")).assert();
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(101));
})
test!(modify_only_some_files {
let p = project("foo")
.file("Cargo.toml", r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
"#)
.file("src/lib.rs", "mod a;")
.file("src/a.rs", "")
|
"#)
.file("src/b.rs", "")
.file("tests/test.rs", "");
assert_that(p.cargo_process("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(p.process(cargo_dir().join("cargo")).arg("test"),
execs().with_status(0));
assert_that(&p.bin("foo"), existing_file());
let lib = p.root().join("src/lib.rs");
let bin = p.root().join("src/b.rs");
File::create(&lib).write_str("invalid rust code").assert();
lib.move_into_the_past().assert();
p.root().move_into_the_past().assert();
File::create(&bin).write_str("fn foo() {}").assert();
// Make sure the binary is rebuilt, not the lib
assert_that(p.process(cargo_dir().join("cargo")).arg("build")
.env("RUST_LOG", Some("cargo::ops::cargo_rustc::fingerprint")),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(&p.bin("foo"), existing_file());
})
|
.file("src/main.rs", r#"
mod b;
fn main() {}
|
random_line_split
|
test_cargo_freshness.rs
|
use std::io::{fs, File};
use support::{project, execs, path2url};
use support::{COMPILING, cargo_dir, ResultTest};
use support::paths::PathExt;
use hamcrest::{assert_that, existing_file};
fn
|
() {}
test!(modifying_and_moving {
let p = project("foo")
.file("Cargo.toml", r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
"#)
.file("src/main.rs", r#"
mod a; fn main() {}
"#)
.file("src/a.rs", "");
assert_that(p.cargo_process("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(0).with_stdout(""));
p.root().move_into_the_past().assert();
File::create(&p.root().join("src/a.rs")).write_str("fn main() {}").assert();
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
fs::rename(&p.root().join("src/a.rs"), &p.root().join("src/b.rs")).assert();
assert_that(p.process(cargo_dir().join("cargo")).arg("build"),
execs().with_status(101));
})
test!(modify_only_some_files {
let p = project("foo")
.file("Cargo.toml", r#"
[package]
name = "foo"
authors = []
version = "0.0.1"
"#)
.file("src/lib.rs", "mod a;")
.file("src/a.rs", "")
.file("src/main.rs", r#"
mod b;
fn main() {}
"#)
.file("src/b.rs", "")
.file("tests/test.rs", "");
assert_that(p.cargo_process("build"),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(p.process(cargo_dir().join("cargo")).arg("test"),
execs().with_status(0));
assert_that(&p.bin("foo"), existing_file());
let lib = p.root().join("src/lib.rs");
let bin = p.root().join("src/b.rs");
File::create(&lib).write_str("invalid rust code").assert();
lib.move_into_the_past().assert();
p.root().move_into_the_past().assert();
File::create(&bin).write_str("fn foo() {}").assert();
// Make sure the binary is rebuilt, not the lib
assert_that(p.process(cargo_dir().join("cargo")).arg("build")
.env("RUST_LOG", Some("cargo::ops::cargo_rustc::fingerprint")),
execs().with_status(0).with_stdout(format!("\
{compiling} foo v0.0.1 ({dir})
", compiling = COMPILING, dir = path2url(p.root()))));
assert_that(&p.bin("foo"), existing_file());
})
|
setup
|
identifier_name
|
lib.rs
|
extern crate natural_constants;
#[test]
fn test_math() {
use natural_constants::math::*;
println!("{}", golden_ratio)
}
#[test]
fn test_conversion() {
use natural_constants::conversion::*;
let mass_in_g = 50_000.0; // 50 kg
assert_eq!(to_kilo(mass_in_g), 50.0);
assert_eq!(from_kilo(50.0), mass_in_g);
let energy_in_j = 125_000_000.0; // 125 MJoule
assert_eq!(to_mega(energy_in_j), 125.0);
assert_eq!(from_mega(125.0), energy_in_j);
let file_size_in_bytes1 = 73_000_000_000.0; // 74 gigabytes (not gibibytes)
assert_eq!(to_giga(file_size_in_bytes1), 73.0);
|
let file_size_in_bytes2 = 312_000_000_000_000.0; // 312 terabytes (not tebibytes)
assert_eq!(to_tera(file_size_in_bytes2), 312.0);
assert_eq!(from_tera(312.0), file_size_in_bytes2);
let force_in_kn = 780.23; // kilo newton
assert_eq!(kilo_to_mega(force_in_kn), 0.78023);
assert_eq!(mega_to_kilo(0.78023), force_in_kn);
let temp_in_kelvin = 1.0;
assert_eq!(kelvin_to_deg_cel(temp_in_kelvin), -272.15);
assert_eq!(deg_cel_to_kelvin(-272.15), temp_in_kelvin);
}
#[test]
fn limits() {
use natural_constants::math::*;
assert_eq!(golden_ratio, (1.0 + 5.0_f64.sqrt())/2.0);
}
|
assert_eq!(from_giga(73.0), file_size_in_bytes1);
|
random_line_split
|
lib.rs
|
extern crate natural_constants;
#[test]
fn test_math() {
use natural_constants::math::*;
println!("{}", golden_ratio)
}
#[test]
fn test_conversion() {
use natural_constants::conversion::*;
let mass_in_g = 50_000.0; // 50 kg
assert_eq!(to_kilo(mass_in_g), 50.0);
assert_eq!(from_kilo(50.0), mass_in_g);
let energy_in_j = 125_000_000.0; // 125 MJoule
assert_eq!(to_mega(energy_in_j), 125.0);
assert_eq!(from_mega(125.0), energy_in_j);
let file_size_in_bytes1 = 73_000_000_000.0; // 74 gigabytes (not gibibytes)
assert_eq!(to_giga(file_size_in_bytes1), 73.0);
assert_eq!(from_giga(73.0), file_size_in_bytes1);
let file_size_in_bytes2 = 312_000_000_000_000.0; // 312 terabytes (not tebibytes)
assert_eq!(to_tera(file_size_in_bytes2), 312.0);
assert_eq!(from_tera(312.0), file_size_in_bytes2);
let force_in_kn = 780.23; // kilo newton
assert_eq!(kilo_to_mega(force_in_kn), 0.78023);
assert_eq!(mega_to_kilo(0.78023), force_in_kn);
let temp_in_kelvin = 1.0;
assert_eq!(kelvin_to_deg_cel(temp_in_kelvin), -272.15);
assert_eq!(deg_cel_to_kelvin(-272.15), temp_in_kelvin);
}
#[test]
fn limits()
|
{
use natural_constants::math::*;
assert_eq!(golden_ratio, (1.0 + 5.0_f64.sqrt())/2.0);
}
|
identifier_body
|
|
lib.rs
|
extern crate natural_constants;
#[test]
fn test_math() {
use natural_constants::math::*;
println!("{}", golden_ratio)
}
#[test]
fn
|
() {
use natural_constants::conversion::*;
let mass_in_g = 50_000.0; // 50 kg
assert_eq!(to_kilo(mass_in_g), 50.0);
assert_eq!(from_kilo(50.0), mass_in_g);
let energy_in_j = 125_000_000.0; // 125 MJoule
assert_eq!(to_mega(energy_in_j), 125.0);
assert_eq!(from_mega(125.0), energy_in_j);
let file_size_in_bytes1 = 73_000_000_000.0; // 74 gigabytes (not gibibytes)
assert_eq!(to_giga(file_size_in_bytes1), 73.0);
assert_eq!(from_giga(73.0), file_size_in_bytes1);
let file_size_in_bytes2 = 312_000_000_000_000.0; // 312 terabytes (not tebibytes)
assert_eq!(to_tera(file_size_in_bytes2), 312.0);
assert_eq!(from_tera(312.0), file_size_in_bytes2);
let force_in_kn = 780.23; // kilo newton
assert_eq!(kilo_to_mega(force_in_kn), 0.78023);
assert_eq!(mega_to_kilo(0.78023), force_in_kn);
let temp_in_kelvin = 1.0;
assert_eq!(kelvin_to_deg_cel(temp_in_kelvin), -272.15);
assert_eq!(deg_cel_to_kelvin(-272.15), temp_in_kelvin);
}
#[test]
fn limits() {
use natural_constants::math::*;
assert_eq!(golden_ratio, (1.0 + 5.0_f64.sqrt())/2.0);
}
|
test_conversion
|
identifier_name
|
unboxed-closures-call-sugar-object.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn make_adder(x: isize) -> Box<FnMut(isize)->isize +'static> {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
Box::new(move |y| { x + y })
}
pub fn
|
() {
let mut adder = make_adder(3);
let z = (*adder)(2);
println!("{}", z);
assert_eq!(z, 5);
}
|
main
|
identifier_name
|
unboxed-closures-call-sugar-object.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn make_adder(x: isize) -> Box<FnMut(isize)->isize +'static> {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
Box::new(move |y| { x + y })
}
pub fn main() {
let mut adder = make_adder(3);
|
println!("{}", z);
assert_eq!(z, 5);
}
|
let z = (*adder)(2);
|
random_line_split
|
unboxed-closures-call-sugar-object.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn make_adder(x: isize) -> Box<FnMut(isize)->isize +'static>
|
pub fn main() {
let mut adder = make_adder(3);
let z = (*adder)(2);
println!("{}", z);
assert_eq!(z, 5);
}
|
{
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
Box::new(move |y| { x + y })
}
|
identifier_body
|
lint-output-format-2.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.
// aux-build:lint_output_format.rs
#![feature(unstable_test_feature)]
// compile-pass
extern crate lint_output_format;
use lint_output_format::{foo, bar};
//~^ WARNING use of deprecated item 'lint_output_format::foo': text
fn main()
|
{
let _x = foo();
//~^ WARNING use of deprecated item 'lint_output_format::foo': text
let _y = bar();
}
|
identifier_body
|
|
lint-output-format-2.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.
// aux-build:lint_output_format.rs
#![feature(unstable_test_feature)]
// compile-pass
extern crate lint_output_format;
use lint_output_format::{foo, bar};
//~^ WARNING use of deprecated item 'lint_output_format::foo': text
fn
|
() {
let _x = foo();
//~^ WARNING use of deprecated item 'lint_output_format::foo': text
let _y = bar();
}
|
main
|
identifier_name
|
lint-output-format-2.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.
// aux-build:lint_output_format.rs
#![feature(unstable_test_feature)]
|
//~^ WARNING use of deprecated item 'lint_output_format::foo': text
fn main() {
let _x = foo();
//~^ WARNING use of deprecated item 'lint_output_format::foo': text
let _y = bar();
}
|
// compile-pass
extern crate lint_output_format;
use lint_output_format::{foo, bar};
|
random_line_split
|
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
#[derive(PartialEq, Clone, PartialOrd, Eq, Ord, Debug, Deserialize, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
self.0.send(msg).unwrap();
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(PartialEq, Clone, Copy, PartialOrd, Eq, Ord, Deserialize, Serialize, Debug, Hash)]
pub enum ProfilerCategory {
Compositing,
LayoutPerform,
LayoutStyleRecalc,
LayoutTextShaping,
LayoutRestyleDamagePropagation,
LayoutNonIncrementalReset,
LayoutSelectorMatch,
LayoutTreeBuilder,
LayoutDamagePropagate,
LayoutGeneratedContent,
LayoutDisplayListSorting,
LayoutFloatPlacementSpeculation,
LayoutMain,
LayoutStoreOverflow,
LayoutParallelWarmup,
LayoutDispListBuild,
NetHTTPRequestResponse,
PaintingPerTile,
PaintingPrepBuff,
Painting,
ImageDecoding,
ImageSaving,
ScriptAttachLayout,
ScriptConstellationMsg,
ScriptDevtoolsMsg,
ScriptDocumentEvent,
ScriptDomEvent,
ScriptEvaluate,
ScriptEvent,
ScriptFileRead,
ScriptImageCacheMsg,
ScriptInputEvent,
ScriptNetworkEvent,
ScriptParseHTML,
ScriptPlannedNavigation,
ScriptResize,
ScriptSetViewport,
ScriptTimerEvent,
ScriptStylesheetLoad,
ScriptUpdateReplacedElement,
ScriptWebSocketEvent,
ScriptWorkerEvent,
ApplicationHeartbeat,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum
|
{
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T
{
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
send_profile_data(category,
meta,
profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
|
TimerMetadataReflowType
|
identifier_name
|
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
#[derive(PartialEq, Clone, PartialOrd, Eq, Ord, Debug, Deserialize, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg) {
self.0.send(msg).unwrap();
}
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(PartialEq, Clone, Copy, PartialOrd, Eq, Ord, Deserialize, Serialize, Debug, Hash)]
pub enum ProfilerCategory {
Compositing,
LayoutPerform,
LayoutStyleRecalc,
LayoutTextShaping,
LayoutRestyleDamagePropagation,
LayoutNonIncrementalReset,
LayoutSelectorMatch,
LayoutTreeBuilder,
LayoutDamagePropagate,
LayoutGeneratedContent,
LayoutDisplayListSorting,
LayoutFloatPlacementSpeculation,
LayoutMain,
LayoutStoreOverflow,
LayoutParallelWarmup,
LayoutDispListBuild,
NetHTTPRequestResponse,
PaintingPerTile,
PaintingPrepBuff,
Painting,
ImageDecoding,
ImageSaving,
ScriptAttachLayout,
ScriptConstellationMsg,
ScriptDevtoolsMsg,
ScriptDocumentEvent,
ScriptDomEvent,
ScriptEvaluate,
ScriptEvent,
ScriptFileRead,
ScriptImageCacheMsg,
ScriptInputEvent,
ScriptNetworkEvent,
ScriptParseHTML,
ScriptPlannedNavigation,
ScriptResize,
ScriptSetViewport,
ScriptTimerEvent,
ScriptStylesheetLoad,
ScriptUpdateReplacedElement,
ScriptWebSocketEvent,
ScriptWorkerEvent,
ApplicationHeartbeat,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
|
where F: FnOnce() -> T
{
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
send_profile_data(category,
meta,
profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
|
random_line_split
|
|
time.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/. */
extern crate time as std_time;
use energy::read_energy_uj;
use ipc_channel::ipc::IpcSender;
use self::std_time::precise_time_ns;
#[derive(PartialEq, Clone, PartialOrd, Eq, Ord, Debug, Deserialize, Serialize)]
pub struct TimerMetadata {
pub url: String,
pub iframe: TimerMetadataFrameType,
pub incremental: TimerMetadataReflowType,
}
#[derive(Clone, Deserialize, Serialize)]
pub struct ProfilerChan(pub IpcSender<ProfilerMsg>);
impl ProfilerChan {
pub fn send(&self, msg: ProfilerMsg)
|
}
#[derive(Clone, Deserialize, Serialize)]
pub enum ProfilerMsg {
/// Normal message used for reporting time
Time((ProfilerCategory, Option<TimerMetadata>), (u64, u64), (u64, u64)),
/// Message used to force print the profiling metrics
Print,
/// Tells the profiler to shut down.
Exit(IpcSender<()>),
}
#[repr(u32)]
#[derive(PartialEq, Clone, Copy, PartialOrd, Eq, Ord, Deserialize, Serialize, Debug, Hash)]
pub enum ProfilerCategory {
Compositing,
LayoutPerform,
LayoutStyleRecalc,
LayoutTextShaping,
LayoutRestyleDamagePropagation,
LayoutNonIncrementalReset,
LayoutSelectorMatch,
LayoutTreeBuilder,
LayoutDamagePropagate,
LayoutGeneratedContent,
LayoutDisplayListSorting,
LayoutFloatPlacementSpeculation,
LayoutMain,
LayoutStoreOverflow,
LayoutParallelWarmup,
LayoutDispListBuild,
NetHTTPRequestResponse,
PaintingPerTile,
PaintingPrepBuff,
Painting,
ImageDecoding,
ImageSaving,
ScriptAttachLayout,
ScriptConstellationMsg,
ScriptDevtoolsMsg,
ScriptDocumentEvent,
ScriptDomEvent,
ScriptEvaluate,
ScriptEvent,
ScriptFileRead,
ScriptImageCacheMsg,
ScriptInputEvent,
ScriptNetworkEvent,
ScriptParseHTML,
ScriptPlannedNavigation,
ScriptResize,
ScriptSetViewport,
ScriptTimerEvent,
ScriptStylesheetLoad,
ScriptUpdateReplacedElement,
ScriptWebSocketEvent,
ScriptWorkerEvent,
ApplicationHeartbeat,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataFrameType {
RootWindow,
IFrame,
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
pub enum TimerMetadataReflowType {
Incremental,
FirstReflow,
}
pub fn profile<T, F>(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
callback: F)
-> T
where F: FnOnce() -> T
{
let start_energy = read_energy_uj();
let start_time = precise_time_ns();
let val = callback();
let end_time = precise_time_ns();
let end_energy = read_energy_uj();
send_profile_data(category,
meta,
profiler_chan,
start_time,
end_time,
start_energy,
end_energy);
val
}
pub fn send_profile_data(category: ProfilerCategory,
meta: Option<TimerMetadata>,
profiler_chan: ProfilerChan,
start_time: u64,
end_time: u64,
start_energy: u64,
end_energy: u64) {
profiler_chan.send(ProfilerMsg::Time((category, meta),
(start_time, end_time),
(start_energy, end_energy)));
}
|
{
self.0.send(msg).unwrap();
}
|
identifier_body
|
util.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
client_extensions::CLIENT_EXTENSION_DIRECTIVE_NAME,
connections::ConnectionMetadataDirective,
handle_fields::HANDLE_FIELD_DIRECTIVE_NAME,
inline_data_fragment::InlineDirectiveMetadata,
react_flight::REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
refetchable_fragment::RefetchableMetadata,
relay_actor_change::RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
required_directive::{CHILDREN_CAN_BUBBLE_METADATA_KEY, REQUIRED_DIRECTIVE_NAME},
ModuleMetadata, ReactFlightLocalComponentsMetadata, RefetchableDerivedFromMetadata,
RelayClientComponentMetadata, RelayResolverSpreadMetadata, RequiredMetadataDirective,
CLIENT_EDGE_GENERATED_FRAGMENT_KEY, CLIENT_EDGE_METADATA_KEY, CLIENT_EDGE_QUERY_METADATA_KEY,
DIRECTIVE_SPLIT_OPERATION, INTERNAL_METADATA_DIRECTIVE,
};
use graphql_ir::{
Argument, Directive, ProvidedVariableMetadata, Value, ARGUMENT_DEFINITION,
UNUSED_LOCAL_VARIABLE_DEPRECATED,
};
use intern::string_key::{Intern, StringKey};
use lazy_static::lazy_static;
use regex::Regex;
use schema::{SDLSchema, Schema, Type};
// A wrapper type that allows comparing pointer equality of references. Two
// `PointerAddress` values are equal if they point to the same memory location.
//
// This type is _sound_, but misuse can easily lead to logical bugs if the memory
// of one PointerAddress could not have been freed and reused for a subsequent
// PointerAddress.
#[derive(Hash, Eq, PartialEq, Clone, Copy)]
pub struct PointerAddress(usize);
impl PointerAddress {
pub fn new<T>(ptr: &T) -> Self {
let ptr_address: usize = unsafe { std::mem::transmute(ptr) };
Self(ptr_address)
}
}
/// This function will return a new Vec[...] of directives,
/// where one will be missing. The one with `remove_directive_name` name
pub fn remove_directive(
directives: &[Directive],
remove_directive_name: StringKey,
) -> Vec<Directive> {
let mut next_directives = Vec::with_capacity(directives.len() - 1);
for directive in directives {
if directive.name.item!= remove_directive_name {
next_directives.push(directive.clone());
}
}
next_directives
}
/// Function will create a new Vec[...] of directives
/// when one of them will be replaced with the `replacement`. If the name of
/// `replacement` is matched with the item in the list
pub fn replace_directive(directives: &[Directive], replacement: Directive) -> Vec<Directive> {
directives
.iter()
.map(|directive| {
if directive.name.item == replacement.name.item {
return replacement.to_owned();
}
directive.to_owned()
})
.collect()
}
/// The function that will return a variable name for an argument
/// it it uses a variable (and it the argument is available)
pub fn extract_variable_name(argument: Option<&Argument>) -> Option<StringKey> {
match argument {
Some(arg) => match &arg.value.item {
Value::Variable(var) => Some(var.name.item),
_ => None,
},
None => None,
}
}
lazy_static! {
static ref CUSTOM_METADATA_DIRECTIVES: [StringKey; 22] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
*DIRECTIVE_SPLIT_OPERATION,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RequiredMetadataDirective::directive_name(),
*CLIENT_EDGE_METADATA_KEY,
*CLIENT_EDGE_QUERY_METADATA_KEY,
*CLIENT_EDGE_GENERATED_FRAGMENT_KEY,
*CHILDREN_CAN_BUBBLE_METADATA_KEY,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
*UNUSED_LOCAL_VARIABLE_DEPRECATED,
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
ProvidedVariableMetadata::directive_name(),
];
static ref DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER: [StringKey; 12] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
];
static ref RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES: [StringKey; 6] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
InlineDirectiveMetadata::directive_name(),
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
*CLIENT_EDGE_METADATA_KEY,
"defer".intern(),
];
static ref VALID_PROVIDED_VARIABLE_NAME: Regex = Regex::new(r#"^[A-Za-z0-9_]*$"#).unwrap();
pub static ref INTERNAL_RELAY_VARIABLES_PREFIX: StringKey = "__relay_internal".intern();
}
pub struct CustomMetadataDirectives;
impl CustomMetadataDirectives {
pub fn is_custom_metadata_directive(name: StringKey) -> bool {
CUSTOM_METADATA_DIRECTIVES.contains(&name)
}
pub fn should_skip_in_node_identifier(name: StringKey) -> bool {
DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER.contains(&name)
}
pub fn is_handle_field_directive(name: StringKey) -> bool {
name == *HANDLE_FIELD_DIRECTIVE_NAME
}
}
pub fn is_relay_custom_inline_fragment_directive(directive: &Directive) -> bool {
RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES.contains(&directive.name.item)
}
pub fn generate_abstract_type_refinement_key(schema: &SDLSchema, type_: Type) -> StringKey {
format!("__is{}", schema.get_type_name(type_).lookup()).intern()
}
pub fn get_normalization_operation_name(name: StringKey) -> String {
format!("{}$normalization", name)
}
pub fn get_fragment_filename(fragment_name: StringKey) -> StringKey
|
pub fn format_provided_variable_name(module_name: StringKey) -> StringKey {
if VALID_PROVIDED_VARIABLE_NAME.is_match(module_name.lookup()) {
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX,
module_name.lookup()
)
.intern()
} else {
let transformed_name = module_name
.lookup()
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect::<String>();
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX, transformed_name
)
.intern()
}
}
|
{
format!(
"{}.graphql",
get_normalization_operation_name(fragment_name)
)
.intern()
}
|
identifier_body
|
util.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
client_extensions::CLIENT_EXTENSION_DIRECTIVE_NAME,
connections::ConnectionMetadataDirective,
handle_fields::HANDLE_FIELD_DIRECTIVE_NAME,
inline_data_fragment::InlineDirectiveMetadata,
react_flight::REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
refetchable_fragment::RefetchableMetadata,
relay_actor_change::RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
required_directive::{CHILDREN_CAN_BUBBLE_METADATA_KEY, REQUIRED_DIRECTIVE_NAME},
ModuleMetadata, ReactFlightLocalComponentsMetadata, RefetchableDerivedFromMetadata,
RelayClientComponentMetadata, RelayResolverSpreadMetadata, RequiredMetadataDirective,
CLIENT_EDGE_GENERATED_FRAGMENT_KEY, CLIENT_EDGE_METADATA_KEY, CLIENT_EDGE_QUERY_METADATA_KEY,
DIRECTIVE_SPLIT_OPERATION, INTERNAL_METADATA_DIRECTIVE,
};
use graphql_ir::{
Argument, Directive, ProvidedVariableMetadata, Value, ARGUMENT_DEFINITION,
UNUSED_LOCAL_VARIABLE_DEPRECATED,
};
use intern::string_key::{Intern, StringKey};
use lazy_static::lazy_static;
use regex::Regex;
use schema::{SDLSchema, Schema, Type};
// A wrapper type that allows comparing pointer equality of references. Two
// `PointerAddress` values are equal if they point to the same memory location.
//
// This type is _sound_, but misuse can easily lead to logical bugs if the memory
// of one PointerAddress could not have been freed and reused for a subsequent
// PointerAddress.
#[derive(Hash, Eq, PartialEq, Clone, Copy)]
pub struct PointerAddress(usize);
impl PointerAddress {
pub fn new<T>(ptr: &T) -> Self {
let ptr_address: usize = unsafe { std::mem::transmute(ptr) };
Self(ptr_address)
}
}
/// This function will return a new Vec[...] of directives,
/// where one will be missing. The one with `remove_directive_name` name
pub fn remove_directive(
directives: &[Directive],
remove_directive_name: StringKey,
) -> Vec<Directive> {
let mut next_directives = Vec::with_capacity(directives.len() - 1);
for directive in directives {
if directive.name.item!= remove_directive_name {
next_directives.push(directive.clone());
}
}
next_directives
}
/// Function will create a new Vec[...] of directives
/// when one of them will be replaced with the `replacement`. If the name of
/// `replacement` is matched with the item in the list
pub fn replace_directive(directives: &[Directive], replacement: Directive) -> Vec<Directive> {
directives
.iter()
.map(|directive| {
if directive.name.item == replacement.name.item {
return replacement.to_owned();
}
directive.to_owned()
})
.collect()
}
/// The function that will return a variable name for an argument
/// it it uses a variable (and it the argument is available)
pub fn extract_variable_name(argument: Option<&Argument>) -> Option<StringKey> {
match argument {
Some(arg) => match &arg.value.item {
Value::Variable(var) => Some(var.name.item),
_ => None,
},
None => None,
}
}
lazy_static! {
static ref CUSTOM_METADATA_DIRECTIVES: [StringKey; 22] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
*DIRECTIVE_SPLIT_OPERATION,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RequiredMetadataDirective::directive_name(),
*CLIENT_EDGE_METADATA_KEY,
*CLIENT_EDGE_QUERY_METADATA_KEY,
*CLIENT_EDGE_GENERATED_FRAGMENT_KEY,
*CHILDREN_CAN_BUBBLE_METADATA_KEY,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
*UNUSED_LOCAL_VARIABLE_DEPRECATED,
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
ProvidedVariableMetadata::directive_name(),
];
static ref DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER: [StringKey; 12] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
];
static ref RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES: [StringKey; 6] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
InlineDirectiveMetadata::directive_name(),
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
*CLIENT_EDGE_METADATA_KEY,
"defer".intern(),
];
static ref VALID_PROVIDED_VARIABLE_NAME: Regex = Regex::new(r#"^[A-Za-z0-9_]*$"#).unwrap();
pub static ref INTERNAL_RELAY_VARIABLES_PREFIX: StringKey = "__relay_internal".intern();
}
pub struct CustomMetadataDirectives;
impl CustomMetadataDirectives {
pub fn is_custom_metadata_directive(name: StringKey) -> bool {
CUSTOM_METADATA_DIRECTIVES.contains(&name)
}
pub fn should_skip_in_node_identifier(name: StringKey) -> bool {
DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER.contains(&name)
}
pub fn is_handle_field_directive(name: StringKey) -> bool {
name == *HANDLE_FIELD_DIRECTIVE_NAME
}
}
pub fn is_relay_custom_inline_fragment_directive(directive: &Directive) -> bool {
RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES.contains(&directive.name.item)
}
pub fn generate_abstract_type_refinement_key(schema: &SDLSchema, type_: Type) -> StringKey {
format!("__is{}", schema.get_type_name(type_).lookup()).intern()
}
pub fn get_normalization_operation_name(name: StringKey) -> String {
format!("{}$normalization", name)
}
pub fn get_fragment_filename(fragment_name: StringKey) -> StringKey {
format!(
"{}.graphql",
get_normalization_operation_name(fragment_name)
)
.intern()
}
pub fn format_provided_variable_name(module_name: StringKey) -> StringKey {
if VALID_PROVIDED_VARIABLE_NAME.is_match(module_name.lookup()) {
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX,
module_name.lookup()
)
.intern()
} else
|
}
|
{
let transformed_name = module_name
.lookup()
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect::<String>();
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX, transformed_name
)
.intern()
}
|
conditional_block
|
util.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
client_extensions::CLIENT_EXTENSION_DIRECTIVE_NAME,
connections::ConnectionMetadataDirective,
handle_fields::HANDLE_FIELD_DIRECTIVE_NAME,
inline_data_fragment::InlineDirectiveMetadata,
react_flight::REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
refetchable_fragment::RefetchableMetadata,
relay_actor_change::RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
required_directive::{CHILDREN_CAN_BUBBLE_METADATA_KEY, REQUIRED_DIRECTIVE_NAME},
ModuleMetadata, ReactFlightLocalComponentsMetadata, RefetchableDerivedFromMetadata,
RelayClientComponentMetadata, RelayResolverSpreadMetadata, RequiredMetadataDirective,
CLIENT_EDGE_GENERATED_FRAGMENT_KEY, CLIENT_EDGE_METADATA_KEY, CLIENT_EDGE_QUERY_METADATA_KEY,
DIRECTIVE_SPLIT_OPERATION, INTERNAL_METADATA_DIRECTIVE,
};
use graphql_ir::{
Argument, Directive, ProvidedVariableMetadata, Value, ARGUMENT_DEFINITION,
UNUSED_LOCAL_VARIABLE_DEPRECATED,
};
use intern::string_key::{Intern, StringKey};
use lazy_static::lazy_static;
use regex::Regex;
use schema::{SDLSchema, Schema, Type};
// A wrapper type that allows comparing pointer equality of references. Two
// `PointerAddress` values are equal if they point to the same memory location.
//
// This type is _sound_, but misuse can easily lead to logical bugs if the memory
// of one PointerAddress could not have been freed and reused for a subsequent
// PointerAddress.
#[derive(Hash, Eq, PartialEq, Clone, Copy)]
pub struct PointerAddress(usize);
impl PointerAddress {
pub fn new<T>(ptr: &T) -> Self {
let ptr_address: usize = unsafe { std::mem::transmute(ptr) };
Self(ptr_address)
}
}
/// This function will return a new Vec[...] of directives,
/// where one will be missing. The one with `remove_directive_name` name
pub fn
|
(
directives: &[Directive],
remove_directive_name: StringKey,
) -> Vec<Directive> {
let mut next_directives = Vec::with_capacity(directives.len() - 1);
for directive in directives {
if directive.name.item!= remove_directive_name {
next_directives.push(directive.clone());
}
}
next_directives
}
/// Function will create a new Vec[...] of directives
/// when one of them will be replaced with the `replacement`. If the name of
/// `replacement` is matched with the item in the list
pub fn replace_directive(directives: &[Directive], replacement: Directive) -> Vec<Directive> {
directives
.iter()
.map(|directive| {
if directive.name.item == replacement.name.item {
return replacement.to_owned();
}
directive.to_owned()
})
.collect()
}
/// The function that will return a variable name for an argument
/// it it uses a variable (and it the argument is available)
pub fn extract_variable_name(argument: Option<&Argument>) -> Option<StringKey> {
match argument {
Some(arg) => match &arg.value.item {
Value::Variable(var) => Some(var.name.item),
_ => None,
},
None => None,
}
}
lazy_static! {
static ref CUSTOM_METADATA_DIRECTIVES: [StringKey; 22] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
*DIRECTIVE_SPLIT_OPERATION,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RequiredMetadataDirective::directive_name(),
*CLIENT_EDGE_METADATA_KEY,
*CLIENT_EDGE_QUERY_METADATA_KEY,
*CLIENT_EDGE_GENERATED_FRAGMENT_KEY,
*CHILDREN_CAN_BUBBLE_METADATA_KEY,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
*UNUSED_LOCAL_VARIABLE_DEPRECATED,
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
ProvidedVariableMetadata::directive_name(),
];
static ref DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER: [StringKey; 12] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
];
static ref RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES: [StringKey; 6] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
InlineDirectiveMetadata::directive_name(),
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
*CLIENT_EDGE_METADATA_KEY,
"defer".intern(),
];
static ref VALID_PROVIDED_VARIABLE_NAME: Regex = Regex::new(r#"^[A-Za-z0-9_]*$"#).unwrap();
pub static ref INTERNAL_RELAY_VARIABLES_PREFIX: StringKey = "__relay_internal".intern();
}
pub struct CustomMetadataDirectives;
impl CustomMetadataDirectives {
pub fn is_custom_metadata_directive(name: StringKey) -> bool {
CUSTOM_METADATA_DIRECTIVES.contains(&name)
}
pub fn should_skip_in_node_identifier(name: StringKey) -> bool {
DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER.contains(&name)
}
pub fn is_handle_field_directive(name: StringKey) -> bool {
name == *HANDLE_FIELD_DIRECTIVE_NAME
}
}
pub fn is_relay_custom_inline_fragment_directive(directive: &Directive) -> bool {
RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES.contains(&directive.name.item)
}
pub fn generate_abstract_type_refinement_key(schema: &SDLSchema, type_: Type) -> StringKey {
format!("__is{}", schema.get_type_name(type_).lookup()).intern()
}
pub fn get_normalization_operation_name(name: StringKey) -> String {
format!("{}$normalization", name)
}
pub fn get_fragment_filename(fragment_name: StringKey) -> StringKey {
format!(
"{}.graphql",
get_normalization_operation_name(fragment_name)
)
.intern()
}
pub fn format_provided_variable_name(module_name: StringKey) -> StringKey {
if VALID_PROVIDED_VARIABLE_NAME.is_match(module_name.lookup()) {
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX,
module_name.lookup()
)
.intern()
} else {
let transformed_name = module_name
.lookup()
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect::<String>();
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX, transformed_name
)
.intern()
}
}
|
remove_directive
|
identifier_name
|
util.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::{
client_extensions::CLIENT_EXTENSION_DIRECTIVE_NAME,
connections::ConnectionMetadataDirective,
handle_fields::HANDLE_FIELD_DIRECTIVE_NAME,
inline_data_fragment::InlineDirectiveMetadata,
react_flight::REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
refetchable_fragment::RefetchableMetadata,
relay_actor_change::RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
required_directive::{CHILDREN_CAN_BUBBLE_METADATA_KEY, REQUIRED_DIRECTIVE_NAME},
ModuleMetadata, ReactFlightLocalComponentsMetadata, RefetchableDerivedFromMetadata,
RelayClientComponentMetadata, RelayResolverSpreadMetadata, RequiredMetadataDirective,
CLIENT_EDGE_GENERATED_FRAGMENT_KEY, CLIENT_EDGE_METADATA_KEY, CLIENT_EDGE_QUERY_METADATA_KEY,
DIRECTIVE_SPLIT_OPERATION, INTERNAL_METADATA_DIRECTIVE,
};
use graphql_ir::{
Argument, Directive, ProvidedVariableMetadata, Value, ARGUMENT_DEFINITION,
UNUSED_LOCAL_VARIABLE_DEPRECATED,
};
use intern::string_key::{Intern, StringKey};
use lazy_static::lazy_static;
use regex::Regex;
use schema::{SDLSchema, Schema, Type};
// A wrapper type that allows comparing pointer equality of references. Two
// `PointerAddress` values are equal if they point to the same memory location.
//
// This type is _sound_, but misuse can easily lead to logical bugs if the memory
// of one PointerAddress could not have been freed and reused for a subsequent
// PointerAddress.
#[derive(Hash, Eq, PartialEq, Clone, Copy)]
pub struct PointerAddress(usize);
impl PointerAddress {
pub fn new<T>(ptr: &T) -> Self {
let ptr_address: usize = unsafe { std::mem::transmute(ptr) };
Self(ptr_address)
}
}
|
remove_directive_name: StringKey,
) -> Vec<Directive> {
let mut next_directives = Vec::with_capacity(directives.len() - 1);
for directive in directives {
if directive.name.item!= remove_directive_name {
next_directives.push(directive.clone());
}
}
next_directives
}
/// Function will create a new Vec[...] of directives
/// when one of them will be replaced with the `replacement`. If the name of
/// `replacement` is matched with the item in the list
pub fn replace_directive(directives: &[Directive], replacement: Directive) -> Vec<Directive> {
directives
.iter()
.map(|directive| {
if directive.name.item == replacement.name.item {
return replacement.to_owned();
}
directive.to_owned()
})
.collect()
}
/// The function that will return a variable name for an argument
/// it it uses a variable (and it the argument is available)
pub fn extract_variable_name(argument: Option<&Argument>) -> Option<StringKey> {
match argument {
Some(arg) => match &arg.value.item {
Value::Variable(var) => Some(var.name.item),
_ => None,
},
None => None,
}
}
lazy_static! {
static ref CUSTOM_METADATA_DIRECTIVES: [StringKey; 22] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
*DIRECTIVE_SPLIT_OPERATION,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RequiredMetadataDirective::directive_name(),
*CLIENT_EDGE_METADATA_KEY,
*CLIENT_EDGE_QUERY_METADATA_KEY,
*CLIENT_EDGE_GENERATED_FRAGMENT_KEY,
*CHILDREN_CAN_BUBBLE_METADATA_KEY,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
*UNUSED_LOCAL_VARIABLE_DEPRECATED,
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
ProvidedVariableMetadata::directive_name(),
];
static ref DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER: [StringKey; 12] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ConnectionMetadataDirective::directive_name(),
*HANDLE_FIELD_DIRECTIVE_NAME,
RefetchableMetadata::directive_name(),
RefetchableDerivedFromMetadata::directive_name(),
*INTERNAL_METADATA_DIRECTIVE,
*ARGUMENT_DEFINITION,
*REACT_FLIGHT_SCALAR_FLIGHT_FIELD_METADATA_KEY,
ReactFlightLocalComponentsMetadata::directive_name(),
*REQUIRED_DIRECTIVE_NAME,
RelayResolverSpreadMetadata::directive_name(),
RelayClientComponentMetadata::directive_name(),
];
static ref RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES: [StringKey; 6] = [
*CLIENT_EXTENSION_DIRECTIVE_NAME,
ModuleMetadata::directive_name(),
InlineDirectiveMetadata::directive_name(),
*RELAY_ACTOR_CHANGE_DIRECTIVE_FOR_CODEGEN,
*CLIENT_EDGE_METADATA_KEY,
"defer".intern(),
];
static ref VALID_PROVIDED_VARIABLE_NAME: Regex = Regex::new(r#"^[A-Za-z0-9_]*$"#).unwrap();
pub static ref INTERNAL_RELAY_VARIABLES_PREFIX: StringKey = "__relay_internal".intern();
}
pub struct CustomMetadataDirectives;
impl CustomMetadataDirectives {
pub fn is_custom_metadata_directive(name: StringKey) -> bool {
CUSTOM_METADATA_DIRECTIVES.contains(&name)
}
pub fn should_skip_in_node_identifier(name: StringKey) -> bool {
DIRECTIVES_SKIPPED_IN_NODE_IDENTIFIER.contains(&name)
}
pub fn is_handle_field_directive(name: StringKey) -> bool {
name == *HANDLE_FIELD_DIRECTIVE_NAME
}
}
pub fn is_relay_custom_inline_fragment_directive(directive: &Directive) -> bool {
RELAY_CUSTOM_INLINE_FRAGMENT_DIRECTIVES.contains(&directive.name.item)
}
pub fn generate_abstract_type_refinement_key(schema: &SDLSchema, type_: Type) -> StringKey {
format!("__is{}", schema.get_type_name(type_).lookup()).intern()
}
pub fn get_normalization_operation_name(name: StringKey) -> String {
format!("{}$normalization", name)
}
pub fn get_fragment_filename(fragment_name: StringKey) -> StringKey {
format!(
"{}.graphql",
get_normalization_operation_name(fragment_name)
)
.intern()
}
pub fn format_provided_variable_name(module_name: StringKey) -> StringKey {
if VALID_PROVIDED_VARIABLE_NAME.is_match(module_name.lookup()) {
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX,
module_name.lookup()
)
.intern()
} else {
let transformed_name = module_name
.lookup()
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect::<String>();
format!(
"{}__pv__{}",
*INTERNAL_RELAY_VARIABLES_PREFIX, transformed_name
)
.intern()
}
}
|
/// This function will return a new Vec[...] of directives,
/// where one will be missing. The one with `remove_directive_name` name
pub fn remove_directive(
directives: &[Directive],
|
random_line_split
|
tvec.rs
|
at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
use back::abi;
use llvm;
use llvm::ValueRef;
use trans::base::*;
use trans::base;
use trans::build::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::common::*;
use trans::consts;
use trans::datum::*;
use trans::debuginfo::DebugLoc;
use trans::expr::{Dest, Ignore, SaveIn};
use trans::expr;
use trans::machine::llsize_of_alloc;
use trans::type_::Type;
use trans::type_of;
use middle::ty::{self, Ty};
use util::ppaux::ty_to_string;
use syntax::ast;
use syntax::parse::token::InternedString;
#[derive(Copy, Clone)]
struct VecTypes<'tcx> {
unit_ty: Ty<'tcx>,
llunit_ty: Type
}
impl<'tcx> VecTypes<'tcx> {
pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String {
format!("VecTypes {{unit_ty={}, llunit_ty={}}}",
ty_to_string(ccx.tcx(), self.unit_ty),
ccx.tn().type_to_string(self.llunit_ty))
}
}
pub fn trans_fixed_vstore<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
expr: &ast::Expr,
dest: expr::Dest)
-> Block<'blk, 'tcx> {
//!
//
// [...] allocates a fixed-size array and moves it around "by value".
// In this case, it means that the caller has already given us a location
// to store the array of the suitable size, so all we have to do is
// generate the content.
debug!("trans_fixed_vstore(expr={}, dest={})",
bcx.expr_to_string(expr), dest.to_string(bcx.ccx()));
let vt = vec_types_from_expr(bcx, expr);
return match dest {
Ignore => write_content(bcx, &vt, expr, expr, dest),
SaveIn(lldest) => {
// lldest will have type *[T x N], but we want the type *T,
// so use GEP to convert:
let lldest = GEPi(bcx, lldest, &[0, 0]);
write_content(bcx, &vt, expr, expr, SaveIn(lldest))
}
};
}
/// &[...] allocates memory on the stack and writes the values into it, returning the vector (the
/// caller must make the reference). "..." is similar except that the memory can be statically
/// allocated and we return a reference (strings are always by-ref).
pub fn trans_slice_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
slice_expr: &ast::Expr,
content_expr: &ast::Expr)
-> DatumBlock<'blk, 'tcx, Expr> {
let fcx = bcx.fcx;
let ccx = fcx.ccx;
let mut bcx = bcx;
debug!("trans_slice_vec(slice_expr={})",
bcx.expr_to_string(slice_expr));
let vec_ty = node_id_type(bcx, slice_expr.id);
// Handle the "..." case (returns a slice since strings are always unsized):
if let ast::ExprLit(ref lit) = content_expr.node {
if let ast::LitStr(ref s, _) = lit.node {
let scratch = rvalue_scratch_datum(bcx, vec_ty, "");
bcx = trans_lit_str(bcx,
content_expr,
s.clone(),
SaveIn(scratch.val));
return DatumBlock::new(bcx, scratch.to_expr_datum());
}
}
// Handle the &[...] case:
let vt = vec_types_from_expr(bcx, content_expr);
let count = elements_required(bcx, content_expr);
debug!(" vt={}, count={}", vt.to_string(ccx), count);
let fixed_ty = ty::mk_vec(bcx.tcx(),
vt.unit_ty,
Some(count));
let llfixed_ty = type_of::type_of(bcx.ccx(), fixed_ty);
// Always create an alloca even if zero-sized, to preserve
// the non-null invariant of the inner slice ptr
let llfixed = base::alloca(bcx, llfixed_ty, "");
if count > 0 {
// Arrange for the backing array to be cleaned up.
let cleanup_scope = cleanup::temporary_scope(bcx.tcx(), content_expr.id);
fcx.schedule_lifetime_end(cleanup_scope, llfixed);
fcx.schedule_drop_mem(cleanup_scope, llfixed, fixed_ty);
// Generate the content into the backing array.
// llfixed has type *[T x N], but we want the type *T,
// so use GEP to convert
bcx = write_content(bcx, &vt, slice_expr, content_expr,
SaveIn(GEPi(bcx, llfixed, &[0, 0])));
};
immediate_rvalue_bcx(bcx, llfixed, vec_ty).to_expr_datumblock()
}
/// Literal strings translate to slices into static memory. This is different from
/// trans_slice_vstore() above because it doesn't need to copy the content anywhere.
pub fn trans_lit_str<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
lit_expr: &ast::Expr,
str_lit: InternedString,
dest: Dest)
-> Block<'blk, 'tcx> {
debug!("trans_lit_str(lit_expr={}, dest={})",
bcx.expr_to_string(lit_expr),
dest.to_string(bcx.ccx()));
match dest {
Ignore => bcx,
SaveIn(lldest) => {
let bytes = str_lit.len();
let llbytes = C_uint(bcx.ccx(), bytes);
let llcstr = C_cstr(bcx.ccx(), str_lit, false);
let llcstr = consts::ptrcast(llcstr, Type::i8p(bcx.ccx()));
Store(bcx, llcstr, GEPi(bcx, lldest, &[0, abi::FAT_PTR_ADDR]));
Store(bcx, llbytes, GEPi(bcx, lldest, &[0, abi::FAT_PTR_EXTRA]));
bcx
}
}
}
fn write_content<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
vt: &VecTypes<'tcx>,
vstore_expr: &ast::Expr,
content_expr: &ast::Expr,
dest: Dest)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("tvec::write_content");
let fcx = bcx.fcx;
let mut bcx = bcx;
debug!("write_content(vt={}, dest={}, vstore_expr={})",
vt.to_string(bcx.ccx()),
dest.to_string(bcx.ccx()),
bcx.expr_to_string(vstore_expr));
match content_expr.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) => {
match dest {
Ignore => return bcx,
SaveIn(lldest) => {
let bytes = s.len();
let llbytes = C_uint(bcx.ccx(), bytes);
let llcstr = C_cstr(bcx.ccx(), (*s).clone(), false);
base::call_memcpy(bcx,
lldest,
llcstr,
llbytes,
1);
return bcx;
}
}
}
_ => {
bcx.tcx().sess.span_bug(content_expr.span,
"unexpected evec content");
}
}
}
ast::ExprVec(ref elements) => {
match dest {
Ignore => {
for element in elements {
bcx = expr::trans_into(bcx, &**element, Ignore);
}
}
SaveIn(lldest) => {
let temp_scope = fcx.push_custom_cleanup_scope();
for (i, element) in elements.iter().enumerate() {
let lleltptr = GEPi(bcx, lldest, &[i]);
debug!("writing index {} with lleltptr={}",
i, bcx.val_to_string(lleltptr));
bcx = expr::trans_into(bcx, &**element,
SaveIn(lleltptr));
let scope = cleanup::CustomScope(temp_scope);
fcx.schedule_lifetime_end(scope, lleltptr);
fcx.schedule_drop_mem(scope, lleltptr, vt.unit_ty);
}
fcx.pop_custom_cleanup_scope(temp_scope);
}
}
return bcx;
}
ast::ExprRepeat(ref element, ref count_expr) => {
match dest {
Ignore => {
return expr::trans_into(bcx, &**element, Ignore);
}
SaveIn(lldest) => {
match ty::eval_repeat_count(bcx.tcx(), &**count_expr) {
0 => expr::trans_into(bcx, &**element, Ignore),
1 => expr::trans_into(bcx, &**element, SaveIn(lldest)),
count => {
let elem = unpack_datum!(bcx, expr::trans(bcx, &**element));
let bcx = iter_vec_loop(bcx, lldest, vt,
C_uint(bcx.ccx(), count),
|set_bcx, lleltptr, _| {
elem.shallow_copy(set_bcx, lleltptr)
});
bcx
}
}
}
}
}
_ => {
bcx.tcx().sess.span_bug(content_expr.span,
"unexpected vec content");
}
}
}
fn vec_types_from_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, vec_expr: &ast::Expr)
-> VecTypes<'tcx> {
let vec_ty = node_id_type(bcx, vec_expr.id);
vec_types(bcx, ty::sequence_element_type(bcx.tcx(), vec_ty))
}
fn vec_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, unit_ty: Ty<'tcx>)
-> VecTypes<'tcx> {
VecTypes {
unit_ty: unit_ty,
llunit_ty: type_of::type_of(bcx.ccx(), unit_ty)
}
}
fn elements_required(bcx: Block, content_expr: &ast::Expr) -> usize {
//! Figure out the number of elements we need to store this content
match content_expr.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) => s.len(),
_ => {
bcx.tcx().sess.span_bug(content_expr.span,
"unexpected evec content")
}
}
},
ast::ExprVec(ref es) => es.len(),
ast::ExprRepeat(_, ref count_expr) => {
ty::eval_repeat_count(bcx.tcx(), &**count_expr)
}
_ => bcx.tcx().sess.span_bug(content_expr.span,
"unexpected vec content")
|
/// Converts a fixed-length vector into the slice pair. The vector should be stored in `llval`
/// which should be by ref.
pub fn get_fixed_base_and_len(bcx: Block,
llval: ValueRef,
vec_length: usize)
-> (ValueRef, ValueRef) {
let ccx = bcx.ccx();
let base = expr::get_dataptr(bcx, llval);
let len = C_uint(ccx, vec_length);
(base, len)
}
/// Converts a vector into the slice pair. The vector should be stored in `llval` which should be
/// by-reference. If you have a datum, you would probably prefer to call
/// `Datum::get_base_and_len()` which will handle any conversions for you.
pub fn get_base_and_len<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
llval: ValueRef,
vec_ty: Ty<'tcx>)
-> (ValueRef, ValueRef) {
let ccx = bcx.ccx();
match vec_ty.sty {
ty::TyArray(_, n) => get_fixed_base_and_len(bcx, llval, n),
ty::TySlice(_) | ty::TyStr => {
let base = Load(bcx, expr::get_dataptr(bcx, llval));
let len = Load(bcx, expr::get_len(bcx, llval));
(base, len)
}
// Only used for pattern matching.
ty::TyBox(ty) | ty::TyRef(_, ty::mt{ty,..}) => {
let inner = if type_is_sized(bcx.tcx(), ty) {
Load(bcx, llval)
} else {
llval
};
get_base_and_len(bcx, inner, ty)
},
_ => ccx.sess().bug("unexpected type in get_base_and_len"),
}
}
fn iter_vec_loop<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
data_ptr: ValueRef,
vt: &VecTypes<'tcx>,
count: ValueRef,
f: F)
-> Block<'blk, 'tcx> where
F: FnOnce(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
{
let _icx = push_ctxt("tvec::iter_vec_loop");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
let loop_bcx = fcx.new_temp_block("expr_repeat");
let next_bcx = fcx.new_temp_block("expr_repeat: next");
Br(bcx, loop_bcx.llbb, DebugLoc::None);
let loop_counter = Phi(loop_bcx, bcx.ccx().int_type(),
&[C_uint(bcx.ccx(), 0 as usize)], &[bcx.llbb]);
let bcx = loop_bcx;
let lleltptr = if llsize_of_alloc(bcx.ccx(), vt.llunit_ty) == 0 {
data_ptr
} else {
InBoundsGEP(bcx, data_ptr, &[loop_counter])
};
let bcx = f(bcx, lleltptr, vt.unit_ty);
let plusone = Add(bcx, loop_counter, C_uint(bcx.ccx(), 1usize), DebugLoc::None);
AddIncomingToPhi(loop_counter, plusone, bcx.llbb);
let cond_val = ICmp(bcx, llvm::IntULT, plusone, count, DebugLoc::None);
CondBr(bcx, cond_val, loop_bcx.llbb, next_bcx.llbb, DebugLoc::None);
next_bcx
}
pub fn iter_vec_raw<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
data_ptr: ValueRef,
unit_ty: Ty<'tcx>,
len: ValueRef,
f: F)
-> Block<'blk, 'tcx> where
F: FnOnce(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
{
let _icx = push_ctxt("tvec::iter_vec_raw");
let fcx = bcx.fcx;
let vt = vec_types(bcx, unit_ty);
if llsize_of_alloc(bcx.ccx(), vt.llunit_ty) == 0 {
// Special-case vectors with elements of size 0 so they don't go out of bounds (#9890)
iter_vec_loop(bcx, data_ptr, &vt, len, f)
} else {
// Calculate the last pointer address we want to handle.
let data_end_ptr = InBoundsGEP(bcx, data_ptr, &[len]);
// Now perform the iteration.
let header_bcx = fcx.new_temp_block("iter_vec_loop_header");
Br(bcx, header_bcx.llbb, DebugLoc::None);
let data_ptr =
Phi(header_bcx, val_ty(data_ptr), &[data_ptr], &[bcx.llbb]);
let not_yet_at_end =
ICmp(header_bcx, llvm::IntULT, data_ptr, data_end_ptr, DebugLoc::None);
let body_bcx = fcx.new_temp_block("iter_vec_loop_body");
let next_bcx = fcx.new_temp_block("iter_vec_next");
CondBr(header_bcx, not_yet_
|
}
}
|
random_line_split
|
tvec.rs
|
your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
use back::abi;
use llvm;
use llvm::ValueRef;
use trans::base::*;
use trans::base;
use trans::build::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::common::*;
use trans::consts;
use trans::datum::*;
use trans::debuginfo::DebugLoc;
use trans::expr::{Dest, Ignore, SaveIn};
use trans::expr;
use trans::machine::llsize_of_alloc;
use trans::type_::Type;
use trans::type_of;
use middle::ty::{self, Ty};
use util::ppaux::ty_to_string;
use syntax::ast;
use syntax::parse::token::InternedString;
#[derive(Copy, Clone)]
struct VecTypes<'tcx> {
unit_ty: Ty<'tcx>,
llunit_ty: Type
}
impl<'tcx> VecTypes<'tcx> {
pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String {
format!("VecTypes {{unit_ty={}, llunit_ty={}}}",
ty_to_string(ccx.tcx(), self.unit_ty),
ccx.tn().type_to_string(self.llunit_ty))
}
}
pub fn trans_fixed_vstore<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
expr: &ast::Expr,
dest: expr::Dest)
-> Block<'blk, 'tcx> {
//!
//
// [...] allocates a fixed-size array and moves it around "by value".
// In this case, it means that the caller has already given us a location
// to store the array of the suitable size, so all we have to do is
// generate the content.
debug!("trans_fixed_vstore(expr={}, dest={})",
bcx.expr_to_string(expr), dest.to_string(bcx.ccx()));
let vt = vec_types_from_expr(bcx, expr);
return match dest {
Ignore => write_content(bcx, &vt, expr, expr, dest),
SaveIn(lldest) => {
// lldest will have type *[T x N], but we want the type *T,
// so use GEP to convert:
let lldest = GEPi(bcx, lldest, &[0, 0]);
write_content(bcx, &vt, expr, expr, SaveIn(lldest))
}
};
}
/// &[...] allocates memory on the stack and writes the values into it, returning the vector (the
/// caller must make the reference). "..." is similar except that the memory can be statically
/// allocated and we return a reference (strings are always by-ref).
pub fn trans_slice_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
slice_expr: &ast::Expr,
content_expr: &ast::Expr)
-> DatumBlock<'blk, 'tcx, Expr> {
let fcx = bcx.fcx;
let ccx = fcx.ccx;
let mut bcx = bcx;
debug!("trans_slice_vec(slice_expr={})",
bcx.expr_to_string(slice_expr));
let vec_ty = node_id_type(bcx, slice_expr.id);
// Handle the "..." case (returns a slice since strings are always unsized):
if let ast::ExprLit(ref lit) = content_expr.node {
if let ast::LitStr(ref s, _) = lit.node {
let scratch = rvalue_scratch_datum(bcx, vec_ty, "");
bcx = trans_lit_str(bcx,
content_expr,
s.clone(),
SaveIn(scratch.val));
return DatumBlock::new(bcx, scratch.to_expr_datum());
}
}
// Handle the &[...] case:
let vt = vec_types_from_expr(bcx, content_expr);
let count = elements_required(bcx, content_expr);
debug!(" vt={}, count={}", vt.to_string(ccx), count);
let fixed_ty = ty::mk_vec(bcx.tcx(),
vt.unit_ty,
Some(count));
let llfixed_ty = type_of::type_of(bcx.ccx(), fixed_ty);
// Always create an alloca even if zero-sized, to preserve
// the non-null invariant of the inner slice ptr
let llfixed = base::alloca(bcx, llfixed_ty, "");
if count > 0 {
// Arrange for the backing array to be cleaned up.
let cleanup_scope = cleanup::temporary_scope(bcx.tcx(), content_expr.id);
fcx.schedule_lifetime_end(cleanup_scope, llfixed);
fcx.schedule_drop_mem(cleanup_scope, llfixed, fixed_ty);
// Generate the content into the backing array.
// llfixed has type *[T x N], but we want the type *T,
// so use GEP to convert
bcx = write_content(bcx, &vt, slice_expr, content_expr,
SaveIn(GEPi(bcx, llfixed, &[0, 0])));
};
immediate_rvalue_bcx(bcx, llfixed, vec_ty).to_expr_datumblock()
}
/// Literal strings translate to slices into static memory. This is different from
/// trans_slice_vstore() above because it doesn't need to copy the content anywhere.
pub fn
|
<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
lit_expr: &ast::Expr,
str_lit: InternedString,
dest: Dest)
-> Block<'blk, 'tcx> {
debug!("trans_lit_str(lit_expr={}, dest={})",
bcx.expr_to_string(lit_expr),
dest.to_string(bcx.ccx()));
match dest {
Ignore => bcx,
SaveIn(lldest) => {
let bytes = str_lit.len();
let llbytes = C_uint(bcx.ccx(), bytes);
let llcstr = C_cstr(bcx.ccx(), str_lit, false);
let llcstr = consts::ptrcast(llcstr, Type::i8p(bcx.ccx()));
Store(bcx, llcstr, GEPi(bcx, lldest, &[0, abi::FAT_PTR_ADDR]));
Store(bcx, llbytes, GEPi(bcx, lldest, &[0, abi::FAT_PTR_EXTRA]));
bcx
}
}
}
fn write_content<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
vt: &VecTypes<'tcx>,
vstore_expr: &ast::Expr,
content_expr: &ast::Expr,
dest: Dest)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("tvec::write_content");
let fcx = bcx.fcx;
let mut bcx = bcx;
debug!("write_content(vt={}, dest={}, vstore_expr={})",
vt.to_string(bcx.ccx()),
dest.to_string(bcx.ccx()),
bcx.expr_to_string(vstore_expr));
match content_expr.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) => {
match dest {
Ignore => return bcx,
SaveIn(lldest) => {
let bytes = s.len();
let llbytes = C_uint(bcx.ccx(), bytes);
let llcstr = C_cstr(bcx.ccx(), (*s).clone(), false);
base::call_memcpy(bcx,
lldest,
llcstr,
llbytes,
1);
return bcx;
}
}
}
_ => {
bcx.tcx().sess.span_bug(content_expr.span,
"unexpected evec content");
}
}
}
ast::ExprVec(ref elements) => {
match dest {
Ignore => {
for element in elements {
bcx = expr::trans_into(bcx, &**element, Ignore);
}
}
SaveIn(lldest) => {
let temp_scope = fcx.push_custom_cleanup_scope();
for (i, element) in elements.iter().enumerate() {
let lleltptr = GEPi(bcx, lldest, &[i]);
debug!("writing index {} with lleltptr={}",
i, bcx.val_to_string(lleltptr));
bcx = expr::trans_into(bcx, &**element,
SaveIn(lleltptr));
let scope = cleanup::CustomScope(temp_scope);
fcx.schedule_lifetime_end(scope, lleltptr);
fcx.schedule_drop_mem(scope, lleltptr, vt.unit_ty);
}
fcx.pop_custom_cleanup_scope(temp_scope);
}
}
return bcx;
}
ast::ExprRepeat(ref element, ref count_expr) => {
match dest {
Ignore => {
return expr::trans_into(bcx, &**element, Ignore);
}
SaveIn(lldest) => {
match ty::eval_repeat_count(bcx.tcx(), &**count_expr) {
0 => expr::trans_into(bcx, &**element, Ignore),
1 => expr::trans_into(bcx, &**element, SaveIn(lldest)),
count => {
let elem = unpack_datum!(bcx, expr::trans(bcx, &**element));
let bcx = iter_vec_loop(bcx, lldest, vt,
C_uint(bcx.ccx(), count),
|set_bcx, lleltptr, _| {
elem.shallow_copy(set_bcx, lleltptr)
});
bcx
}
}
}
}
}
_ => {
bcx.tcx().sess.span_bug(content_expr.span,
"unexpected vec content");
}
}
}
fn vec_types_from_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, vec_expr: &ast::Expr)
-> VecTypes<'tcx> {
let vec_ty = node_id_type(bcx, vec_expr.id);
vec_types(bcx, ty::sequence_element_type(bcx.tcx(), vec_ty))
}
fn vec_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, unit_ty: Ty<'tcx>)
-> VecTypes<'tcx> {
VecTypes {
unit_ty: unit_ty,
llunit_ty: type_of::type_of(bcx.ccx(), unit_ty)
}
}
fn elements_required(bcx: Block, content_expr: &ast::Expr) -> usize {
//! Figure out the number of elements we need to store this content
match content_expr.node {
ast::ExprLit(ref lit) => {
match lit.node {
ast::LitStr(ref s, _) => s.len(),
_ => {
bcx.tcx().sess.span_bug(content_expr.span,
"unexpected evec content")
}
}
},
ast::ExprVec(ref es) => es.len(),
ast::ExprRepeat(_, ref count_expr) => {
ty::eval_repeat_count(bcx.tcx(), &**count_expr)
}
_ => bcx.tcx().sess.span_bug(content_expr.span,
"unexpected vec content")
}
}
/// Converts a fixed-length vector into the slice pair. The vector should be stored in `llval`
/// which should be by ref.
pub fn get_fixed_base_and_len(bcx: Block,
llval: ValueRef,
vec_length: usize)
-> (ValueRef, ValueRef) {
let ccx = bcx.ccx();
let base = expr::get_dataptr(bcx, llval);
let len = C_uint(ccx, vec_length);
(base, len)
}
/// Converts a vector into the slice pair. The vector should be stored in `llval` which should be
/// by-reference. If you have a datum, you would probably prefer to call
/// `Datum::get_base_and_len()` which will handle any conversions for you.
pub fn get_base_and_len<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
llval: ValueRef,
vec_ty: Ty<'tcx>)
-> (ValueRef, ValueRef) {
let ccx = bcx.ccx();
match vec_ty.sty {
ty::TyArray(_, n) => get_fixed_base_and_len(bcx, llval, n),
ty::TySlice(_) | ty::TyStr => {
let base = Load(bcx, expr::get_dataptr(bcx, llval));
let len = Load(bcx, expr::get_len(bcx, llval));
(base, len)
}
// Only used for pattern matching.
ty::TyBox(ty) | ty::TyRef(_, ty::mt{ty,..}) => {
let inner = if type_is_sized(bcx.tcx(), ty) {
Load(bcx, llval)
} else {
llval
};
get_base_and_len(bcx, inner, ty)
},
_ => ccx.sess().bug("unexpected type in get_base_and_len"),
}
}
fn iter_vec_loop<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
data_ptr: ValueRef,
vt: &VecTypes<'tcx>,
count: ValueRef,
f: F)
-> Block<'blk, 'tcx> where
F: FnOnce(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
{
let _icx = push_ctxt("tvec::iter_vec_loop");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
let loop_bcx = fcx.new_temp_block("expr_repeat");
let next_bcx = fcx.new_temp_block("expr_repeat: next");
Br(bcx, loop_bcx.llbb, DebugLoc::None);
let loop_counter = Phi(loop_bcx, bcx.ccx().int_type(),
&[C_uint(bcx.ccx(), 0 as usize)], &[bcx.llbb]);
let bcx = loop_bcx;
let lleltptr = if llsize_of_alloc(bcx.ccx(), vt.llunit_ty) == 0 {
data_ptr
} else {
InBoundsGEP(bcx, data_ptr, &[loop_counter])
};
let bcx = f(bcx, lleltptr, vt.unit_ty);
let plusone = Add(bcx, loop_counter, C_uint(bcx.ccx(), 1usize), DebugLoc::None);
AddIncomingToPhi(loop_counter, plusone, bcx.llbb);
let cond_val = ICmp(bcx, llvm::IntULT, plusone, count, DebugLoc::None);
CondBr(bcx, cond_val, loop_bcx.llbb, next_bcx.llbb, DebugLoc::None);
next_bcx
}
pub fn iter_vec_raw<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
data_ptr: ValueRef,
unit_ty: Ty<'tcx>,
len: ValueRef,
f: F)
-> Block<'blk, 'tcx> where
F: FnOnce(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
{
let _icx = push_ctxt("tvec::iter_vec_raw");
let fcx = bcx.fcx;
let vt = vec_types(bcx, unit_ty);
if llsize_of_alloc(bcx.ccx(), vt.llunit_ty) == 0 {
// Special-case vectors with elements of size 0 so they don't go out of bounds (#9890)
iter_vec_loop(bcx, data_ptr, &vt, len, f)
} else {
// Calculate the last pointer address we want to handle.
let data_end_ptr = InBoundsGEP(bcx, data_ptr, &[len]);
// Now perform the iteration.
let header_bcx = fcx.new_temp_block("iter_vec_loop_header");
Br(bcx, header_bcx.llbb, DebugLoc::None);
let data_ptr =
Phi(header_bcx, val_ty(data_ptr), &[data_ptr], &[bcx.llbb]);
let not_yet_at_end =
ICmp(header_bcx, llvm::IntULT, data_ptr, data_end_ptr, DebugLoc::None);
let body_bcx = fcx.new_temp_block("iter_vec_loop_body");
let next_bcx = fcx.new_temp_block("iter_vec_next");
CondBr(header_bcx, not_
|
trans_lit_str
|
identifier_name
|
htmlareaelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::Element;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::follow_hyperlink;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use euclid::point::Point2D;
use html5ever_atoms::LocalName;
use net_traits::ReferrerPolicy;
use std::default::Default;
use std::f32;
use style::attr::AttrValue;
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Area {
Circle { left: f32, top: f32, radius: f32 },
Rectangle { top_left: (f32, f32), bottom_right: (f32, f32) },
Polygon { points: Vec<f32> },
}
pub enum Shape {
Circle,
Rectangle,
Polygon,
}
// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-list-of-floating-point-numbers
// https://html.spec.whatwg.org/multipage/#image-map-processing-model
impl Area {
pub fn parse(coord: &str, target: Shape) -> Option<Area> {
let points_count = match target {
Shape::Circle => 3,
Shape::Rectangle => 4,
Shape::Polygon => 0,
};
let size = coord.len();
let num = coord.as_bytes();
let mut index = 0;
// Step 4: Walk till char is not a delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => {},
_ => break,
}
index += 1;
}
//This vector will hold all parsed coordinates
let mut number_list = Vec::new();
let mut array = Vec::new();
let ar_ref = &mut array;
// Step 5: walk till end of string
while index < size {
// Step 5.1: walk till we hit a valid char i.e., 0 to 9, dot or dash, e, E
while index < size {
let val = num[index];
match val {
b'0'...b'9' | b'.' | b'-' | b'E' | b'e' => break,
_ => {},
}
index += 1;
}
// Step 5.2: collect valid symbols till we hit another delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => break,
_ => (*ar_ref).push(val),
}
index += 1;
}
// The input does not consist any valid charecters
if (*ar_ref).is_empty() {
break;
}
// Convert String to float
match String::from_utf8((*ar_ref).clone()).unwrap().parse::<f32>() {
Ok(v) => number_list.push(v),
Err(_) => number_list.push(0.0),
};
(*ar_ref).clear();
// For rectangle and circle, stop parsing once we have three
// and four coordinates respectively
if points_count > 0 && number_list.len() == points_count {
break;
}
}
let final_size = number_list.len();
match target {
Shape::Circle => {
if final_size == 3 {
if number_list[2] <= 0.0 {
None
} else {
Some(Area::Circle {
left: number_list[0],
top: number_list[1],
radius: number_list[2]
})
}
} else {
None
}
},
Shape::Rectangle => {
if final_size == 4 {
if number_list[0] > number_list[2] {
number_list.swap(0, 2);
}
if number_list[1] > number_list[3] {
number_list.swap(1, 3);
}
Some(Area::Rectangle {
top_left: (number_list[0], number_list[1]),
bottom_right: (number_list[2], number_list[3])
})
} else {
None
}
},
Shape::Polygon => {
if final_size >= 6 {
if final_size % 2!= 0 {
// Drop last element if there are odd number of coordinates
number_list.remove(final_size - 1);
}
Some(Area::Polygon { points: number_list })
} else {
None
}
},
}
}
pub fn hit_test(&self, p: Point2D<f32>) -> bool {
match *self {
Area::Circle { left, top, radius } => {
(p.x - left) * (p.x - left) +
(p.y - top) * (p.y - top) -
radius * radius <= 0.0
},
Area::Rectangle { top_left, bottom_right } => {
p.x <= bottom_right.0 && p.x >= top_left.0 &&
p.y <= bottom_right.1 && p.y >= top_left.1
},
//TODO polygon hit_test
_ => false,
}
}
pub fn absolute_coords(&self, p: Point2D<f32>) -> Area {
match *self {
Area::Rectangle { top_left, bottom_right } => {
Area::Rectangle {
top_left: (top_left.0 + p.x, top_left.1 + p.y),
bottom_right: (bottom_right.0 + p.x, bottom_right.1 + p.y)
}
},
Area::Circle { left, top, radius } => {
Area::Circle {
left: (left + p.x),
top: (top + p.y),
radius: radius
}
},
Area::Polygon { ref points } => {
// let new_points = Vec::new();
let iter = points.iter().enumerate().map(|(index, point)| {
match index % 2 {
0 => point + p.x as f32,
_ => point + p.y as f32,
}
});
Area::Polygon { points: iter.collect::<Vec<_>>() }
},
}
}
}
#[dom_struct]
pub struct HTMLAreaElement {
htmlelement: HTMLElement,
rel_list: MutNullableJS<DOMTokenList>,
}
impl HTMLAreaElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
rel_list: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAreaElement> {
Node::reflect_node(box HTMLAreaElement::new_inherited(local_name, prefix, document),
document,
HTMLAreaElementBinding::Wrap)
}
pub fn get_shape_from_coords(&self) -> Option<Area> {
let elem = self.upcast::<Element>();
let shape = elem.get_string_attribute(&"shape".into());
let shp: Shape = match shape.to_lowercase().as_ref() {
"circle" => Shape::Circle,
"circ" => Shape::Circle,
"rectangle" => Shape::Rectangle,
"rect" => Shape::Rectangle,
"polygon" => Shape::Rectangle,
"poly" => Shape::Polygon,
_ => return None,
};
if elem.has_attribute(&"coords".into()) {
let attribute = elem.get_string_attribute(&"coords".into());
Area::parse(&attribute, shp)
} else {
None
}
}
}
impl VirtualMethods for HTMLAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast(), &local_name!("rel"))
})
}
}
impl Activatable for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#the-area-element:activation-behaviour
fn as_element(&self) -> &Element {
self.upcast::<Element>()
}
fn is_instance_activatable(&self) -> bool {
self.as_element().has_attribute(&local_name!("href"))
}
fn pre_click_activation(&self) {
}
fn canceled_activation(&self)
|
fn implicit_submission(&self, _ctrl_key: bool, _shift_key: bool,
_alt_key: bool, _meta_key: bool) {
}
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
// Step 1
let doc = document_from_node(self);
if!doc.is_fully_active() {
return;
}
// Step 2
// TODO : We should be choosing a browsing context and navigating to it.
// Step 3
let referrer_policy = match self.RelList().Contains("noreferrer".into()) {
true => Some(ReferrerPolicy::NoReferrer),
false => None,
};
follow_hyperlink(self.upcast::<Element>(), None, referrer_policy);
}
}
|
{
}
|
identifier_body
|
htmlareaelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::Element;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::follow_hyperlink;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use euclid::point::Point2D;
use html5ever_atoms::LocalName;
use net_traits::ReferrerPolicy;
use std::default::Default;
use std::f32;
use style::attr::AttrValue;
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Area {
Circle { left: f32, top: f32, radius: f32 },
Rectangle { top_left: (f32, f32), bottom_right: (f32, f32) },
Polygon { points: Vec<f32> },
}
pub enum Shape {
Circle,
Rectangle,
Polygon,
}
// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-list-of-floating-point-numbers
// https://html.spec.whatwg.org/multipage/#image-map-processing-model
impl Area {
pub fn parse(coord: &str, target: Shape) -> Option<Area> {
let points_count = match target {
Shape::Circle => 3,
Shape::Rectangle => 4,
Shape::Polygon => 0,
};
let size = coord.len();
let num = coord.as_bytes();
let mut index = 0;
// Step 4: Walk till char is not a delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => {},
_ => break,
}
index += 1;
}
//This vector will hold all parsed coordinates
let mut number_list = Vec::new();
let mut array = Vec::new();
let ar_ref = &mut array;
// Step 5: walk till end of string
while index < size {
// Step 5.1: walk till we hit a valid char i.e., 0 to 9, dot or dash, e, E
while index < size {
let val = num[index];
match val {
b'0'...b'9' | b'.' | b'-' | b'E' | b'e' => break,
_ => {},
}
index += 1;
}
// Step 5.2: collect valid symbols till we hit another delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => break,
_ => (*ar_ref).push(val),
}
index += 1;
}
// The input does not consist any valid charecters
if (*ar_ref).is_empty() {
break;
}
// Convert String to float
match String::from_utf8((*ar_ref).clone()).unwrap().parse::<f32>() {
Ok(v) => number_list.push(v),
Err(_) => number_list.push(0.0),
};
(*ar_ref).clear();
// For rectangle and circle, stop parsing once we have three
// and four coordinates respectively
if points_count > 0 && number_list.len() == points_count {
break;
}
}
let final_size = number_list.len();
match target {
Shape::Circle => {
if final_size == 3 {
if number_list[2] <= 0.0 {
None
} else {
Some(Area::Circle {
left: number_list[0],
top: number_list[1],
radius: number_list[2]
})
}
} else {
None
}
},
Shape::Rectangle => {
if final_size == 4 {
if number_list[0] > number_list[2] {
number_list.swap(0, 2);
}
if number_list[1] > number_list[3] {
number_list.swap(1, 3);
}
Some(Area::Rectangle {
top_left: (number_list[0], number_list[1]),
bottom_right: (number_list[2], number_list[3])
})
} else {
None
}
},
Shape::Polygon => {
if final_size >= 6 {
if final_size % 2!= 0 {
// Drop last element if there are odd number of coordinates
number_list.remove(final_size - 1);
}
Some(Area::Polygon { points: number_list })
} else {
None
}
},
}
}
pub fn hit_test(&self, p: Point2D<f32>) -> bool {
match *self {
Area::Circle { left, top, radius } => {
(p.x - left) * (p.x - left) +
(p.y - top) * (p.y - top) -
radius * radius <= 0.0
},
Area::Rectangle { top_left, bottom_right } => {
p.x <= bottom_right.0 && p.x >= top_left.0 &&
p.y <= bottom_right.1 && p.y >= top_left.1
},
//TODO polygon hit_test
_ => false,
}
}
pub fn absolute_coords(&self, p: Point2D<f32>) -> Area {
match *self {
Area::Rectangle { top_left, bottom_right } => {
Area::Rectangle {
top_left: (top_left.0 + p.x, top_left.1 + p.y),
bottom_right: (bottom_right.0 + p.x, bottom_right.1 + p.y)
}
},
Area::Circle { left, top, radius } => {
Area::Circle {
left: (left + p.x),
top: (top + p.y),
radius: radius
}
},
Area::Polygon { ref points } => {
// let new_points = Vec::new();
let iter = points.iter().enumerate().map(|(index, point)| {
match index % 2 {
0 => point + p.x as f32,
_ => point + p.y as f32,
}
});
Area::Polygon { points: iter.collect::<Vec<_>>() }
},
}
}
}
#[dom_struct]
pub struct HTMLAreaElement {
htmlelement: HTMLElement,
rel_list: MutNullableJS<DOMTokenList>,
}
impl HTMLAreaElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
rel_list: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAreaElement> {
Node::reflect_node(box HTMLAreaElement::new_inherited(local_name, prefix, document),
document,
HTMLAreaElementBinding::Wrap)
}
pub fn get_shape_from_coords(&self) -> Option<Area> {
let elem = self.upcast::<Element>();
let shape = elem.get_string_attribute(&"shape".into());
let shp: Shape = match shape.to_lowercase().as_ref() {
"circle" => Shape::Circle,
"circ" => Shape::Circle,
"rectangle" => Shape::Rectangle,
"rect" => Shape::Rectangle,
"polygon" => Shape::Rectangle,
"poly" => Shape::Polygon,
_ => return None,
};
if elem.has_attribute(&"coords".into()) {
let attribute = elem.get_string_attribute(&"coords".into());
Area::parse(&attribute, shp)
} else {
None
}
}
}
impl VirtualMethods for HTMLAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast(), &local_name!("rel"))
})
}
}
impl Activatable for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#the-area-element:activation-behaviour
fn as_element(&self) -> &Element {
self.upcast::<Element>()
}
fn is_instance_activatable(&self) -> bool {
self.as_element().has_attribute(&local_name!("href"))
}
fn pre_click_activation(&self) {
}
fn canceled_activation(&self) {
}
fn
|
(&self, _ctrl_key: bool, _shift_key: bool,
_alt_key: bool, _meta_key: bool) {
}
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
// Step 1
let doc = document_from_node(self);
if!doc.is_fully_active() {
return;
}
// Step 2
// TODO : We should be choosing a browsing context and navigating to it.
// Step 3
let referrer_policy = match self.RelList().Contains("noreferrer".into()) {
true => Some(ReferrerPolicy::NoReferrer),
false => None,
};
follow_hyperlink(self.upcast::<Element>(), None, referrer_policy);
}
}
|
implicit_submission
|
identifier_name
|
htmlareaelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::Element;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::follow_hyperlink;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use euclid::point::Point2D;
use html5ever_atoms::LocalName;
use net_traits::ReferrerPolicy;
use std::default::Default;
use std::f32;
use style::attr::AttrValue;
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Area {
Circle { left: f32, top: f32, radius: f32 },
Rectangle { top_left: (f32, f32), bottom_right: (f32, f32) },
Polygon { points: Vec<f32> },
}
pub enum Shape {
Circle,
Rectangle,
Polygon,
}
// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-list-of-floating-point-numbers
// https://html.spec.whatwg.org/multipage/#image-map-processing-model
impl Area {
pub fn parse(coord: &str, target: Shape) -> Option<Area> {
let points_count = match target {
Shape::Circle => 3,
Shape::Rectangle => 4,
Shape::Polygon => 0,
};
let size = coord.len();
let num = coord.as_bytes();
let mut index = 0;
// Step 4: Walk till char is not a delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => {},
_ => break,
}
index += 1;
}
//This vector will hold all parsed coordinates
let mut number_list = Vec::new();
let mut array = Vec::new();
let ar_ref = &mut array;
// Step 5: walk till end of string
while index < size {
// Step 5.1: walk till we hit a valid char i.e., 0 to 9, dot or dash, e, E
while index < size {
let val = num[index];
match val {
b'0'...b'9' | b'.' | b'-' | b'E' | b'e' => break,
_ => {},
}
index += 1;
}
// Step 5.2: collect valid symbols till we hit another delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => break,
_ => (*ar_ref).push(val),
}
index += 1;
}
// The input does not consist any valid charecters
if (*ar_ref).is_empty() {
break;
}
// Convert String to float
match String::from_utf8((*ar_ref).clone()).unwrap().parse::<f32>() {
Ok(v) => number_list.push(v),
Err(_) => number_list.push(0.0),
};
(*ar_ref).clear();
// For rectangle and circle, stop parsing once we have three
// and four coordinates respectively
if points_count > 0 && number_list.len() == points_count {
break;
}
}
let final_size = number_list.len();
match target {
Shape::Circle => {
if final_size == 3 {
if number_list[2] <= 0.0 {
None
} else {
Some(Area::Circle {
left: number_list[0],
top: number_list[1],
radius: number_list[2]
})
}
} else {
None
}
},
Shape::Rectangle => {
if final_size == 4 {
if number_list[0] > number_list[2] {
number_list.swap(0, 2);
}
if number_list[1] > number_list[3] {
number_list.swap(1, 3);
}
Some(Area::Rectangle {
top_left: (number_list[0], number_list[1]),
bottom_right: (number_list[2], number_list[3])
})
} else {
None
}
},
Shape::Polygon => {
if final_size >= 6 {
if final_size % 2!= 0 {
// Drop last element if there are odd number of coordinates
number_list.remove(final_size - 1);
}
Some(Area::Polygon { points: number_list })
} else {
None
}
},
}
}
pub fn hit_test(&self, p: Point2D<f32>) -> bool {
match *self {
Area::Circle { left, top, radius } => {
(p.x - left) * (p.x - left) +
(p.y - top) * (p.y - top) -
radius * radius <= 0.0
},
Area::Rectangle { top_left, bottom_right } => {
p.x <= bottom_right.0 && p.x >= top_left.0 &&
p.y <= bottom_right.1 && p.y >= top_left.1
},
//TODO polygon hit_test
_ => false,
}
}
pub fn absolute_coords(&self, p: Point2D<f32>) -> Area {
match *self {
Area::Rectangle { top_left, bottom_right } => {
Area::Rectangle {
top_left: (top_left.0 + p.x, top_left.1 + p.y),
bottom_right: (bottom_right.0 + p.x, bottom_right.1 + p.y)
}
},
Area::Circle { left, top, radius } => {
Area::Circle {
left: (left + p.x),
top: (top + p.y),
radius: radius
}
},
Area::Polygon { ref points } => {
// let new_points = Vec::new();
let iter = points.iter().enumerate().map(|(index, point)| {
match index % 2 {
0 => point + p.x as f32,
_ => point + p.y as f32,
}
});
Area::Polygon { points: iter.collect::<Vec<_>>() }
},
}
}
}
#[dom_struct]
pub struct HTMLAreaElement {
htmlelement: HTMLElement,
rel_list: MutNullableJS<DOMTokenList>,
}
impl HTMLAreaElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
rel_list: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAreaElement> {
Node::reflect_node(box HTMLAreaElement::new_inherited(local_name, prefix, document),
document,
HTMLAreaElementBinding::Wrap)
}
pub fn get_shape_from_coords(&self) -> Option<Area> {
let elem = self.upcast::<Element>();
let shape = elem.get_string_attribute(&"shape".into());
let shp: Shape = match shape.to_lowercase().as_ref() {
"circle" => Shape::Circle,
"circ" => Shape::Circle,
"rectangle" => Shape::Rectangle,
"rect" => Shape::Rectangle,
"polygon" => Shape::Rectangle,
"poly" => Shape::Polygon,
_ => return None,
};
if elem.has_attribute(&"coords".into()) {
let attribute = elem.get_string_attribute(&"coords".into());
Area::parse(&attribute, shp)
} else {
None
}
}
}
impl VirtualMethods for HTMLAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast(), &local_name!("rel"))
})
}
}
impl Activatable for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#the-area-element:activation-behaviour
fn as_element(&self) -> &Element {
self.upcast::<Element>()
}
fn is_instance_activatable(&self) -> bool {
self.as_element().has_attribute(&local_name!("href"))
}
fn pre_click_activation(&self) {
}
fn canceled_activation(&self) {
}
fn implicit_submission(&self, _ctrl_key: bool, _shift_key: bool,
_alt_key: bool, _meta_key: bool) {
}
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
// Step 1
let doc = document_from_node(self);
|
// Step 3
let referrer_policy = match self.RelList().Contains("noreferrer".into()) {
true => Some(ReferrerPolicy::NoReferrer),
false => None,
};
follow_hyperlink(self.upcast::<Element>(), None, referrer_policy);
}
}
|
if !doc.is_fully_active() {
return;
}
// Step 2
// TODO : We should be choosing a browsing context and navigating to it.
|
random_line_split
|
htmlareaelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding;
use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::domtokenlist::DOMTokenList;
use dom::element::Element;
use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::follow_hyperlink;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, document_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use euclid::point::Point2D;
use html5ever_atoms::LocalName;
use net_traits::ReferrerPolicy;
use std::default::Default;
use std::f32;
use style::attr::AttrValue;
#[derive(PartialEq)]
#[derive(Debug)]
pub enum Area {
Circle { left: f32, top: f32, radius: f32 },
Rectangle { top_left: (f32, f32), bottom_right: (f32, f32) },
Polygon { points: Vec<f32> },
}
pub enum Shape {
Circle,
Rectangle,
Polygon,
}
// https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-list-of-floating-point-numbers
// https://html.spec.whatwg.org/multipage/#image-map-processing-model
impl Area {
pub fn parse(coord: &str, target: Shape) -> Option<Area> {
let points_count = match target {
Shape::Circle => 3,
Shape::Rectangle => 4,
Shape::Polygon => 0,
};
let size = coord.len();
let num = coord.as_bytes();
let mut index = 0;
// Step 4: Walk till char is not a delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => {},
_ => break,
}
index += 1;
}
//This vector will hold all parsed coordinates
let mut number_list = Vec::new();
let mut array = Vec::new();
let ar_ref = &mut array;
// Step 5: walk till end of string
while index < size {
// Step 5.1: walk till we hit a valid char i.e., 0 to 9, dot or dash, e, E
while index < size {
let val = num[index];
match val {
b'0'...b'9' | b'.' | b'-' | b'E' | b'e' => break,
_ => {},
}
index += 1;
}
// Step 5.2: collect valid symbols till we hit another delimiter
while index < size {
let val = num[index];
match val {
b',' | b';' | b''| b'\t' | b'\n' | 0x0C | b'\r' => break,
_ => (*ar_ref).push(val),
}
index += 1;
}
// The input does not consist any valid charecters
if (*ar_ref).is_empty() {
break;
}
// Convert String to float
match String::from_utf8((*ar_ref).clone()).unwrap().parse::<f32>() {
Ok(v) => number_list.push(v),
Err(_) => number_list.push(0.0),
};
(*ar_ref).clear();
// For rectangle and circle, stop parsing once we have three
// and four coordinates respectively
if points_count > 0 && number_list.len() == points_count {
break;
}
}
let final_size = number_list.len();
match target {
Shape::Circle => {
if final_size == 3 {
if number_list[2] <= 0.0 {
None
} else {
Some(Area::Circle {
left: number_list[0],
top: number_list[1],
radius: number_list[2]
})
}
} else {
None
}
},
Shape::Rectangle => {
if final_size == 4 {
if number_list[0] > number_list[2] {
number_list.swap(0, 2);
}
if number_list[1] > number_list[3] {
number_list.swap(1, 3);
}
Some(Area::Rectangle {
top_left: (number_list[0], number_list[1]),
bottom_right: (number_list[2], number_list[3])
})
} else {
None
}
},
Shape::Polygon => {
if final_size >= 6 {
if final_size % 2!= 0 {
// Drop last element if there are odd number of coordinates
number_list.remove(final_size - 1);
}
Some(Area::Polygon { points: number_list })
} else {
None
}
},
}
}
pub fn hit_test(&self, p: Point2D<f32>) -> bool {
match *self {
Area::Circle { left, top, radius } =>
|
,
Area::Rectangle { top_left, bottom_right } => {
p.x <= bottom_right.0 && p.x >= top_left.0 &&
p.y <= bottom_right.1 && p.y >= top_left.1
},
//TODO polygon hit_test
_ => false,
}
}
pub fn absolute_coords(&self, p: Point2D<f32>) -> Area {
match *self {
Area::Rectangle { top_left, bottom_right } => {
Area::Rectangle {
top_left: (top_left.0 + p.x, top_left.1 + p.y),
bottom_right: (bottom_right.0 + p.x, bottom_right.1 + p.y)
}
},
Area::Circle { left, top, radius } => {
Area::Circle {
left: (left + p.x),
top: (top + p.y),
radius: radius
}
},
Area::Polygon { ref points } => {
// let new_points = Vec::new();
let iter = points.iter().enumerate().map(|(index, point)| {
match index % 2 {
0 => point + p.x as f32,
_ => point + p.y as f32,
}
});
Area::Polygon { points: iter.collect::<Vec<_>>() }
},
}
}
}
#[dom_struct]
pub struct HTMLAreaElement {
htmlelement: HTMLElement,
rel_list: MutNullableJS<DOMTokenList>,
}
impl HTMLAreaElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLAreaElement {
HTMLAreaElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
rel_list: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAreaElement> {
Node::reflect_node(box HTMLAreaElement::new_inherited(local_name, prefix, document),
document,
HTMLAreaElementBinding::Wrap)
}
pub fn get_shape_from_coords(&self) -> Option<Area> {
let elem = self.upcast::<Element>();
let shape = elem.get_string_attribute(&"shape".into());
let shp: Shape = match shape.to_lowercase().as_ref() {
"circle" => Shape::Circle,
"circ" => Shape::Circle,
"rectangle" => Shape::Rectangle,
"rect" => Shape::Rectangle,
"polygon" => Shape::Rectangle,
"poly" => Shape::Polygon,
_ => return None,
};
if elem.has_attribute(&"coords".into()) {
let attribute = elem.get_string_attribute(&"coords".into());
Area::parse(&attribute, shp)
} else {
None
}
}
}
impl VirtualMethods for HTMLAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast(), &local_name!("rel"))
})
}
}
impl Activatable for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#the-area-element:activation-behaviour
fn as_element(&self) -> &Element {
self.upcast::<Element>()
}
fn is_instance_activatable(&self) -> bool {
self.as_element().has_attribute(&local_name!("href"))
}
fn pre_click_activation(&self) {
}
fn canceled_activation(&self) {
}
fn implicit_submission(&self, _ctrl_key: bool, _shift_key: bool,
_alt_key: bool, _meta_key: bool) {
}
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
// Step 1
let doc = document_from_node(self);
if!doc.is_fully_active() {
return;
}
// Step 2
// TODO : We should be choosing a browsing context and navigating to it.
// Step 3
let referrer_policy = match self.RelList().Contains("noreferrer".into()) {
true => Some(ReferrerPolicy::NoReferrer),
false => None,
};
follow_hyperlink(self.upcast::<Element>(), None, referrer_policy);
}
}
|
{
(p.x - left) * (p.x - left) +
(p.y - top) * (p.y - top) -
radius * radius <= 0.0
}
|
conditional_block
|
controller.rs
|
use futures::{Future, Async, Poll, Stream};
use futures::sync::mpsc::{UnboundedSender, UnboundedReceiver};
|
ClientMessage,
Message,
Command as ClientControllerCommand
};
use planetwars::config::Config;
use planetwars::step_lock::StepLock;
use planetwars::pw_controller::PwController;
use slog;
/// The controller forms the bridge between game rules and clients.
/// It is responsible for communications, the control flow, and logging.
pub struct Controller {
step_lock: StepLock,
pw_controller: PwController,
client_msgs: UnboundedReceiver<ClientMessage>,
clients: Vec<Client>,
logger: slog::Logger,
}
#[derive(Clone)]
pub struct Client {
pub id: usize,
pub player_name: String,
pub handle: UnboundedSender<ClientControllerCommand>,
}
impl Client {
pub fn send_msg(&mut self, msg: Vec<u8>) {
let cmd = ClientControllerCommand::Send(msg);
// unbounded channels don't fail
self.handle.unbounded_send(cmd).unwrap();
}
}
impl Controller {
// TODO: this method does both controller initialization and game staritng.
// It would be nice to split these.
pub fn new(clients: Vec<Client>,
client_msgs: UnboundedReceiver<ClientMessage>,
conf: Config, logger: slog::Logger,)
-> Self
{
let mut c = Controller {
pw_controller: PwController::new(conf, clients.clone(), logger.clone()),
step_lock: StepLock::new(),
client_msgs,
clients,
logger,
};
c.init();
return c;
}
fn init(&mut self) {
self.pw_controller.init(&mut self.step_lock);
}
/// Handle an incoming message.
fn handle_message(&mut self, client_id: usize, msg: Message) {
match msg {
Message::Data(msg) => {
// TODO: maybe it would be better to log this in the
// client_controller.
info!(self.logger, "message received";
"client_id" => client_id
// TODO: content is binary now, how do we encode this?
);
self.step_lock.attach_command(client_id, msg);
},
Message::Disconnected => {
// TODO: should a reason be included here?
// It might be more useful to have the client controller log
// disconnect reasons.
info!(self.logger, "client disconnected";
"client_id" => client_id
);
self.step_lock.remove(client_id);
self.pw_controller.handle_disconnect(client_id);
}
}
}
}
impl Future for Controller {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
loop {
let msg = try_ready!(self.client_msgs.poll()).unwrap();
self.handle_message(msg.client_id, msg.message);
while self.step_lock.is_ready() {
let msgs = self.step_lock.take_messages();
self.pw_controller.step(&mut self.step_lock, msgs);
// TODO: this could be done better
if self.pw_controller.outcome().is_some() {
for client in self.clients.iter_mut() {
client.handle.unbounded_send(
ClientControllerCommand::Disconnect
).unwrap();
}
return Ok(Async::Ready(()));
}
}
}
}
}
|
use client_controller::{
|
random_line_split
|
controller.rs
|
use futures::{Future, Async, Poll, Stream};
use futures::sync::mpsc::{UnboundedSender, UnboundedReceiver};
use client_controller::{
ClientMessage,
Message,
Command as ClientControllerCommand
};
use planetwars::config::Config;
use planetwars::step_lock::StepLock;
use planetwars::pw_controller::PwController;
use slog;
/// The controller forms the bridge between game rules and clients.
/// It is responsible for communications, the control flow, and logging.
pub struct Controller {
step_lock: StepLock,
pw_controller: PwController,
client_msgs: UnboundedReceiver<ClientMessage>,
clients: Vec<Client>,
logger: slog::Logger,
}
#[derive(Clone)]
pub struct Client {
pub id: usize,
pub player_name: String,
pub handle: UnboundedSender<ClientControllerCommand>,
}
impl Client {
pub fn send_msg(&mut self, msg: Vec<u8>) {
let cmd = ClientControllerCommand::Send(msg);
// unbounded channels don't fail
self.handle.unbounded_send(cmd).unwrap();
}
}
impl Controller {
// TODO: this method does both controller initialization and game staritng.
// It would be nice to split these.
pub fn new(clients: Vec<Client>,
client_msgs: UnboundedReceiver<ClientMessage>,
conf: Config, logger: slog::Logger,)
-> Self
{
let mut c = Controller {
pw_controller: PwController::new(conf, clients.clone(), logger.clone()),
step_lock: StepLock::new(),
client_msgs,
clients,
logger,
};
c.init();
return c;
}
fn init(&mut self)
|
/// Handle an incoming message.
fn handle_message(&mut self, client_id: usize, msg: Message) {
match msg {
Message::Data(msg) => {
// TODO: maybe it would be better to log this in the
// client_controller.
info!(self.logger, "message received";
"client_id" => client_id
// TODO: content is binary now, how do we encode this?
);
self.step_lock.attach_command(client_id, msg);
},
Message::Disconnected => {
// TODO: should a reason be included here?
// It might be more useful to have the client controller log
// disconnect reasons.
info!(self.logger, "client disconnected";
"client_id" => client_id
);
self.step_lock.remove(client_id);
self.pw_controller.handle_disconnect(client_id);
}
}
}
}
impl Future for Controller {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
loop {
let msg = try_ready!(self.client_msgs.poll()).unwrap();
self.handle_message(msg.client_id, msg.message);
while self.step_lock.is_ready() {
let msgs = self.step_lock.take_messages();
self.pw_controller.step(&mut self.step_lock, msgs);
// TODO: this could be done better
if self.pw_controller.outcome().is_some() {
for client in self.clients.iter_mut() {
client.handle.unbounded_send(
ClientControllerCommand::Disconnect
).unwrap();
}
return Ok(Async::Ready(()));
}
}
}
}
}
|
{
self.pw_controller.init(&mut self.step_lock);
}
|
identifier_body
|
controller.rs
|
use futures::{Future, Async, Poll, Stream};
use futures::sync::mpsc::{UnboundedSender, UnboundedReceiver};
use client_controller::{
ClientMessage,
Message,
Command as ClientControllerCommand
};
use planetwars::config::Config;
use planetwars::step_lock::StepLock;
use planetwars::pw_controller::PwController;
use slog;
/// The controller forms the bridge between game rules and clients.
/// It is responsible for communications, the control flow, and logging.
pub struct Controller {
step_lock: StepLock,
pw_controller: PwController,
client_msgs: UnboundedReceiver<ClientMessage>,
clients: Vec<Client>,
logger: slog::Logger,
}
#[derive(Clone)]
pub struct Client {
pub id: usize,
pub player_name: String,
pub handle: UnboundedSender<ClientControllerCommand>,
}
impl Client {
pub fn send_msg(&mut self, msg: Vec<u8>) {
let cmd = ClientControllerCommand::Send(msg);
// unbounded channels don't fail
self.handle.unbounded_send(cmd).unwrap();
}
}
impl Controller {
// TODO: this method does both controller initialization and game staritng.
// It would be nice to split these.
pub fn new(clients: Vec<Client>,
client_msgs: UnboundedReceiver<ClientMessage>,
conf: Config, logger: slog::Logger,)
-> Self
{
let mut c = Controller {
pw_controller: PwController::new(conf, clients.clone(), logger.clone()),
step_lock: StepLock::new(),
client_msgs,
clients,
logger,
};
c.init();
return c;
}
fn init(&mut self) {
self.pw_controller.init(&mut self.step_lock);
}
/// Handle an incoming message.
fn handle_message(&mut self, client_id: usize, msg: Message) {
match msg {
Message::Data(msg) =>
|
,
Message::Disconnected => {
// TODO: should a reason be included here?
// It might be more useful to have the client controller log
// disconnect reasons.
info!(self.logger, "client disconnected";
"client_id" => client_id
);
self.step_lock.remove(client_id);
self.pw_controller.handle_disconnect(client_id);
}
}
}
}
impl Future for Controller {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
loop {
let msg = try_ready!(self.client_msgs.poll()).unwrap();
self.handle_message(msg.client_id, msg.message);
while self.step_lock.is_ready() {
let msgs = self.step_lock.take_messages();
self.pw_controller.step(&mut self.step_lock, msgs);
// TODO: this could be done better
if self.pw_controller.outcome().is_some() {
for client in self.clients.iter_mut() {
client.handle.unbounded_send(
ClientControllerCommand::Disconnect
).unwrap();
}
return Ok(Async::Ready(()));
}
}
}
}
}
|
{
// TODO: maybe it would be better to log this in the
// client_controller.
info!(self.logger, "message received";
"client_id" => client_id
// TODO: content is binary now, how do we encode this?
);
self.step_lock.attach_command(client_id, msg);
}
|
conditional_block
|
controller.rs
|
use futures::{Future, Async, Poll, Stream};
use futures::sync::mpsc::{UnboundedSender, UnboundedReceiver};
use client_controller::{
ClientMessage,
Message,
Command as ClientControllerCommand
};
use planetwars::config::Config;
use planetwars::step_lock::StepLock;
use planetwars::pw_controller::PwController;
use slog;
/// The controller forms the bridge between game rules and clients.
/// It is responsible for communications, the control flow, and logging.
pub struct Controller {
step_lock: StepLock,
pw_controller: PwController,
client_msgs: UnboundedReceiver<ClientMessage>,
clients: Vec<Client>,
logger: slog::Logger,
}
#[derive(Clone)]
pub struct Client {
pub id: usize,
pub player_name: String,
pub handle: UnboundedSender<ClientControllerCommand>,
}
impl Client {
pub fn send_msg(&mut self, msg: Vec<u8>) {
let cmd = ClientControllerCommand::Send(msg);
// unbounded channels don't fail
self.handle.unbounded_send(cmd).unwrap();
}
}
impl Controller {
// TODO: this method does both controller initialization and game staritng.
// It would be nice to split these.
pub fn new(clients: Vec<Client>,
client_msgs: UnboundedReceiver<ClientMessage>,
conf: Config, logger: slog::Logger,)
-> Self
{
let mut c = Controller {
pw_controller: PwController::new(conf, clients.clone(), logger.clone()),
step_lock: StepLock::new(),
client_msgs,
clients,
logger,
};
c.init();
return c;
}
fn init(&mut self) {
self.pw_controller.init(&mut self.step_lock);
}
/// Handle an incoming message.
fn
|
(&mut self, client_id: usize, msg: Message) {
match msg {
Message::Data(msg) => {
// TODO: maybe it would be better to log this in the
// client_controller.
info!(self.logger, "message received";
"client_id" => client_id
// TODO: content is binary now, how do we encode this?
);
self.step_lock.attach_command(client_id, msg);
},
Message::Disconnected => {
// TODO: should a reason be included here?
// It might be more useful to have the client controller log
// disconnect reasons.
info!(self.logger, "client disconnected";
"client_id" => client_id
);
self.step_lock.remove(client_id);
self.pw_controller.handle_disconnect(client_id);
}
}
}
}
impl Future for Controller {
type Item = ();
type Error = ();
fn poll(&mut self) -> Poll<(), ()> {
loop {
let msg = try_ready!(self.client_msgs.poll()).unwrap();
self.handle_message(msg.client_id, msg.message);
while self.step_lock.is_ready() {
let msgs = self.step_lock.take_messages();
self.pw_controller.step(&mut self.step_lock, msgs);
// TODO: this could be done better
if self.pw_controller.outcome().is_some() {
for client in self.clients.iter_mut() {
client.handle.unbounded_send(
ClientControllerCommand::Disconnect
).unwrap();
}
return Ok(Async::Ready(()));
}
}
}
}
}
|
handle_message
|
identifier_name
|
issue-9951.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// pretty-expanded FIXME #23616
#![allow(unused_variables)]
trait Bar {
fn noop(&self);
}
impl Bar for u8 {
fn noop(&self) {}
}
fn
|
() {
let (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
let (c, d): (&Bar, &Bar) = (a, b);
let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
let (c, d): (&Bar, &Bar) = (&*a, &*b);
let (c, d): (&Bar, &Bar) = (&5, &9);
}
|
main
|
identifier_name
|
issue-9951.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// pretty-expanded FIXME #23616
#![allow(unused_variables)]
trait Bar {
fn noop(&self);
}
impl Bar for u8 {
fn noop(&self) {}
}
fn main() {
let (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
let (c, d): (&Bar, &Bar) = (a, b);
|
let (c, d): (&Bar, &Bar) = (&*a, &*b);
let (c, d): (&Bar, &Bar) = (&5, &9);
}
|
let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
|
random_line_split
|
issue-9951.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// pretty-expanded FIXME #23616
#![allow(unused_variables)]
trait Bar {
fn noop(&self);
}
impl Bar for u8 {
fn noop(&self) {}
}
fn main()
|
{
let (a, b) = (&5u8 as &Bar, &9u8 as &Bar);
let (c, d): (&Bar, &Bar) = (a, b);
let (a, b) = (Box::new(5u8) as Box<Bar>, Box::new(9u8) as Box<Bar>);
let (c, d): (&Bar, &Bar) = (&*a, &*b);
let (c, d): (&Bar, &Bar) = (&5, &9);
}
|
identifier_body
|
|
unsafe_rc.rs
|
use std::cell::UnsafeCell;
use std::rc::{Rc, Weak};
use std::ops::{Deref, DerefMut};
use std::hash::{Hash, Hasher};
pub struct
|
<T> {
value: Rc<UnsafeCell<T>>
}
impl<T> Hash for UnsafeRc<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.ptr().hash(state)
}
}
impl<T> PartialEq for UnsafeRc<T> {
fn eq(&self, other: &UnsafeRc<T>) -> bool {
self.ptr() == other.ptr()
}
}
impl<T> Eq for UnsafeRc<T> {}
impl<T> Clone for UnsafeRc<T> {
fn clone(&self) -> UnsafeRc<T> {
UnsafeRc::from_rc(self.value.clone())
}
}
impl<T> Deref for UnsafeRc<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe {
self.value.get().as_ref().unwrap()
}
}
}
impl<T> DerefMut for UnsafeRc<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe {
self.value.get().as_mut::<'a>().unwrap()
}
}
}
impl<T> UnsafeRc<T> {
pub fn new(v: T) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: Rc::new(UnsafeCell::new(v))
}
}
pub fn from_rc(v: Rc<UnsafeCell<T>>) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: v
}
}
pub fn downgrade(&self) -> UnsafeWeak<T> {
UnsafeWeak::from_weak(self.value.downgrade())
}
pub fn ptr(&self) -> *const T {
self.value.get()
}
}
pub struct UnsafeWeak<T> {
value: Weak<UnsafeCell<T>>
}
impl<T> UnsafeWeak<T> {
pub fn from_weak(r: Weak<UnsafeCell<T>>) -> UnsafeWeak<T> {
UnsafeWeak {
value: r
}
}
pub fn upgrade(&self) -> Option<UnsafeRc<T>> {
self.value.upgrade().map(UnsafeRc::from_rc)
}
}
impl<T> Hash for UnsafeWeak<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.upgrade().hash(state)
}
}
impl<T> PartialEq for UnsafeWeak<T> {
fn eq(&self, other: &UnsafeWeak<T>) -> bool {
self.upgrade() == other.upgrade()
}
}
impl<T> Eq for UnsafeWeak<T> {}
|
UnsafeRc
|
identifier_name
|
unsafe_rc.rs
|
use std::cell::UnsafeCell;
use std::rc::{Rc, Weak};
use std::ops::{Deref, DerefMut};
use std::hash::{Hash, Hasher};
pub struct UnsafeRc<T> {
value: Rc<UnsafeCell<T>>
}
impl<T> Hash for UnsafeRc<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.ptr().hash(state)
}
}
impl<T> PartialEq for UnsafeRc<T> {
fn eq(&self, other: &UnsafeRc<T>) -> bool {
self.ptr() == other.ptr()
}
}
impl<T> Eq for UnsafeRc<T> {}
impl<T> Clone for UnsafeRc<T> {
fn clone(&self) -> UnsafeRc<T> {
UnsafeRc::from_rc(self.value.clone())
}
}
impl<T> Deref for UnsafeRc<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe {
self.value.get().as_ref().unwrap()
}
}
}
impl<T> DerefMut for UnsafeRc<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe {
self.value.get().as_mut::<'a>().unwrap()
}
}
}
impl<T> UnsafeRc<T> {
pub fn new(v: T) -> UnsafeRc<T>
|
pub fn from_rc(v: Rc<UnsafeCell<T>>) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: v
}
}
pub fn downgrade(&self) -> UnsafeWeak<T> {
UnsafeWeak::from_weak(self.value.downgrade())
}
pub fn ptr(&self) -> *const T {
self.value.get()
}
}
pub struct UnsafeWeak<T> {
value: Weak<UnsafeCell<T>>
}
impl<T> UnsafeWeak<T> {
pub fn from_weak(r: Weak<UnsafeCell<T>>) -> UnsafeWeak<T> {
UnsafeWeak {
value: r
}
}
pub fn upgrade(&self) -> Option<UnsafeRc<T>> {
self.value.upgrade().map(UnsafeRc::from_rc)
}
}
impl<T> Hash for UnsafeWeak<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.upgrade().hash(state)
}
}
impl<T> PartialEq for UnsafeWeak<T> {
fn eq(&self, other: &UnsafeWeak<T>) -> bool {
self.upgrade() == other.upgrade()
}
}
impl<T> Eq for UnsafeWeak<T> {}
|
{
UnsafeRc::<T> {
value: Rc::new(UnsafeCell::new(v))
}
}
|
identifier_body
|
unsafe_rc.rs
|
use std::cell::UnsafeCell;
use std::rc::{Rc, Weak};
use std::ops::{Deref, DerefMut};
use std::hash::{Hash, Hasher};
pub struct UnsafeRc<T> {
value: Rc<UnsafeCell<T>>
}
impl<T> Hash for UnsafeRc<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.ptr().hash(state)
}
}
impl<T> PartialEq for UnsafeRc<T> {
fn eq(&self, other: &UnsafeRc<T>) -> bool {
self.ptr() == other.ptr()
}
}
|
impl<T> Clone for UnsafeRc<T> {
fn clone(&self) -> UnsafeRc<T> {
UnsafeRc::from_rc(self.value.clone())
}
}
impl<T> Deref for UnsafeRc<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe {
self.value.get().as_ref().unwrap()
}
}
}
impl<T> DerefMut for UnsafeRc<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe {
self.value.get().as_mut::<'a>().unwrap()
}
}
}
impl<T> UnsafeRc<T> {
pub fn new(v: T) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: Rc::new(UnsafeCell::new(v))
}
}
pub fn from_rc(v: Rc<UnsafeCell<T>>) -> UnsafeRc<T> {
UnsafeRc::<T> {
value: v
}
}
pub fn downgrade(&self) -> UnsafeWeak<T> {
UnsafeWeak::from_weak(self.value.downgrade())
}
pub fn ptr(&self) -> *const T {
self.value.get()
}
}
pub struct UnsafeWeak<T> {
value: Weak<UnsafeCell<T>>
}
impl<T> UnsafeWeak<T> {
pub fn from_weak(r: Weak<UnsafeCell<T>>) -> UnsafeWeak<T> {
UnsafeWeak {
value: r
}
}
pub fn upgrade(&self) -> Option<UnsafeRc<T>> {
self.value.upgrade().map(UnsafeRc::from_rc)
}
}
impl<T> Hash for UnsafeWeak<T> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.upgrade().hash(state)
}
}
impl<T> PartialEq for UnsafeWeak<T> {
fn eq(&self, other: &UnsafeWeak<T>) -> bool {
self.upgrade() == other.upgrade()
}
}
impl<T> Eq for UnsafeWeak<T> {}
|
impl<T> Eq for UnsafeRc<T> {}
|
random_line_split
|
main.rs
|
#![feature(plugin)]
#![feature(custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_redis;
extern crate rand;
extern crate redis;
extern crate serde;
extern crate serde_json;
use rocket_contrib::Template;
use rocket::http::{self, Cookie, RawStr};
use rocket::request::{self, FromFormValue};
use rocket::response::status;
use rocket::Outcome;
mod static_files;
mod db;
mod domain;
mod view_models;
mod controllers;
use db::redis::db_pool;
use domain::TodoFilter;
use domain::SessionId;
use controllers::root;
use controllers::todo;
use controllers::todos;
// Cookie session
const SESSION_ID_KEY: &'static str = "session_id";
pub struct CookieSessionId(SessionId);
impl From<CookieSessionId> for SessionId {
fn from(id: CookieSessionId) -> Self {
id.0
}
}
impl<'a, 'r> request::FromRequest<'a, 'r> for CookieSessionId {
type Error = ();
fn from_request(request: &'a request::Request<'r>) -> request::Outcome<CookieSessionId, ()> {
let id_from_cookie: Option<usize> = request
.cookies()
.get(SESSION_ID_KEY)
.and_then(|cookie| cookie.value().parse().ok());
let id = match id_from_cookie {
None => {
let random_id = rand::random::<usize>();
request
.cookies()
.add(Cookie::new(SESSION_ID_KEY, format!("{}", random_id)));
random_id
}
Some(id) => id,
};
Outcome::Success(CookieSessionId(id))
}
}
// Query params
#[derive(FromForm)]
pub struct QueryParams {
filter: TodoFilter,
}
pub fn todo_filter(filter: Option<QueryParams>) -> Result<TodoFilter, status::Custom<String>> {
Ok(filter.ok_or(invalid_filter_bad_request())?.filter)
}
fn invalid_filter_bad_request() -> status::Custom<String> {
status::Custom(http::Status::BadRequest, "Invalid filter".into())
}
impl<'v> FromFormValue<'v> for TodoFilter {
type Error = &'v RawStr;
fn
|
(value: &'v RawStr) -> Result<Self, Self::Error> {
let variant = match value.as_str() {
"all" => TodoFilter::All,
"active" => TodoFilter::Active,
"completed" => TodoFilter::Completed,
_ => return Err(value),
};
Ok(variant)
}
}
// Launch
fn main() {
let app = rocket::ignite();
let redis_pool = { db_pool(app.config()) };
app.mount("/", routes![root::index, static_files::all])
.mount("/todo", routes![todo::create, todo::update, todo::destroy])
.mount("/todos", routes![todos::show, todos::update])
.manage(redis_pool)
.attach(Template::fairing())
.launch();
}
|
from_form_value
|
identifier_name
|
main.rs
|
#![feature(plugin)]
#![feature(custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_redis;
extern crate rand;
extern crate redis;
extern crate serde;
extern crate serde_json;
use rocket_contrib::Template;
use rocket::http::{self, Cookie, RawStr};
use rocket::request::{self, FromFormValue};
use rocket::response::status;
use rocket::Outcome;
mod static_files;
mod db;
mod domain;
mod view_models;
mod controllers;
use db::redis::db_pool;
use domain::TodoFilter;
use domain::SessionId;
use controllers::root;
use controllers::todo;
use controllers::todos;
// Cookie session
const SESSION_ID_KEY: &'static str = "session_id";
pub struct CookieSessionId(SessionId);
impl From<CookieSessionId> for SessionId {
fn from(id: CookieSessionId) -> Self {
id.0
}
}
impl<'a, 'r> request::FromRequest<'a, 'r> for CookieSessionId {
type Error = ();
fn from_request(request: &'a request::Request<'r>) -> request::Outcome<CookieSessionId, ()> {
let id_from_cookie: Option<usize> = request
.cookies()
.get(SESSION_ID_KEY)
.and_then(|cookie| cookie.value().parse().ok());
let id = match id_from_cookie {
None => {
let random_id = rand::random::<usize>();
request
.cookies()
.add(Cookie::new(SESSION_ID_KEY, format!("{}", random_id)));
random_id
}
Some(id) => id,
};
Outcome::Success(CookieSessionId(id))
}
}
// Query params
#[derive(FromForm)]
pub struct QueryParams {
filter: TodoFilter,
}
pub fn todo_filter(filter: Option<QueryParams>) -> Result<TodoFilter, status::Custom<String>> {
Ok(filter.ok_or(invalid_filter_bad_request())?.filter)
}
fn invalid_filter_bad_request() -> status::Custom<String> {
status::Custom(http::Status::BadRequest, "Invalid filter".into())
}
|
fn from_form_value(value: &'v RawStr) -> Result<Self, Self::Error> {
let variant = match value.as_str() {
"all" => TodoFilter::All,
"active" => TodoFilter::Active,
"completed" => TodoFilter::Completed,
_ => return Err(value),
};
Ok(variant)
}
}
// Launch
fn main() {
let app = rocket::ignite();
let redis_pool = { db_pool(app.config()) };
app.mount("/", routes![root::index, static_files::all])
.mount("/todo", routes![todo::create, todo::update, todo::destroy])
.mount("/todos", routes![todos::show, todos::update])
.manage(redis_pool)
.attach(Template::fairing())
.launch();
}
|
impl<'v> FromFormValue<'v> for TodoFilter {
type Error = &'v RawStr;
|
random_line_split
|
main.rs
|
#![feature(plugin)]
#![feature(custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate serde_derive;
extern crate r2d2;
extern crate r2d2_redis;
extern crate rand;
extern crate redis;
extern crate serde;
extern crate serde_json;
use rocket_contrib::Template;
use rocket::http::{self, Cookie, RawStr};
use rocket::request::{self, FromFormValue};
use rocket::response::status;
use rocket::Outcome;
mod static_files;
mod db;
mod domain;
mod view_models;
mod controllers;
use db::redis::db_pool;
use domain::TodoFilter;
use domain::SessionId;
use controllers::root;
use controllers::todo;
use controllers::todos;
// Cookie session
const SESSION_ID_KEY: &'static str = "session_id";
pub struct CookieSessionId(SessionId);
impl From<CookieSessionId> for SessionId {
fn from(id: CookieSessionId) -> Self {
id.0
}
}
impl<'a, 'r> request::FromRequest<'a, 'r> for CookieSessionId {
type Error = ();
fn from_request(request: &'a request::Request<'r>) -> request::Outcome<CookieSessionId, ()> {
let id_from_cookie: Option<usize> = request
.cookies()
.get(SESSION_ID_KEY)
.and_then(|cookie| cookie.value().parse().ok());
let id = match id_from_cookie {
None =>
|
Some(id) => id,
};
Outcome::Success(CookieSessionId(id))
}
}
// Query params
#[derive(FromForm)]
pub struct QueryParams {
filter: TodoFilter,
}
pub fn todo_filter(filter: Option<QueryParams>) -> Result<TodoFilter, status::Custom<String>> {
Ok(filter.ok_or(invalid_filter_bad_request())?.filter)
}
fn invalid_filter_bad_request() -> status::Custom<String> {
status::Custom(http::Status::BadRequest, "Invalid filter".into())
}
impl<'v> FromFormValue<'v> for TodoFilter {
type Error = &'v RawStr;
fn from_form_value(value: &'v RawStr) -> Result<Self, Self::Error> {
let variant = match value.as_str() {
"all" => TodoFilter::All,
"active" => TodoFilter::Active,
"completed" => TodoFilter::Completed,
_ => return Err(value),
};
Ok(variant)
}
}
// Launch
fn main() {
let app = rocket::ignite();
let redis_pool = { db_pool(app.config()) };
app.mount("/", routes![root::index, static_files::all])
.mount("/todo", routes![todo::create, todo::update, todo::destroy])
.mount("/todos", routes![todos::show, todos::update])
.manage(redis_pool)
.attach(Template::fairing())
.launch();
}
|
{
let random_id = rand::random::<usize>();
request
.cookies()
.add(Cookie::new(SESSION_ID_KEY, format!("{}", random_id)));
random_id
}
|
conditional_block
|
next_back.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::Fuse;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn fuse(self) -> Fuse<Self> where Self: Sized {
// Fuse{iter: self, done: false}
// }
}
}
}
impl DoubleEndedIterator for A<T> {
fn
|
(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
} else {
None::<Self::Item>
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
// #[inline]
// fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
// if self.done {
// None
// } else {
// let next = self.iter.next_back();
// self.done = next.is_none();
// next
// }
// }
// }
#[test]
fn next_back_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let mut fuse: Fuse<A<T>> = a.fuse();
for x in 0..10 {
let y: Option<T> = fuse.next_back();
match y {
Some(v) => { assert_eq!(v, 9 - x); }
None => { assert!(false); }
}
}
assert_eq!(fuse.next(), None::<T>);
}
}
|
next_back
|
identifier_name
|
next_back.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
|
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn fuse(self) -> Fuse<Self> where Self: Sized {
// Fuse{iter: self, done: false}
// }
}
}
}
impl DoubleEndedIterator for A<T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
} else {
None::<Self::Item>
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
// #[inline]
// fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
// if self.done {
// None
// } else {
// let next = self.iter.next_back();
// self.done = next.is_none();
// next
// }
// }
// }
#[test]
fn next_back_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let mut fuse: Fuse<A<T>> = a.fuse();
for x in 0..10 {
let y: Option<T> = fuse.next_back();
match y {
Some(v) => { assert_eq!(v, 9 - x); }
None => { assert!(false); }
}
}
assert_eq!(fuse.next(), None::<T>);
}
}
|
use core::iter::Fuse;
struct A<T> {
begin: T,
end: T
|
random_line_split
|
next_back.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::DoubleEndedIterator;
use core::iter::Fuse;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn fuse(self) -> Fuse<Self> where Self: Sized {
// Fuse{iter: self, done: false}
// }
}
}
}
impl DoubleEndedIterator for A<T> {
fn next_back(&mut self) -> Option<Self::Item> {
if self.begin < self.end
|
else {
None::<Self::Item>
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I> DoubleEndedIterator for Fuse<I> where I: DoubleEndedIterator {
// #[inline]
// fn next_back(&mut self) -> Option<<I as Iterator>::Item> {
// if self.done {
// None
// } else {
// let next = self.iter.next_back();
// self.done = next.is_none();
// next
// }
// }
// }
#[test]
fn next_back_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let mut fuse: Fuse<A<T>> = a.fuse();
for x in 0..10 {
let y: Option<T> = fuse.next_back();
match y {
Some(v) => { assert_eq!(v, 9 - x); }
None => { assert!(false); }
}
}
assert_eq!(fuse.next(), None::<T>);
}
}
|
{
self.end = self.end.wrapping_sub(1);
Some::<Self::Item>(self.end)
}
|
conditional_block
|
issue-3424.rs
|
// xfail-fast
// 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.
// rustc --test ignores2.rs &&./ignores2
extern mod std;
use core::path::{Path};
type rsrc_loader = ~fn(path: &Path) -> result::Result<~str, ~str>;
#[test]
fn
|
()
{
let loader: rsrc_loader = |_path| {result::Ok(~"more blah")};
let path = path::from_str("blah");
assert!(loader(&path).is_ok());
}
pub fn main() {}
|
tester
|
identifier_name
|
issue-3424.rs
|
// xfail-fast
// 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.
// rustc --test ignores2.rs &&./ignores2
extern mod std;
use core::path::{Path};
type rsrc_loader = ~fn(path: &Path) -> result::Result<~str, ~str>;
#[test]
fn tester()
{
|
}
pub fn main() {}
|
let loader: rsrc_loader = |_path| {result::Ok(~"more blah")};
let path = path::from_str("blah");
assert!(loader(&path).is_ok());
|
random_line_split
|
issue-3424.rs
|
// xfail-fast
// 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.
// rustc --test ignores2.rs &&./ignores2
extern mod std;
use core::path::{Path};
type rsrc_loader = ~fn(path: &Path) -> result::Result<~str, ~str>;
#[test]
fn tester()
{
let loader: rsrc_loader = |_path| {result::Ok(~"more blah")};
let path = path::from_str("blah");
assert!(loader(&path).is_ok());
}
pub fn main()
|
{}
|
identifier_body
|
|
drawing.rs
|
use std::char;
use std::cmp::{max, min};
use std::collections::VecDeque;
use num::{Complex, Float};
use rustty::{Attr, Color, Terminal, Cell, CellAccessor, HasSize};
use rustty::ui::{Alignable, Widget, VerticalAlign, HorizontalAlign};
use itertools::{Itertools, EitherOrBoth};
use std::io;
pub struct Canvas {
term: Terminal,
spectrum: Widget,
waterfall: Widget,
history: VecDeque<Vec<f32>>,
}
impl Canvas {
pub fn new() -> Result<Self, io::Error> {
let term = try!(Terminal::new());
let mut canvas = Canvas {
term: term,
spectrum: Widget::new(0, 0),
waterfall: Widget::new(0, 0),
history: VecDeque::new(),
};
canvas.resize();
Ok(canvas)
}
fn resize(&mut self) {
let (cols, rows) = self.term.size();
let spectrum_height = rows / 2;
let waterfall_height = if rows % 2 == 0 { rows / 2 } else { rows / 2 + 1 };
self.spectrum = Widget::new(cols, spectrum_height);
self.spectrum.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Top, 0);
self.waterfall = Widget::new(cols, waterfall_height);
self.waterfall.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Bottom, 0);
self.history.reserve(waterfall_height * 2);
}
fn check_and_resize(&mut self) {
let (cols, rows) = self.term.size();
let (spectrum_cols, spectrum_rows) = self.spectrum.size();
let (waterfall_cols, waterfall_rows) = self.waterfall.size();
// if the terminal size has changed...
if cols!= spectrum_cols || cols!= waterfall_cols ||
rows!= (spectrum_rows + waterfall_rows) {
self.resize();
}
}
/// Adds a spectrum to the history and draws it on the waterfall
/// and the spectrum view.
pub fn add_spectrum(&mut self, spec: Vec<Complex<f32>>) {
let normalized = normalize_spectrum(&spec, 50.0);
draw_spectrum(&mut self.spectrum, &normalized);
// Since the waterfall has half the horizontal resolution of the spectrum view,
// average every two values and store the averaged spectrum.
let averaged = normalized.chunks(2).map(|v| (v[0] + v[1]) / 2.0).collect();
// push spectrum onto the history
self.history.push_front(averaged);
let (_, rows) = self.waterfall.size();
if self.history.len() >= rows * 2 {
self.history.pop_back();
}
draw_waterfall(&mut self.waterfall, &self.history);
self.spectrum.draw_into(&mut self.term);
self.waterfall.draw_into(&mut self.term);
self.term.swap_buffers().unwrap();
self.check_and_resize();
}
pub fn get_term(&mut self) -> &mut Terminal {
&mut self.term
}
pub fn get_spectrum_width(&self) -> usize {
2 * self.term.cols()
}
}
fn draw_waterfall<T: CellAccessor + HasSize>(canvas: &mut T, spectra: &VecDeque<Vec<f32>>) {
let (cols, rows) = canvas.size();
for (row, mut specs) in (0..rows).zip(&spectra.iter().chunks_lazy(2)) {
let upper_heights = specs.next().into_iter().flat_map(|x| x);
let lower_heights = specs.next().into_iter().flat_map(|x| x);
for (c, heights) in (0..cols).zip(upper_heights.zip_longest(lower_heights)) {
let (u, l) = match heights {
EitherOrBoth::Both(&upper, &lower) => (upper, lower),
EitherOrBoth::Left(&upper) => (upper, 0.0),
EitherOrBoth::Right(&lower) => (0.0, lower),
};
*canvas.get_mut(c, row).unwrap() = spectrum_heights_to_waterfall_cell(u, l);
}
}
}
fn spectrum_heights_to_waterfall_cell(upper: f32, lower: f32) -> Cell {
Cell::new('▀',
Color::Byte(color_mapping(upper)),
Color::Byte(color_mapping(lower)),
Attr::Default)
}
/// Assumes `f` is between 0 and 1. Anything outside of this range
/// will be clamped.
fn color_mapping(f: f32) -> u8 {
let mapping = [16, 17, 18, 19, 21, 27, 33, 39, 45, 51,
50, 49, 48, 47, 46, 82, 118, 154, 190, 226];
let idx = (f * (mapping.len() as f32)) as i32;
if idx < 0 {
mapping[0]
} else if idx >= mapping.len() as i32 {
mapping[mapping.len() - 1]
} else {
mapping[idx as usize]
}
}
fn normalize_spectrum(spec: &[Complex<f32>], max_db: f32) -> Vec<f32> {
// FFT shift
let (first_half, last_half) = spec.split_at((spec.len() + 1) / 2);
let shifted_spec = last_half.iter().chain(first_half.iter());
// normalize and take the log
shifted_spec.map(Complex::norm)
.map(Float::log10)
.map(|x| 10.0 * x)
.map(|x| x / max_db)
.collect()
}
// indexing is from the top of the cell
fn pixel_nums_to_braille(p1: Option<u8>, p2: Option<u8>) -> char {
let pixel_map = [[0x01, 0x08],
[0x02, 0x10],
[0x04, 0x20],
[0x40, 0x80]];
let mut c = 0;
if let Some(p) = p1 {
for i in p..4 {
c |= pixel_map[i as usize][0];
}
}
if let Some(p) = p2 {
for i in p..4 {
c |= pixel_map[i as usize][1];
}
}
char::from_u32((0x2800 + c) as u32).unwrap()
}
fn char_to_cell(c: char) -> Cell {
let mut cell = Cell::with_char(c);
cell.set_attrs(Attr::Bold);
cell
}
fn draw_pixel_pair<T>(canvas: &mut T, col_idx: usize, p1: usize, p2: usize)
where T: CellAccessor + HasSize
{
let (_, rows) = canvas.size();
let max_pixel_height = 4 * rows;
// clamp heights
let p1 = if p1 >= max_pixel_height { max_pixel_height - 1} else { p1 };
let p2 = if p2 >= max_pixel_height { max_pixel_height - 1} else { p2 };
// Reverse it, since the terminal indexing is from the top
let p1 = max_pixel_height - p1 - 1;
let p2 = max_pixel_height - p2 - 1;
// cell indices
let c1 = p1 / 4;
let c2 = p2 / 4;
// Fill in full height cells.
let full_cell_char = pixel_nums_to_braille(Some(0), Some(0));
for row_idx in max(c1, c2)..rows {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(full_cell_char);
}
let left_fill_cell_char = pixel_nums_to_braille(Some(0), None);
for row_idx in min(c1, c2)..c2 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(left_fill_cell_char);
}
let right_fill_cell_char = pixel_nums_to_braille(None, Some(0));
for row_idx in min(c1, c2)..c1 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(right_fill_cell_char);
}
// Now fill in partial height cells.
if c1 == c2 {
// top pixels are in the same cell
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some((p2 % 4) as u8)));
} else if c1 > c2 {
// right pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some(0)));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(None, Some((p2 % 4) as u8)));
} else {
// left pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), None));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(Some(0), Some((p2 % 4) as u8)));
}
}
fn draw_spectrum<T: CellAccessor + HasSize>(canvas: &mut T, spec: &[f32]) {
canvas.clear(Cell::default());
let (num_cols, num_rows) = canvas.size();
let pixel_height = num_rows * 4;
for (col_idx, chunk) in (0..num_cols).zip(spec.chunks(2)) {
// height in float between 0 and 1.
let h1 = chunk[0];
let h2 = chunk[1];
// The "pixel" height of each point.
let p1 = (h1 * pixel_height as f32).floor().max(0.0) as usize;
let p2 = (h2 * pixel_height as f32).floor().max(0.0) as usize;
draw_pixel_pair(canvas, col_idx, p1, p2);
|
}
}
#[cfg(test)]
mod tests {
use super::{pixel_nums_to_braille, draw_pixel_pair};
use rustty::Terminal;
#[test]
fn test_pixel_nums() {
assert_eq!(pixel_nums_to_braille(Some(0), Some(0)), '⣿');
assert_eq!(pixel_nums_to_braille(Some(1), Some(2)), '⣦');
assert_eq!(pixel_nums_to_braille(None, Some(3)), '⢀');
assert_eq!(pixel_nums_to_braille(Some(2), None), '⡄');
assert_eq!(pixel_nums_to_braille(None, None), '⠀');
}
#[test]
fn test_draw_pixel_pair() {
let mut term = Terminal::new().unwrap();
// Test drawing with the same top cell
draw_pixel_pair(&mut term, 0, 4, 6);
assert_eq!(term[(0, term.rows() - 3)].ch(),'');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣰');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
// Test drawing with the top pixel in each column being in
// different cells
draw_pixel_pair(&mut term, 0, 4, 8);
assert_eq!(term[(0, term.rows() - 4)].ch(),'');
assert_eq!(term[(0, term.rows() - 3)].ch(), '⢀');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣸');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
draw_pixel_pair(&mut term, 1, 13, 2);
assert_eq!(term[(1, term.rows() - 5)].ch(),'');
assert_eq!(term[(1, term.rows() - 4)].ch(), '⡄');
assert_eq!(term[(1, term.rows() - 3)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 2)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 1)].ch(), '⣷');
term.clear().unwrap();
}
}
|
random_line_split
|
|
drawing.rs
|
use std::char;
use std::cmp::{max, min};
use std::collections::VecDeque;
use num::{Complex, Float};
use rustty::{Attr, Color, Terminal, Cell, CellAccessor, HasSize};
use rustty::ui::{Alignable, Widget, VerticalAlign, HorizontalAlign};
use itertools::{Itertools, EitherOrBoth};
use std::io;
pub struct Canvas {
term: Terminal,
spectrum: Widget,
waterfall: Widget,
history: VecDeque<Vec<f32>>,
}
impl Canvas {
pub fn new() -> Result<Self, io::Error> {
let term = try!(Terminal::new());
let mut canvas = Canvas {
term: term,
spectrum: Widget::new(0, 0),
waterfall: Widget::new(0, 0),
history: VecDeque::new(),
};
canvas.resize();
Ok(canvas)
}
fn resize(&mut self) {
let (cols, rows) = self.term.size();
let spectrum_height = rows / 2;
let waterfall_height = if rows % 2 == 0 { rows / 2 } else { rows / 2 + 1 };
self.spectrum = Widget::new(cols, spectrum_height);
self.spectrum.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Top, 0);
self.waterfall = Widget::new(cols, waterfall_height);
self.waterfall.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Bottom, 0);
self.history.reserve(waterfall_height * 2);
}
fn check_and_resize(&mut self) {
let (cols, rows) = self.term.size();
let (spectrum_cols, spectrum_rows) = self.spectrum.size();
let (waterfall_cols, waterfall_rows) = self.waterfall.size();
// if the terminal size has changed...
if cols!= spectrum_cols || cols!= waterfall_cols ||
rows!= (spectrum_rows + waterfall_rows) {
self.resize();
}
}
/// Adds a spectrum to the history and draws it on the waterfall
/// and the spectrum view.
pub fn add_spectrum(&mut self, spec: Vec<Complex<f32>>) {
let normalized = normalize_spectrum(&spec, 50.0);
draw_spectrum(&mut self.spectrum, &normalized);
// Since the waterfall has half the horizontal resolution of the spectrum view,
// average every two values and store the averaged spectrum.
let averaged = normalized.chunks(2).map(|v| (v[0] + v[1]) / 2.0).collect();
// push spectrum onto the history
self.history.push_front(averaged);
let (_, rows) = self.waterfall.size();
if self.history.len() >= rows * 2 {
self.history.pop_back();
}
draw_waterfall(&mut self.waterfall, &self.history);
self.spectrum.draw_into(&mut self.term);
self.waterfall.draw_into(&mut self.term);
self.term.swap_buffers().unwrap();
self.check_and_resize();
}
pub fn get_term(&mut self) -> &mut Terminal {
&mut self.term
}
pub fn get_spectrum_width(&self) -> usize {
2 * self.term.cols()
}
}
fn draw_waterfall<T: CellAccessor + HasSize>(canvas: &mut T, spectra: &VecDeque<Vec<f32>>) {
let (cols, rows) = canvas.size();
for (row, mut specs) in (0..rows).zip(&spectra.iter().chunks_lazy(2)) {
let upper_heights = specs.next().into_iter().flat_map(|x| x);
let lower_heights = specs.next().into_iter().flat_map(|x| x);
for (c, heights) in (0..cols).zip(upper_heights.zip_longest(lower_heights)) {
let (u, l) = match heights {
EitherOrBoth::Both(&upper, &lower) => (upper, lower),
EitherOrBoth::Left(&upper) => (upper, 0.0),
EitherOrBoth::Right(&lower) => (0.0, lower),
};
*canvas.get_mut(c, row).unwrap() = spectrum_heights_to_waterfall_cell(u, l);
}
}
}
fn spectrum_heights_to_waterfall_cell(upper: f32, lower: f32) -> Cell {
Cell::new('▀',
Color::Byte(color_mapping(upper)),
Color::Byte(color_mapping(lower)),
Attr::Default)
}
/// Assumes `f` is between 0 and 1. Anything outside of this range
/// will be clamped.
fn color_mapping(f: f32) -> u8 {
let mapping = [16, 17, 18, 19, 21, 27, 33, 39, 45, 51,
50, 49, 48, 47, 46, 82, 118, 154, 190, 226];
let idx = (f * (mapping.len() as f32)) as i32;
if idx < 0 {
mapping[0]
} else if idx >= mapping.len() as i32 {
mapping[mapping.len() - 1]
} else {
mapping[idx as usize]
}
}
fn normalize_spectrum(spec: &[Complex<f32>], max_db: f32) -> Vec<f32> {
// FFT shift
let (first_half, last_half) = spec.split_at((spec.len() + 1) / 2);
let shifted_spec = last_half.iter().chain(first_half.iter());
// normalize and take the log
shifted_spec.map(Complex::norm)
.map(Float::log10)
.map(|x| 10.0 * x)
.map(|x| x / max_db)
.collect()
}
// indexing is from the top of the cell
fn pixel_nums_to_braille(p1: Option<u8>, p2: Option<u8>) -> char {
let pixel_map = [[0x01, 0x08],
[0x02, 0x10],
[0x04, 0x20],
[0x40, 0x80]];
let mut c = 0;
if let Some(p) = p1 {
for i in p..4 {
c |= pixel_map[i as usize][0];
}
}
if let Some(p) = p2 {
|
char::from_u32((0x2800 + c) as u32).unwrap()
}
fn char_to_cell(c: char) -> Cell {
let mut cell = Cell::with_char(c);
cell.set_attrs(Attr::Bold);
cell
}
fn draw_pixel_pair<T>(canvas: &mut T, col_idx: usize, p1: usize, p2: usize)
where T: CellAccessor + HasSize
{
let (_, rows) = canvas.size();
let max_pixel_height = 4 * rows;
// clamp heights
let p1 = if p1 >= max_pixel_height { max_pixel_height - 1} else { p1 };
let p2 = if p2 >= max_pixel_height { max_pixel_height - 1} else { p2 };
// Reverse it, since the terminal indexing is from the top
let p1 = max_pixel_height - p1 - 1;
let p2 = max_pixel_height - p2 - 1;
// cell indices
let c1 = p1 / 4;
let c2 = p2 / 4;
// Fill in full height cells.
let full_cell_char = pixel_nums_to_braille(Some(0), Some(0));
for row_idx in max(c1, c2)..rows {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(full_cell_char);
}
let left_fill_cell_char = pixel_nums_to_braille(Some(0), None);
for row_idx in min(c1, c2)..c2 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(left_fill_cell_char);
}
let right_fill_cell_char = pixel_nums_to_braille(None, Some(0));
for row_idx in min(c1, c2)..c1 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(right_fill_cell_char);
}
// Now fill in partial height cells.
if c1 == c2 {
// top pixels are in the same cell
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some((p2 % 4) as u8)));
} else if c1 > c2 {
// right pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some(0)));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(None, Some((p2 % 4) as u8)));
} else {
// left pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), None));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(Some(0), Some((p2 % 4) as u8)));
}
}
fn draw_spectrum<T: CellAccessor + HasSize>(canvas: &mut T, spec: &[f32]) {
canvas.clear(Cell::default());
let (num_cols, num_rows) = canvas.size();
let pixel_height = num_rows * 4;
for (col_idx, chunk) in (0..num_cols).zip(spec.chunks(2)) {
// height in float between 0 and 1.
let h1 = chunk[0];
let h2 = chunk[1];
// The "pixel" height of each point.
let p1 = (h1 * pixel_height as f32).floor().max(0.0) as usize;
let p2 = (h2 * pixel_height as f32).floor().max(0.0) as usize;
draw_pixel_pair(canvas, col_idx, p1, p2);
}
}
#[cfg(test)]
mod tests {
use super::{pixel_nums_to_braille, draw_pixel_pair};
use rustty::Terminal;
#[test]
fn test_pixel_nums() {
assert_eq!(pixel_nums_to_braille(Some(0), Some(0)), '⣿');
assert_eq!(pixel_nums_to_braille(Some(1), Some(2)), '⣦');
assert_eq!(pixel_nums_to_braille(None, Some(3)), '⢀');
assert_eq!(pixel_nums_to_braille(Some(2), None), '⡄');
assert_eq!(pixel_nums_to_braille(None, None), '⠀');
}
#[test]
fn test_draw_pixel_pair() {
let mut term = Terminal::new().unwrap();
// Test drawing with the same top cell
draw_pixel_pair(&mut term, 0, 4, 6);
assert_eq!(term[(0, term.rows() - 3)].ch(),'');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣰');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
// Test drawing with the top pixel in each column being in
// different cells
draw_pixel_pair(&mut term, 0, 4, 8);
assert_eq!(term[(0, term.rows() - 4)].ch(),'');
assert_eq!(term[(0, term.rows() - 3)].ch(), '⢀');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣸');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
draw_pixel_pair(&mut term, 1, 13, 2);
assert_eq!(term[(1, term.rows() - 5)].ch(),'');
assert_eq!(term[(1, term.rows() - 4)].ch(), '⡄');
assert_eq!(term[(1, term.rows() - 3)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 2)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 1)].ch(), '⣷');
term.clear().unwrap();
}
}
|
for i in p..4 {
c |= pixel_map[i as usize][1];
}
}
|
conditional_block
|
drawing.rs
|
use std::char;
use std::cmp::{max, min};
use std::collections::VecDeque;
use num::{Complex, Float};
use rustty::{Attr, Color, Terminal, Cell, CellAccessor, HasSize};
use rustty::ui::{Alignable, Widget, VerticalAlign, HorizontalAlign};
use itertools::{Itertools, EitherOrBoth};
use std::io;
pub struct Canvas {
term: Terminal,
spectrum: Widget,
waterfall: Widget,
history: VecDeque<Vec<f32>>,
}
impl Canvas {
pub fn new() -> Result<Self, io::Error> {
let term = try!(Terminal::new());
let mut canvas = Canvas {
term: term,
spectrum: Widget::new(0, 0),
waterfall: Widget::new(0, 0),
history: VecDeque::new(),
};
canvas.resize();
Ok(canvas)
}
fn resize(&mut self) {
let (cols, rows) = self.term.size();
let spectrum_height = rows / 2;
let waterfall_height = if rows % 2 == 0 { rows / 2 } else { rows / 2 + 1 };
self.spectrum = Widget::new(cols, spectrum_height);
self.spectrum.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Top, 0);
self.waterfall = Widget::new(cols, waterfall_height);
self.waterfall.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Bottom, 0);
self.history.reserve(waterfall_height * 2);
}
fn check_and_resize(&mut self) {
let (cols, rows) = self.term.size();
let (spectrum_cols, spectrum_rows) = self.spectrum.size();
let (waterfall_cols, waterfall_rows) = self.waterfall.size();
// if the terminal size has changed...
if cols!= spectrum_cols || cols!= waterfall_cols ||
rows!= (spectrum_rows + waterfall_rows) {
self.resize();
}
}
/// Adds a spectrum to the history and draws it on the waterfall
/// and the spectrum view.
pub fn add_spectrum(&mut self, spec: Vec<Complex<f32>>) {
let normalized = normalize_spectrum(&spec, 50.0);
draw_spectrum(&mut self.spectrum, &normalized);
// Since the waterfall has half the horizontal resolution of the spectrum view,
// average every two values and store the averaged spectrum.
let averaged = normalized.chunks(2).map(|v| (v[0] + v[1]) / 2.0).collect();
// push spectrum onto the history
self.history.push_front(averaged);
let (_, rows) = self.waterfall.size();
if self.history.len() >= rows * 2 {
self.history.pop_back();
}
draw_waterfall(&mut self.waterfall, &self.history);
self.spectrum.draw_into(&mut self.term);
self.waterfall.draw_into(&mut self.term);
self.term.swap_buffers().unwrap();
self.check_and_resize();
}
pub fn get_term(&mut self) -> &mut Terminal {
&mut self.term
}
pub fn get_spectrum_width(&self) -> usize {
2 * self.term.cols()
}
}
fn draw_waterfall<T: CellAccessor + HasSize>(canvas: &mut T, spectra: &VecDeque<Vec<f32>>) {
let (cols, rows) = canvas.size();
for (row, mut specs) in (0..rows).zip(&spectra.iter().chunks_lazy(2)) {
let upper_heights = specs.next().into_iter().flat_map(|x| x);
let lower_heights = specs.next().into_iter().flat_map(|x| x);
for (c, heights) in (0..cols).zip(upper_heights.zip_longest(lower_heights)) {
let (u, l) = match heights {
EitherOrBoth::Both(&upper, &lower) => (upper, lower),
EitherOrBoth::Left(&upper) => (upper, 0.0),
EitherOrBoth::Right(&lower) => (0.0, lower),
};
*canvas.get_mut(c, row).unwrap() = spectrum_heights_to_waterfall_cell(u, l);
}
}
}
fn spectrum_heights_to_waterfall_cell(upper: f32, lower: f32) -> Cell
|
/// Assumes `f` is between 0 and 1. Anything outside of this range
/// will be clamped.
fn color_mapping(f: f32) -> u8 {
let mapping = [16, 17, 18, 19, 21, 27, 33, 39, 45, 51,
50, 49, 48, 47, 46, 82, 118, 154, 190, 226];
let idx = (f * (mapping.len() as f32)) as i32;
if idx < 0 {
mapping[0]
} else if idx >= mapping.len() as i32 {
mapping[mapping.len() - 1]
} else {
mapping[idx as usize]
}
}
fn normalize_spectrum(spec: &[Complex<f32>], max_db: f32) -> Vec<f32> {
// FFT shift
let (first_half, last_half) = spec.split_at((spec.len() + 1) / 2);
let shifted_spec = last_half.iter().chain(first_half.iter());
// normalize and take the log
shifted_spec.map(Complex::norm)
.map(Float::log10)
.map(|x| 10.0 * x)
.map(|x| x / max_db)
.collect()
}
// indexing is from the top of the cell
fn pixel_nums_to_braille(p1: Option<u8>, p2: Option<u8>) -> char {
let pixel_map = [[0x01, 0x08],
[0x02, 0x10],
[0x04, 0x20],
[0x40, 0x80]];
let mut c = 0;
if let Some(p) = p1 {
for i in p..4 {
c |= pixel_map[i as usize][0];
}
}
if let Some(p) = p2 {
for i in p..4 {
c |= pixel_map[i as usize][1];
}
}
char::from_u32((0x2800 + c) as u32).unwrap()
}
fn char_to_cell(c: char) -> Cell {
let mut cell = Cell::with_char(c);
cell.set_attrs(Attr::Bold);
cell
}
fn draw_pixel_pair<T>(canvas: &mut T, col_idx: usize, p1: usize, p2: usize)
where T: CellAccessor + HasSize
{
let (_, rows) = canvas.size();
let max_pixel_height = 4 * rows;
// clamp heights
let p1 = if p1 >= max_pixel_height { max_pixel_height - 1} else { p1 };
let p2 = if p2 >= max_pixel_height { max_pixel_height - 1} else { p2 };
// Reverse it, since the terminal indexing is from the top
let p1 = max_pixel_height - p1 - 1;
let p2 = max_pixel_height - p2 - 1;
// cell indices
let c1 = p1 / 4;
let c2 = p2 / 4;
// Fill in full height cells.
let full_cell_char = pixel_nums_to_braille(Some(0), Some(0));
for row_idx in max(c1, c2)..rows {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(full_cell_char);
}
let left_fill_cell_char = pixel_nums_to_braille(Some(0), None);
for row_idx in min(c1, c2)..c2 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(left_fill_cell_char);
}
let right_fill_cell_char = pixel_nums_to_braille(None, Some(0));
for row_idx in min(c1, c2)..c1 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(right_fill_cell_char);
}
// Now fill in partial height cells.
if c1 == c2 {
// top pixels are in the same cell
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some((p2 % 4) as u8)));
} else if c1 > c2 {
// right pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some(0)));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(None, Some((p2 % 4) as u8)));
} else {
// left pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), None));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(Some(0), Some((p2 % 4) as u8)));
}
}
fn draw_spectrum<T: CellAccessor + HasSize>(canvas: &mut T, spec: &[f32]) {
canvas.clear(Cell::default());
let (num_cols, num_rows) = canvas.size();
let pixel_height = num_rows * 4;
for (col_idx, chunk) in (0..num_cols).zip(spec.chunks(2)) {
// height in float between 0 and 1.
let h1 = chunk[0];
let h2 = chunk[1];
// The "pixel" height of each point.
let p1 = (h1 * pixel_height as f32).floor().max(0.0) as usize;
let p2 = (h2 * pixel_height as f32).floor().max(0.0) as usize;
draw_pixel_pair(canvas, col_idx, p1, p2);
}
}
#[cfg(test)]
mod tests {
use super::{pixel_nums_to_braille, draw_pixel_pair};
use rustty::Terminal;
#[test]
fn test_pixel_nums() {
assert_eq!(pixel_nums_to_braille(Some(0), Some(0)), '⣿');
assert_eq!(pixel_nums_to_braille(Some(1), Some(2)), '⣦');
assert_eq!(pixel_nums_to_braille(None, Some(3)), '⢀');
assert_eq!(pixel_nums_to_braille(Some(2), None), '⡄');
assert_eq!(pixel_nums_to_braille(None, None), '⠀');
}
#[test]
fn test_draw_pixel_pair() {
let mut term = Terminal::new().unwrap();
// Test drawing with the same top cell
draw_pixel_pair(&mut term, 0, 4, 6);
assert_eq!(term[(0, term.rows() - 3)].ch(),'');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣰');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
// Test drawing with the top pixel in each column being in
// different cells
draw_pixel_pair(&mut term, 0, 4, 8);
assert_eq!(term[(0, term.rows() - 4)].ch(),'');
assert_eq!(term[(0, term.rows() - 3)].ch(), '⢀');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣸');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
draw_pixel_pair(&mut term, 1, 13, 2);
assert_eq!(term[(1, term.rows() - 5)].ch(),'');
assert_eq!(term[(1, term.rows() - 4)].ch(), '⡄');
assert_eq!(term[(1, term.rows() - 3)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 2)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 1)].ch(), '⣷');
term.clear().unwrap();
}
}
|
{
Cell::new('▀',
Color::Byte(color_mapping(upper)),
Color::Byte(color_mapping(lower)),
Attr::Default)
}
|
identifier_body
|
drawing.rs
|
use std::char;
use std::cmp::{max, min};
use std::collections::VecDeque;
use num::{Complex, Float};
use rustty::{Attr, Color, Terminal, Cell, CellAccessor, HasSize};
use rustty::ui::{Alignable, Widget, VerticalAlign, HorizontalAlign};
use itertools::{Itertools, EitherOrBoth};
use std::io;
pub struct Canvas {
term: Terminal,
spectrum: Widget,
waterfall: Widget,
history: VecDeque<Vec<f32>>,
}
impl Canvas {
pub fn new() -> Result<Self, io::Error> {
let term = try!(Terminal::new());
let mut canvas = Canvas {
term: term,
spectrum: Widget::new(0, 0),
waterfall: Widget::new(0, 0),
history: VecDeque::new(),
};
canvas.resize();
Ok(canvas)
}
fn resize(&mut self) {
let (cols, rows) = self.term.size();
let spectrum_height = rows / 2;
let waterfall_height = if rows % 2 == 0 { rows / 2 } else { rows / 2 + 1 };
self.spectrum = Widget::new(cols, spectrum_height);
self.spectrum.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Top, 0);
self.waterfall = Widget::new(cols, waterfall_height);
self.waterfall.align(&self.term, HorizontalAlign::Middle, VerticalAlign::Bottom, 0);
self.history.reserve(waterfall_height * 2);
}
fn check_and_resize(&mut self) {
let (cols, rows) = self.term.size();
let (spectrum_cols, spectrum_rows) = self.spectrum.size();
let (waterfall_cols, waterfall_rows) = self.waterfall.size();
// if the terminal size has changed...
if cols!= spectrum_cols || cols!= waterfall_cols ||
rows!= (spectrum_rows + waterfall_rows) {
self.resize();
}
}
/// Adds a spectrum to the history and draws it on the waterfall
/// and the spectrum view.
pub fn add_spectrum(&mut self, spec: Vec<Complex<f32>>) {
let normalized = normalize_spectrum(&spec, 50.0);
draw_spectrum(&mut self.spectrum, &normalized);
// Since the waterfall has half the horizontal resolution of the spectrum view,
// average every two values and store the averaged spectrum.
let averaged = normalized.chunks(2).map(|v| (v[0] + v[1]) / 2.0).collect();
// push spectrum onto the history
self.history.push_front(averaged);
let (_, rows) = self.waterfall.size();
if self.history.len() >= rows * 2 {
self.history.pop_back();
}
draw_waterfall(&mut self.waterfall, &self.history);
self.spectrum.draw_into(&mut self.term);
self.waterfall.draw_into(&mut self.term);
self.term.swap_buffers().unwrap();
self.check_and_resize();
}
pub fn get_term(&mut self) -> &mut Terminal {
&mut self.term
}
pub fn get_spectrum_width(&self) -> usize {
2 * self.term.cols()
}
}
fn draw_waterfall<T: CellAccessor + HasSize>(canvas: &mut T, spectra: &VecDeque<Vec<f32>>) {
let (cols, rows) = canvas.size();
for (row, mut specs) in (0..rows).zip(&spectra.iter().chunks_lazy(2)) {
let upper_heights = specs.next().into_iter().flat_map(|x| x);
let lower_heights = specs.next().into_iter().flat_map(|x| x);
for (c, heights) in (0..cols).zip(upper_heights.zip_longest(lower_heights)) {
let (u, l) = match heights {
EitherOrBoth::Both(&upper, &lower) => (upper, lower),
EitherOrBoth::Left(&upper) => (upper, 0.0),
EitherOrBoth::Right(&lower) => (0.0, lower),
};
*canvas.get_mut(c, row).unwrap() = spectrum_heights_to_waterfall_cell(u, l);
}
}
}
fn spectrum_heights_to_waterfall_cell(upper: f32, lower: f32) -> Cell {
Cell::new('▀',
Color::Byte(color_mapping(upper)),
Color::Byte(color_mapping(lower)),
Attr::Default)
}
/// Assumes `f` is between 0 and 1. Anything outside of this range
/// will be clamped.
fn color_mapping(f: f32) -> u8 {
let mapping = [16, 17, 18, 19, 21, 27, 33, 39, 45, 51,
50, 49, 48, 47, 46, 82, 118, 154, 190, 226];
let idx = (f * (mapping.len() as f32)) as i32;
if idx < 0 {
mapping[0]
} else if idx >= mapping.len() as i32 {
mapping[mapping.len() - 1]
} else {
mapping[idx as usize]
}
}
fn no
|
pec: &[Complex<f32>], max_db: f32) -> Vec<f32> {
// FFT shift
let (first_half, last_half) = spec.split_at((spec.len() + 1) / 2);
let shifted_spec = last_half.iter().chain(first_half.iter());
// normalize and take the log
shifted_spec.map(Complex::norm)
.map(Float::log10)
.map(|x| 10.0 * x)
.map(|x| x / max_db)
.collect()
}
// indexing is from the top of the cell
fn pixel_nums_to_braille(p1: Option<u8>, p2: Option<u8>) -> char {
let pixel_map = [[0x01, 0x08],
[0x02, 0x10],
[0x04, 0x20],
[0x40, 0x80]];
let mut c = 0;
if let Some(p) = p1 {
for i in p..4 {
c |= pixel_map[i as usize][0];
}
}
if let Some(p) = p2 {
for i in p..4 {
c |= pixel_map[i as usize][1];
}
}
char::from_u32((0x2800 + c) as u32).unwrap()
}
fn char_to_cell(c: char) -> Cell {
let mut cell = Cell::with_char(c);
cell.set_attrs(Attr::Bold);
cell
}
fn draw_pixel_pair<T>(canvas: &mut T, col_idx: usize, p1: usize, p2: usize)
where T: CellAccessor + HasSize
{
let (_, rows) = canvas.size();
let max_pixel_height = 4 * rows;
// clamp heights
let p1 = if p1 >= max_pixel_height { max_pixel_height - 1} else { p1 };
let p2 = if p2 >= max_pixel_height { max_pixel_height - 1} else { p2 };
// Reverse it, since the terminal indexing is from the top
let p1 = max_pixel_height - p1 - 1;
let p2 = max_pixel_height - p2 - 1;
// cell indices
let c1 = p1 / 4;
let c2 = p2 / 4;
// Fill in full height cells.
let full_cell_char = pixel_nums_to_braille(Some(0), Some(0));
for row_idx in max(c1, c2)..rows {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(full_cell_char);
}
let left_fill_cell_char = pixel_nums_to_braille(Some(0), None);
for row_idx in min(c1, c2)..c2 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(left_fill_cell_char);
}
let right_fill_cell_char = pixel_nums_to_braille(None, Some(0));
for row_idx in min(c1, c2)..c1 {
*canvas.get_mut(col_idx, row_idx).unwrap() = char_to_cell(right_fill_cell_char);
}
// Now fill in partial height cells.
if c1 == c2 {
// top pixels are in the same cell
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some((p2 % 4) as u8)));
} else if c1 > c2 {
// right pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), Some(0)));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(None, Some((p2 % 4) as u8)));
} else {
// left pixel is in a higher cell.
*canvas.get_mut(col_idx, c1).unwrap() = char_to_cell(
pixel_nums_to_braille(Some((p1 % 4) as u8), None));
*canvas.get_mut(col_idx, c2).unwrap() = char_to_cell(
pixel_nums_to_braille(Some(0), Some((p2 % 4) as u8)));
}
}
fn draw_spectrum<T: CellAccessor + HasSize>(canvas: &mut T, spec: &[f32]) {
canvas.clear(Cell::default());
let (num_cols, num_rows) = canvas.size();
let pixel_height = num_rows * 4;
for (col_idx, chunk) in (0..num_cols).zip(spec.chunks(2)) {
// height in float between 0 and 1.
let h1 = chunk[0];
let h2 = chunk[1];
// The "pixel" height of each point.
let p1 = (h1 * pixel_height as f32).floor().max(0.0) as usize;
let p2 = (h2 * pixel_height as f32).floor().max(0.0) as usize;
draw_pixel_pair(canvas, col_idx, p1, p2);
}
}
#[cfg(test)]
mod tests {
use super::{pixel_nums_to_braille, draw_pixel_pair};
use rustty::Terminal;
#[test]
fn test_pixel_nums() {
assert_eq!(pixel_nums_to_braille(Some(0), Some(0)), '⣿');
assert_eq!(pixel_nums_to_braille(Some(1), Some(2)), '⣦');
assert_eq!(pixel_nums_to_braille(None, Some(3)), '⢀');
assert_eq!(pixel_nums_to_braille(Some(2), None), '⡄');
assert_eq!(pixel_nums_to_braille(None, None), '⠀');
}
#[test]
fn test_draw_pixel_pair() {
let mut term = Terminal::new().unwrap();
// Test drawing with the same top cell
draw_pixel_pair(&mut term, 0, 4, 6);
assert_eq!(term[(0, term.rows() - 3)].ch(),'');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣰');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
// Test drawing with the top pixel in each column being in
// different cells
draw_pixel_pair(&mut term, 0, 4, 8);
assert_eq!(term[(0, term.rows() - 4)].ch(),'');
assert_eq!(term[(0, term.rows() - 3)].ch(), '⢀');
assert_eq!(term[(0, term.rows() - 2)].ch(), '⣸');
assert_eq!(term[(0, term.rows() - 1)].ch(), '⣿');
term.clear().unwrap();
draw_pixel_pair(&mut term, 1, 13, 2);
assert_eq!(term[(1, term.rows() - 5)].ch(),'');
assert_eq!(term[(1, term.rows() - 4)].ch(), '⡄');
assert_eq!(term[(1, term.rows() - 3)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 2)].ch(), '⡇');
assert_eq!(term[(1, term.rows() - 1)].ch(), '⣷');
term.clear().unwrap();
}
}
|
rmalize_spectrum(s
|
identifier_name
|
mod.rs
|
//! Module implementing the handling of gists.
//!
//! Gists are represented as the Gist structure, with the auxiliary URI
//! that helps refering to them as command line arguments to the program.
mod info;
mod uri;
use std::borrow::Cow;
use std::path::PathBuf;
use super::{BIN_DIR, GISTS_DIR};
pub use self::info::{Datum, Info, InfoBuilder};
pub use self::uri::{Uri, UriError};
/// Structure representing a single gist.
#[derive(Debug, Clone)]
pub struct Gist {
/// URI to the gist.
pub uri: Uri,
/// Alternative, host-specific ID of the gist.
pub id: Option<String>,
/// Optional gist info, which may be available.
///
/// Note that this can be None or partial.
/// No piece of gist info is guaranteed to be available.
pub info: Option<Info>,
}
impl Gist {
#[inline]
pub fn new<I: ToString>(uri: Uri, id: I) -> Gist {
Gist{uri: uri, id: Some(id.to_string()), info: None}
}
#[inline]
pub fn from_uri(uri: Uri) -> Self {
Gist{uri: uri, id: None, info: None}
}
/// Create the copy of Gist that has given ID attached.
#[inline]
pub fn with_id<S: ToString>(self, id: S) -> Self {
Gist{id: Some(id.to_string()),..self}
}
/// Create a copy of Gist with given gist Info attached.
/// Note that two Gists are considered identical if they only differ by Info.
#[inline]
pub fn with_info(self, info: Info) -> Self {
Gist{info: Some(info),..self}
}
}
impl Gist {
/// Returns the path to this gist in the local gists directory
/// (regardless whether it was downloaded or not).
pub fn path(&self) -> PathBuf {
// If the gist is identified by a host-specific ID, it should be a part of the path
// (because uri.name is most likely not unique in that case).
// Otherwise, the gist's URI will form its path.
let path_fragment = match self.id {
Some(ref id) => PathBuf::new().join(&self.uri.host_id).join(id),
_ => self.uri.clone().into(),
};
GISTS_DIR.join(path_fragment)
}
/// Returns the path to the gist's binary
/// (regardless whether it was downloaded or not).
#[inline]
pub fn binary_path(&self) -> PathBuf {
let uri_path: PathBuf = self.uri.clone().into();
BIN_DIR.join(uri_path)
}
/// Whether the gist has been downloaded previously.
#[inline]
pub fn is_local(&self) -> bool {
// Path::exists() will traverse symlinks, so this also ensures
// that the target "binary" file of the gist exists.
self.binary_path().exists()
}
/// Retrieve a specific piece of gist Info, if available.
#[inline]
pub fn info(&self, datum: Datum) -> Option<info::Value> {
let info = try_opt!(self.info.as_ref());
if info.has(datum) {
Some(info.get(datum).into_owned())
} else {
None
}
}
/// Get an InfoBuilder based on this gist's Info (if any).
#[inline]
pub fn info_builder(&self) -> InfoBuilder {
self.info.clone().map(|i| i.to_builder()).unwrap_or_else(InfoBuilder::new)
}
/// Retrieve the main language this gist has been written in, if known.
pub fn main_language(&self) -> Option<&str> {
let info = try_opt!(self.info.as_ref());
// To be able to return Option<&str> rather than Option<String>,
// we need to get the underlying reference from Cow returned by Info::get.
let csv_langs = match info.get(Datum::Language) {
Cow::Borrowed(lang) => lang,
_ => return None, // Language field is default/unknown.
};
csv_langs.split(",").map(|l| l.trim()).next()
}
}
impl PartialEq<Gist> for Gist {
fn eq(&self, other: &Gist) -> bool {
if self.uri!= other.uri {
|
}
if self.id.is_some() && self.id!= other.id {
return false;
}
true
}
}
#[cfg(test)]
mod tests {
use gist::Uri;
use hosts;
use super::Gist;
const HOST_ID: &'static str = hosts::DEFAULT_HOST_ID;
const OWNER: &'static str = "JohnDoe";
const NAME: &'static str = "foo";
const ID: &'static str = "1234abcd5678efgh";
#[test]
fn path_without_id() {
let gist = Gist::from_uri(Uri::new(HOST_ID, OWNER, NAME).unwrap());
let path = gist.path().to_str().unwrap().to_owned();
assert!(path.contains(HOST_ID), "Gist path should contain host ID");
assert!(path.contains(OWNER), "Gist path should contain owner");
assert!(path.contains(NAME), "Gist path should contain gist name");
}
#[test]
fn path_with_id() {
let gist = Gist::from_uri(Uri::from_name(HOST_ID, NAME).unwrap())
.with_id(ID);
let path = gist.path().to_str().unwrap().to_owned();
assert!(path.contains(HOST_ID), "Gist path should contain host ID");
assert!(path.contains(ID), "Gist path should contain gist ID");
assert!(!path.contains(NAME), "Gist path shouldn't contain gist name");
}
#[test]
fn binary_path() {
let gist = Gist::from_uri(Uri::new(HOST_ID, OWNER, NAME).unwrap());
let path = gist.binary_path().to_str().unwrap().to_owned();
assert!(path.contains(HOST_ID), "Gist binary path should contain host ID");
assert!(path.contains(OWNER), "Gist binary path should contain owner");
assert!(path.contains(NAME), "Gist binary path should contain gist name");
}
}
|
return false;
|
random_line_split
|
mod.rs
|
//! Module implementing the handling of gists.
//!
//! Gists are represented as the Gist structure, with the auxiliary URI
//! that helps refering to them as command line arguments to the program.
mod info;
mod uri;
use std::borrow::Cow;
use std::path::PathBuf;
use super::{BIN_DIR, GISTS_DIR};
pub use self::info::{Datum, Info, InfoBuilder};
pub use self::uri::{Uri, UriError};
/// Structure representing a single gist.
#[derive(Debug, Clone)]
pub struct Gist {
/// URI to the gist.
pub uri: Uri,
/// Alternative, host-specific ID of the gist.
pub id: Option<String>,
/// Optional gist info, which may be available.
///
/// Note that this can be None or partial.
/// No piece of gist info is guaranteed to be available.
pub info: Option<Info>,
}
impl Gist {
#[inline]
pub fn new<I: ToString>(uri: Uri, id: I) -> Gist {
Gist{uri: uri, id: Some(id.to_string()), info: None}
}
#[inline]
pub fn from_uri(uri: Uri) -> Self {
Gist{uri: uri, id: None, info: None}
}
/// Create the copy of Gist that has given ID attached.
#[inline]
pub fn
|
<S: ToString>(self, id: S) -> Self {
Gist{id: Some(id.to_string()),..self}
}
/// Create a copy of Gist with given gist Info attached.
/// Note that two Gists are considered identical if they only differ by Info.
#[inline]
pub fn with_info(self, info: Info) -> Self {
Gist{info: Some(info),..self}
}
}
impl Gist {
/// Returns the path to this gist in the local gists directory
/// (regardless whether it was downloaded or not).
pub fn path(&self) -> PathBuf {
// If the gist is identified by a host-specific ID, it should be a part of the path
// (because uri.name is most likely not unique in that case).
// Otherwise, the gist's URI will form its path.
let path_fragment = match self.id {
Some(ref id) => PathBuf::new().join(&self.uri.host_id).join(id),
_ => self.uri.clone().into(),
};
GISTS_DIR.join(path_fragment)
}
/// Returns the path to the gist's binary
/// (regardless whether it was downloaded or not).
#[inline]
pub fn binary_path(&self) -> PathBuf {
let uri_path: PathBuf = self.uri.clone().into();
BIN_DIR.join(uri_path)
}
/// Whether the gist has been downloaded previously.
#[inline]
pub fn is_local(&self) -> bool {
// Path::exists() will traverse symlinks, so this also ensures
// that the target "binary" file of the gist exists.
self.binary_path().exists()
}
/// Retrieve a specific piece of gist Info, if available.
#[inline]
pub fn info(&self, datum: Datum) -> Option<info::Value> {
let info = try_opt!(self.info.as_ref());
if info.has(datum) {
Some(info.get(datum).into_owned())
} else {
None
}
}
/// Get an InfoBuilder based on this gist's Info (if any).
#[inline]
pub fn info_builder(&self) -> InfoBuilder {
self.info.clone().map(|i| i.to_builder()).unwrap_or_else(InfoBuilder::new)
}
/// Retrieve the main language this gist has been written in, if known.
pub fn main_language(&self) -> Option<&str> {
let info = try_opt!(self.info.as_ref());
// To be able to return Option<&str> rather than Option<String>,
// we need to get the underlying reference from Cow returned by Info::get.
let csv_langs = match info.get(Datum::Language) {
Cow::Borrowed(lang) => lang,
_ => return None, // Language field is default/unknown.
};
csv_langs.split(",").map(|l| l.trim()).next()
}
}
impl PartialEq<Gist> for Gist {
fn eq(&self, other: &Gist) -> bool {
if self.uri!= other.uri {
return false;
}
if self.id.is_some() && self.id!= other.id {
return false;
}
true
}
}
#[cfg(test)]
mod tests {
use gist::Uri;
use hosts;
use super::Gist;
const HOST_ID: &'static str = hosts::DEFAULT_HOST_ID;
const OWNER: &'static str = "JohnDoe";
const NAME: &'static str = "foo";
const ID: &'static str = "1234abcd5678efgh";
#[test]
fn path_without_id() {
let gist = Gist::from_uri(Uri::new(HOST_ID, OWNER, NAME).unwrap());
let path = gist.path().to_str().unwrap().to_owned();
assert!(path.contains(HOST_ID), "Gist path should contain host ID");
assert!(path.contains(OWNER), "Gist path should contain owner");
assert!(path.contains(NAME), "Gist path should contain gist name");
}
#[test]
fn path_with_id() {
let gist = Gist::from_uri(Uri::from_name(HOST_ID, NAME).unwrap())
.with_id(ID);
let path = gist.path().to_str().unwrap().to_owned();
assert!(path.contains(HOST_ID), "Gist path should contain host ID");
assert!(path.contains(ID), "Gist path should contain gist ID");
assert!(!path.contains(NAME), "Gist path shouldn't contain gist name");
}
#[test]
fn binary_path() {
let gist = Gist::from_uri(Uri::new(HOST_ID, OWNER, NAME).unwrap());
let path = gist.binary_path().to_str().unwrap().to_owned();
assert!(path.contains(HOST_ID), "Gist binary path should contain host ID");
assert!(path.contains(OWNER), "Gist binary path should contain owner");
assert!(path.contains(NAME), "Gist binary path should contain gist name");
}
}
|
with_id
|
identifier_name
|
restyle_hints.rs
|
://mozilla.org/MPL/2.0/. */
//! Restyle hints: an optimization to avoid unnecessarily matching selectors.
#![deny(missing_docs)]
use Atom;
use dom::TElement;
use element_state::*;
#[cfg(feature = "gecko")]
use gecko_bindings::structs::nsRestyleHint;
#[cfg(feature = "servo")]
use heapsize::HeapSizeOf;
use selector_parser::{AttrValue, NonTSPseudoClass, Snapshot, SelectorImpl};
use selectors::{Element, MatchAttr};
use selectors::matching::{ElementSelectorFlags, StyleRelations};
use selectors::matching::matches_complex_selector;
use selectors::parser::{AttrSelector, Combinator, ComplexSelector, SimpleSelector};
use std::clone::Clone;
use std::sync::Arc;
bitflags! {
/// When the ElementState of an element (like IN_HOVER_STATE) changes,
/// certain pseudo-classes (like :hover) may require us to restyle that
/// element, its siblings, and/or its descendants. Similarly, when various
/// attributes of an element change, we may also need to restyle things with
/// id, class, and attribute selectors. Doing this conservatively is
/// expensive, and so we use RestyleHints to short-circuit work we know is
/// unnecessary.
pub flags RestyleHint: u32 {
/// Rerun selector matching on the element.
const RESTYLE_SELF = 0x01,
/// Rerun selector matching on all of the element's descendants.
///
/// NB: In Gecko, we have RESTYLE_SUBTREE which is inclusive of self,
/// but heycam isn't aware of a good reason for that.
const RESTYLE_DESCENDANTS = 0x02,
/// Rerun selector matching on all later siblings of the element and all
/// of their descendants.
const RESTYLE_LATER_SIBLINGS = 0x08,
/// Don't re-run selector-matching on the element, only the style
/// attribute has changed, and this change didn't have any other
/// dependencies.
const RESTYLE_STYLE_ATTRIBUTE = 0x10,
}
}
impl RestyleHint {
/// The subset hints that affect the styling of a single element during the
/// traversal.
pub fn for_self() -> Self {
RESTYLE_SELF | RESTYLE_STYLE_ATTRIBUTE
}
}
#[cfg(feature = "gecko")]
impl From<nsRestyleHint> for RestyleHint {
fn from(raw: nsRestyleHint) -> Self {
use std::mem;
let raw_bits: u32 = unsafe { mem::transmute(raw) };
// FIXME(bholley): Finish aligning the binary representations here and
// then.expect() the result of the checked version.
if Self::from_bits(raw_bits).is_none() {
error!("stylo: dropping unsupported restyle hint bits");
}
Self::from_bits_truncate(raw_bits)
}
}
#[cfg(feature = "servo")]
impl HeapSizeOf for RestyleHint {
fn heap_size_of_children(&self) -> usize { 0 }
}
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot : Sized + MatchAttr<Impl=SelectorImpl> {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<Atom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom) -> bool;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, F)
where F: FnMut(&Atom);
}
struct ElementWrapper<'a, E>
where E: TElement,
{
element: E,
snapshot: Option<&'a Snapshot>,
}
impl<'a, E> ElementWrapper<'a, E>
where E: TElement,
{
/// Trivially constructs an `ElementWrapper` without a snapshot.
pub fn new(el: E) -> ElementWrapper<'a, E> {
ElementWrapper { element: el, snapshot: None }
}
/// Trivially constructs an `ElementWrapper` with a snapshot.
pub fn new_with_snapshot(el: E, snapshot: &'a Snapshot) -> ElementWrapper<'a, E> {
ElementWrapper { element: el, snapshot: Some(snapshot) }
}
}
impl<'a, E> MatchAttr for ElementWrapper<'a, E>
where E: TElement,
{
type Impl = SelectorImpl;
fn match_attr_has(&self, attr: &AttrSelector<SelectorImpl>) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_has(attr),
_ => self.element.match_attr_has(attr)
}
}
fn match_attr_equals(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_equals(attr, value),
_ => self.element.match_attr_equals(attr, value)
}
}
fn match_attr_equals_ignore_ascii_case(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_equals_ignore_ascii_case(attr, value),
_ => self.element.match_attr_equals_ignore_ascii_case(attr, value)
}
}
fn match_attr_includes(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_includes(attr, value),
_ => self.element.match_attr_includes(attr, value)
}
}
fn match_attr_dash(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_dash(attr, value),
_ => self.element.match_attr_dash(attr, value)
}
}
fn match_attr_prefix(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_prefix(attr, value),
_ => self.element.match_attr_prefix(attr, value)
}
}
fn match_attr_substring(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_substring(attr, value),
_ => self.element.match_attr_substring(attr, value)
}
}
fn match_attr_suffix(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_suffix(attr, value),
_ => self.element.match_attr_suffix(attr, value)
}
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where E: TElement,
{
fn match_non_ts_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
let flag = SelectorImpl::pseudo_class_state_flag(pseudo_class);
if flag == ElementState::empty() {
self.element.match_non_ts_pseudo_class(pseudo_class)
} else {
match self.snapshot.and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.contains(flag),
_ => self.element.match_non_ts_pseudo_class(pseudo_class)
}
}
}
fn parent_element(&self) -> Option<Self> {
self.element.parent_element().map(ElementWrapper::new)
}
fn first_child_element(&self) -> Option<Self> {
self.element.first_child_element().map(ElementWrapper::new)
}
fn last_child_element(&self) -> Option<Self> {
self.element.last_child_element().map(ElementWrapper::new)
}
fn prev_sibling_element(&self) -> Option<Self> {
self.element.prev_sibling_element().map(ElementWrapper::new)
}
fn next_sibling_element(&self) -> Option<Self> {
self.element.next_sibling_element().map(ElementWrapper::new)
}
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
fn get_local_name(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName {
self.element.get_local_name()
}
fn get_namespace(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl {
self.element.get_namespace()
}
fn get_id(&self) -> Option<Atom> {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.id_attr(),
_ => self.element.get_id()
}
}
fn has_class(&self, name: &Atom) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.has_class(name),
_ => self.element.has_class(name)
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn each_class<F>(&self, callback: F)
where F: FnMut(&Atom) {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.each_class(callback),
_ => self.element.each_class(callback)
}
}
}
fn selector_to_state(sel: &SimpleSelector<SelectorImpl>) -> ElementState {
match *sel {
SimpleSelector::NonTSPseudoClass(ref pc) => SelectorImpl::pseudo_class_state_flag(pc),
_ => ElementState::empty(),
}
}
fn is_attr_selector(sel: &SimpleSelector<SelectorImpl>) -> bool {
match *sel {
SimpleSelector::ID(_) |
SimpleSelector::Class(_) |
SimpleSelector::AttrExists(_) |
SimpleSelector::AttrEqual(_, _, _) |
SimpleSelector::AttrIncludes(_, _) |
SimpleSelector::AttrDashMatch(_, _) |
SimpleSelector::AttrPrefixMatch(_, _) |
SimpleSelector::AttrSubstringMatch(_, _) |
SimpleSelector::AttrSuffixMatch(_, _) => true,
_ => false,
}
}
fn combinator_to_restyle_hint(combinator: Option<Combinator>) -> RestyleHint {
match combinator {
None => RESTYLE_SELF,
Some(c) => match c {
Combinator::Child => RESTYLE_DESCENDANTS,
Combinator::Descendant => RESTYLE_DESCENDANTS,
Combinator::NextSibling => RESTYLE_LATER_SIBLINGS,
Combinator::LaterSibling => RESTYLE_LATER_SIBLINGS,
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
struct Sensitivities {
pub states: ElementState,
pub attrs: bool,
}
impl Sensitivities {
fn is_empty(&self) -> bool {
self.states.is_empty() &&!self.attrs
}
fn new() -> Sensitivities {
Sensitivities {
states: ElementState::empty(),
attrs: false,
}
}
}
/// Mapping between (partial) CompoundSelectors (and the combinator to their
/// right) and the states and attributes they depend on.
///
/// In general, for all selectors in all applicable stylesheets of the form:
///
/// |a _ b _ c _ d _ e|
///
/// Where:
/// * |b| and |d| are simple selectors that depend on state (like :hover) or
/// attributes (like [attr...],.foo, or #foo).
/// * |a|, |c|, and |e| are arbitrary simple selectors that do not depend on
/// state or attributes.
///
/// We generate a Dependency for both |a _ b:X _| and |a _ b:X _ c _ d:Y _|,
/// even though those selectors may not appear on their own in any stylesheet.
/// This allows us to quickly scan through the dependency sites of all style
/// rules and determine the maximum effect that a given state or attribute
/// change may have on the style of elements in the document.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
struct Dependency {
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
selector: Arc<ComplexSelector<SelectorImpl>>,
hint: RestyleHint,
sensitivities: Sensitivities,
}
/// A set of dependencies for a given stylist.
///
/// Note that there are measurable perf wins from storing them separately
/// depending on what kind of change they affect, and its also not a big deal to
/// do it, since the dependencies are per-document.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct DependencySet {
/// Dependencies only affected by state.
state_deps: Vec<Dependency>,
/// Dependencies only affected by attributes.
attr_deps: Vec<Dependency>,
/// Dependencies affected by both.
common_deps: Vec<Dependency>,
}
impl DependencySet {
fn add_dependency(&mut self, dep: Dependency) {
let affects_attrs = dep.sensitivities.attrs;
let affects_states =!dep.sensitivities.states.is_empty();
if affects_attrs && affects_states {
self.common_deps.push(dep)
} else if affects_attrs {
self.attr_deps.push(dep)
} else {
self.state_deps.push(dep)
}
}
/// Create an empty `DependencySet`.
pub fn new() -> Self {
DependencySet {
state_deps: vec![],
attr_deps: vec![],
common_deps: vec![],
}
}
/// Return the total number of dependencies that this set contains.
pub fn len(&self) -> usize {
self.common_deps.len() + self.attr_deps.len() + self.state_deps.len()
}
/// Create the needed dependencies that a given selector creates, and add
/// them to the set.
pub fn note_selector(&mut self, selector: &Arc<ComplexSelector<SelectorImpl>>) {
let mut cur = selector;
let mut combinator: Option<Combinator> = None;
loop {
let mut sensitivities = Sensitivities::new();
for s in &cur.compound_selector {
sensitivities.states.insert(selector_to_state(s));
if!sensitivities.attrs {
sensitivities.attrs = is_attr_selector(s);
}
}
if!sensitivities.is_empty() {
self.add_dependency(Dependency {
selector: cur.clone(),
hint: combinator_to_restyle_hint(combinator),
sensitivities: sensitivities,
});
}
cur = match cur.next {
Some((ref sel, comb)) => {
combinator = Some(comb);
sel
}
None => break,
}
}
}
/// Clear this dependency set.
pub fn clear(&mut self) {
self.common_deps.clear();
self.attr_deps.clear();
self.state_deps.clear();
}
/// Compute a restyle hint given an element and a snapshot, per the rules
|
pub fn compute_hint<E>(&self,
el: &E,
snapshot: &Snapshot)
-> RestyleHint
where E: TElement + Clone,
{
let current_state = el.get_state();
let state_changes = snapshot.state()
.map_or_else(ElementState::empty, |old_state| current_state ^ old_state);
let attrs_changed = snapshot.has_attrs();
if state_changes.is_empty() &&!attrs_changed {
return RestyleHint::empty();
}
let mut hint = RestyleHint::empty();
let snapshot_el = ElementWrapper::new_with_snapshot(el.clone(), snapshot);
Self::compute_partial_hint(&self.common_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
if!state_changes.is_empty() {
Self::compute_partial_hint(&self.state_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
}
if attrs_changed {
Self::compute_partial_hint(&self.attr_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
}
debug!("Calculated restyle hint: {:?}. (Element={:?}, State={:?}, Snapshot={:?}, {} Deps)",
hint, el, current_state, snapshot, self.len());
trace!("Deps: {:?}", self);
hint
}
fn compute_partial_hint<E>(deps: &[Dependency],
element: &E,
snapshot: &ElementWrapper<E>,
state_changes: &ElementState,
attrs_changed: bool,
hint: &mut RestyleHint)
where E: TElement,
{
if hint.is_all() {
return;
}
for dep in deps {
debug_assert!((!state_changes.is_empty() &&!dep.sensitivities.states.is_empty()) ||
(attrs_changed && dep.sensitivities.attrs),
"Testing a known ineffective dependency?");
if (attrs_changed || state_changes.intersects(dep.sensitivities.states)) &&!hint.intersects(dep.hint) {
// We can ignore the selector flags, since they would have already been set during
// original matching for any element that might change its matching behavior here.
let matched_then =
matches_complex_selector(&dep.selector, snapshot, None,
&mut StyleRelations::empty(),
&mut ElementSelectorFlags::empty());
let matches_now =
matches_complex_selector(&dep.selector, element, None,
&mut StyleRelations::empty(),
&mut ElementSelectorFlags::empty());
if matched_then!= matches_now {
hint.insert(dep.hint);
|
/// explained in the rest of the documentation.
|
random_line_split
|
restyle_hints.rs
|
mozilla.org/MPL/2.0/. */
//! Restyle hints: an optimization to avoid unnecessarily matching selectors.
#![deny(missing_docs)]
use Atom;
use dom::TElement;
use element_state::*;
#[cfg(feature = "gecko")]
use gecko_bindings::structs::nsRestyleHint;
#[cfg(feature = "servo")]
use heapsize::HeapSizeOf;
use selector_parser::{AttrValue, NonTSPseudoClass, Snapshot, SelectorImpl};
use selectors::{Element, MatchAttr};
use selectors::matching::{ElementSelectorFlags, StyleRelations};
use selectors::matching::matches_complex_selector;
use selectors::parser::{AttrSelector, Combinator, ComplexSelector, SimpleSelector};
use std::clone::Clone;
use std::sync::Arc;
bitflags! {
/// When the ElementState of an element (like IN_HOVER_STATE) changes,
/// certain pseudo-classes (like :hover) may require us to restyle that
/// element, its siblings, and/or its descendants. Similarly, when various
/// attributes of an element change, we may also need to restyle things with
/// id, class, and attribute selectors. Doing this conservatively is
/// expensive, and so we use RestyleHints to short-circuit work we know is
/// unnecessary.
pub flags RestyleHint: u32 {
/// Rerun selector matching on the element.
const RESTYLE_SELF = 0x01,
/// Rerun selector matching on all of the element's descendants.
///
/// NB: In Gecko, we have RESTYLE_SUBTREE which is inclusive of self,
/// but heycam isn't aware of a good reason for that.
const RESTYLE_DESCENDANTS = 0x02,
/// Rerun selector matching on all later siblings of the element and all
/// of their descendants.
const RESTYLE_LATER_SIBLINGS = 0x08,
/// Don't re-run selector-matching on the element, only the style
/// attribute has changed, and this change didn't have any other
/// dependencies.
const RESTYLE_STYLE_ATTRIBUTE = 0x10,
}
}
impl RestyleHint {
/// The subset hints that affect the styling of a single element during the
/// traversal.
pub fn for_self() -> Self {
RESTYLE_SELF | RESTYLE_STYLE_ATTRIBUTE
}
}
#[cfg(feature = "gecko")]
impl From<nsRestyleHint> for RestyleHint {
fn from(raw: nsRestyleHint) -> Self {
use std::mem;
let raw_bits: u32 = unsafe { mem::transmute(raw) };
// FIXME(bholley): Finish aligning the binary representations here and
// then.expect() the result of the checked version.
if Self::from_bits(raw_bits).is_none() {
error!("stylo: dropping unsupported restyle hint bits");
}
Self::from_bits_truncate(raw_bits)
}
}
#[cfg(feature = "servo")]
impl HeapSizeOf for RestyleHint {
fn heap_size_of_children(&self) -> usize { 0 }
}
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot : Sized + MatchAttr<Impl=SelectorImpl> {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<Atom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom) -> bool;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, F)
where F: FnMut(&Atom);
}
struct ElementWrapper<'a, E>
where E: TElement,
{
element: E,
snapshot: Option<&'a Snapshot>,
}
impl<'a, E> ElementWrapper<'a, E>
where E: TElement,
{
/// Trivially constructs an `ElementWrapper` without a snapshot.
pub fn new(el: E) -> ElementWrapper<'a, E> {
ElementWrapper { element: el, snapshot: None }
}
/// Trivially constructs an `ElementWrapper` with a snapshot.
pub fn new_with_snapshot(el: E, snapshot: &'a Snapshot) -> ElementWrapper<'a, E> {
ElementWrapper { element: el, snapshot: Some(snapshot) }
}
}
impl<'a, E> MatchAttr for ElementWrapper<'a, E>
where E: TElement,
{
type Impl = SelectorImpl;
fn match_attr_has(&self, attr: &AttrSelector<SelectorImpl>) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_has(attr),
_ => self.element.match_attr_has(attr)
}
}
fn match_attr_equals(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_equals(attr, value),
_ => self.element.match_attr_equals(attr, value)
}
}
fn match_attr_equals_ignore_ascii_case(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_equals_ignore_ascii_case(attr, value),
_ => self.element.match_attr_equals_ignore_ascii_case(attr, value)
}
}
fn match_attr_includes(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_includes(attr, value),
_ => self.element.match_attr_includes(attr, value)
}
}
fn match_attr_dash(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_dash(attr, value),
_ => self.element.match_attr_dash(attr, value)
}
}
fn match_attr_prefix(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_prefix(attr, value),
_ => self.element.match_attr_prefix(attr, value)
}
}
fn match_attr_substring(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_substring(attr, value),
_ => self.element.match_attr_substring(attr, value)
}
}
fn match_attr_suffix(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_suffix(attr, value),
_ => self.element.match_attr_suffix(attr, value)
}
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where E: TElement,
{
fn match_non_ts_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
let flag = SelectorImpl::pseudo_class_state_flag(pseudo_class);
if flag == ElementState::empty() {
self.element.match_non_ts_pseudo_class(pseudo_class)
} else {
match self.snapshot.and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.contains(flag),
_ => self.element.match_non_ts_pseudo_class(pseudo_class)
}
}
}
fn parent_element(&self) -> Option<Self> {
self.element.parent_element().map(ElementWrapper::new)
}
fn
|
(&self) -> Option<Self> {
self.element.first_child_element().map(ElementWrapper::new)
}
fn last_child_element(&self) -> Option<Self> {
self.element.last_child_element().map(ElementWrapper::new)
}
fn prev_sibling_element(&self) -> Option<Self> {
self.element.prev_sibling_element().map(ElementWrapper::new)
}
fn next_sibling_element(&self) -> Option<Self> {
self.element.next_sibling_element().map(ElementWrapper::new)
}
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
fn get_local_name(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName {
self.element.get_local_name()
}
fn get_namespace(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl {
self.element.get_namespace()
}
fn get_id(&self) -> Option<Atom> {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.id_attr(),
_ => self.element.get_id()
}
}
fn has_class(&self, name: &Atom) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.has_class(name),
_ => self.element.has_class(name)
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn each_class<F>(&self, callback: F)
where F: FnMut(&Atom) {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.each_class(callback),
_ => self.element.each_class(callback)
}
}
}
fn selector_to_state(sel: &SimpleSelector<SelectorImpl>) -> ElementState {
match *sel {
SimpleSelector::NonTSPseudoClass(ref pc) => SelectorImpl::pseudo_class_state_flag(pc),
_ => ElementState::empty(),
}
}
fn is_attr_selector(sel: &SimpleSelector<SelectorImpl>) -> bool {
match *sel {
SimpleSelector::ID(_) |
SimpleSelector::Class(_) |
SimpleSelector::AttrExists(_) |
SimpleSelector::AttrEqual(_, _, _) |
SimpleSelector::AttrIncludes(_, _) |
SimpleSelector::AttrDashMatch(_, _) |
SimpleSelector::AttrPrefixMatch(_, _) |
SimpleSelector::AttrSubstringMatch(_, _) |
SimpleSelector::AttrSuffixMatch(_, _) => true,
_ => false,
}
}
fn combinator_to_restyle_hint(combinator: Option<Combinator>) -> RestyleHint {
match combinator {
None => RESTYLE_SELF,
Some(c) => match c {
Combinator::Child => RESTYLE_DESCENDANTS,
Combinator::Descendant => RESTYLE_DESCENDANTS,
Combinator::NextSibling => RESTYLE_LATER_SIBLINGS,
Combinator::LaterSibling => RESTYLE_LATER_SIBLINGS,
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
struct Sensitivities {
pub states: ElementState,
pub attrs: bool,
}
impl Sensitivities {
fn is_empty(&self) -> bool {
self.states.is_empty() &&!self.attrs
}
fn new() -> Sensitivities {
Sensitivities {
states: ElementState::empty(),
attrs: false,
}
}
}
/// Mapping between (partial) CompoundSelectors (and the combinator to their
/// right) and the states and attributes they depend on.
///
/// In general, for all selectors in all applicable stylesheets of the form:
///
/// |a _ b _ c _ d _ e|
///
/// Where:
/// * |b| and |d| are simple selectors that depend on state (like :hover) or
/// attributes (like [attr...],.foo, or #foo).
/// * |a|, |c|, and |e| are arbitrary simple selectors that do not depend on
/// state or attributes.
///
/// We generate a Dependency for both |a _ b:X _| and |a _ b:X _ c _ d:Y _|,
/// even though those selectors may not appear on their own in any stylesheet.
/// This allows us to quickly scan through the dependency sites of all style
/// rules and determine the maximum effect that a given state or attribute
/// change may have on the style of elements in the document.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
struct Dependency {
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
selector: Arc<ComplexSelector<SelectorImpl>>,
hint: RestyleHint,
sensitivities: Sensitivities,
}
/// A set of dependencies for a given stylist.
///
/// Note that there are measurable perf wins from storing them separately
/// depending on what kind of change they affect, and its also not a big deal to
/// do it, since the dependencies are per-document.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct DependencySet {
/// Dependencies only affected by state.
state_deps: Vec<Dependency>,
/// Dependencies only affected by attributes.
attr_deps: Vec<Dependency>,
/// Dependencies affected by both.
common_deps: Vec<Dependency>,
}
impl DependencySet {
fn add_dependency(&mut self, dep: Dependency) {
let affects_attrs = dep.sensitivities.attrs;
let affects_states =!dep.sensitivities.states.is_empty();
if affects_attrs && affects_states {
self.common_deps.push(dep)
} else if affects_attrs {
self.attr_deps.push(dep)
} else {
self.state_deps.push(dep)
}
}
/// Create an empty `DependencySet`.
pub fn new() -> Self {
DependencySet {
state_deps: vec![],
attr_deps: vec![],
common_deps: vec![],
}
}
/// Return the total number of dependencies that this set contains.
pub fn len(&self) -> usize {
self.common_deps.len() + self.attr_deps.len() + self.state_deps.len()
}
/// Create the needed dependencies that a given selector creates, and add
/// them to the set.
pub fn note_selector(&mut self, selector: &Arc<ComplexSelector<SelectorImpl>>) {
let mut cur = selector;
let mut combinator: Option<Combinator> = None;
loop {
let mut sensitivities = Sensitivities::new();
for s in &cur.compound_selector {
sensitivities.states.insert(selector_to_state(s));
if!sensitivities.attrs {
sensitivities.attrs = is_attr_selector(s);
}
}
if!sensitivities.is_empty() {
self.add_dependency(Dependency {
selector: cur.clone(),
hint: combinator_to_restyle_hint(combinator),
sensitivities: sensitivities,
});
}
cur = match cur.next {
Some((ref sel, comb)) => {
combinator = Some(comb);
sel
}
None => break,
}
}
}
/// Clear this dependency set.
pub fn clear(&mut self) {
self.common_deps.clear();
self.attr_deps.clear();
self.state_deps.clear();
}
/// Compute a restyle hint given an element and a snapshot, per the rules
/// explained in the rest of the documentation.
pub fn compute_hint<E>(&self,
el: &E,
snapshot: &Snapshot)
-> RestyleHint
where E: TElement + Clone,
{
let current_state = el.get_state();
let state_changes = snapshot.state()
.map_or_else(ElementState::empty, |old_state| current_state ^ old_state);
let attrs_changed = snapshot.has_attrs();
if state_changes.is_empty() &&!attrs_changed {
return RestyleHint::empty();
}
let mut hint = RestyleHint::empty();
let snapshot_el = ElementWrapper::new_with_snapshot(el.clone(), snapshot);
Self::compute_partial_hint(&self.common_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
if!state_changes.is_empty() {
Self::compute_partial_hint(&self.state_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
}
if attrs_changed {
Self::compute_partial_hint(&self.attr_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
}
debug!("Calculated restyle hint: {:?}. (Element={:?}, State={:?}, Snapshot={:?}, {} Deps)",
hint, el, current_state, snapshot, self.len());
trace!("Deps: {:?}", self);
hint
}
fn compute_partial_hint<E>(deps: &[Dependency],
element: &E,
snapshot: &ElementWrapper<E>,
state_changes: &ElementState,
attrs_changed: bool,
hint: &mut RestyleHint)
where E: TElement,
{
if hint.is_all() {
return;
}
for dep in deps {
debug_assert!((!state_changes.is_empty() &&!dep.sensitivities.states.is_empty()) ||
(attrs_changed && dep.sensitivities.attrs),
"Testing a known ineffective dependency?");
if (attrs_changed || state_changes.intersects(dep.sensitivities.states)) &&!hint.intersects(dep.hint) {
// We can ignore the selector flags, since they would have already been set during
// original matching for any element that might change its matching behavior here.
let matched_then =
matches_complex_selector(&dep.selector, snapshot, None,
&mut StyleRelations::empty(),
&mut ElementSelectorFlags::empty());
let matches_now =
matches_complex_selector(&dep.selector, element, None,
&mut StyleRelations::empty(),
&mut ElementSelectorFlags::empty());
if matched_then!= matches_now {
hint.insert(dep.hint);
|
first_child_element
|
identifier_name
|
restyle_hints.rs
|
mozilla.org/MPL/2.0/. */
//! Restyle hints: an optimization to avoid unnecessarily matching selectors.
#![deny(missing_docs)]
use Atom;
use dom::TElement;
use element_state::*;
#[cfg(feature = "gecko")]
use gecko_bindings::structs::nsRestyleHint;
#[cfg(feature = "servo")]
use heapsize::HeapSizeOf;
use selector_parser::{AttrValue, NonTSPseudoClass, Snapshot, SelectorImpl};
use selectors::{Element, MatchAttr};
use selectors::matching::{ElementSelectorFlags, StyleRelations};
use selectors::matching::matches_complex_selector;
use selectors::parser::{AttrSelector, Combinator, ComplexSelector, SimpleSelector};
use std::clone::Clone;
use std::sync::Arc;
bitflags! {
/// When the ElementState of an element (like IN_HOVER_STATE) changes,
/// certain pseudo-classes (like :hover) may require us to restyle that
/// element, its siblings, and/or its descendants. Similarly, when various
/// attributes of an element change, we may also need to restyle things with
/// id, class, and attribute selectors. Doing this conservatively is
/// expensive, and so we use RestyleHints to short-circuit work we know is
/// unnecessary.
pub flags RestyleHint: u32 {
/// Rerun selector matching on the element.
const RESTYLE_SELF = 0x01,
/// Rerun selector matching on all of the element's descendants.
///
/// NB: In Gecko, we have RESTYLE_SUBTREE which is inclusive of self,
/// but heycam isn't aware of a good reason for that.
const RESTYLE_DESCENDANTS = 0x02,
/// Rerun selector matching on all later siblings of the element and all
/// of their descendants.
const RESTYLE_LATER_SIBLINGS = 0x08,
/// Don't re-run selector-matching on the element, only the style
/// attribute has changed, and this change didn't have any other
/// dependencies.
const RESTYLE_STYLE_ATTRIBUTE = 0x10,
}
}
impl RestyleHint {
/// The subset hints that affect the styling of a single element during the
/// traversal.
pub fn for_self() -> Self {
RESTYLE_SELF | RESTYLE_STYLE_ATTRIBUTE
}
}
#[cfg(feature = "gecko")]
impl From<nsRestyleHint> for RestyleHint {
fn from(raw: nsRestyleHint) -> Self
|
}
#[cfg(feature = "servo")]
impl HeapSizeOf for RestyleHint {
fn heap_size_of_children(&self) -> usize { 0 }
}
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot : Sized + MatchAttr<Impl=SelectorImpl> {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<Atom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom) -> bool;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, F)
where F: FnMut(&Atom);
}
struct ElementWrapper<'a, E>
where E: TElement,
{
element: E,
snapshot: Option<&'a Snapshot>,
}
impl<'a, E> ElementWrapper<'a, E>
where E: TElement,
{
/// Trivially constructs an `ElementWrapper` without a snapshot.
pub fn new(el: E) -> ElementWrapper<'a, E> {
ElementWrapper { element: el, snapshot: None }
}
/// Trivially constructs an `ElementWrapper` with a snapshot.
pub fn new_with_snapshot(el: E, snapshot: &'a Snapshot) -> ElementWrapper<'a, E> {
ElementWrapper { element: el, snapshot: Some(snapshot) }
}
}
impl<'a, E> MatchAttr for ElementWrapper<'a, E>
where E: TElement,
{
type Impl = SelectorImpl;
fn match_attr_has(&self, attr: &AttrSelector<SelectorImpl>) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_has(attr),
_ => self.element.match_attr_has(attr)
}
}
fn match_attr_equals(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_equals(attr, value),
_ => self.element.match_attr_equals(attr, value)
}
}
fn match_attr_equals_ignore_ascii_case(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_equals_ignore_ascii_case(attr, value),
_ => self.element.match_attr_equals_ignore_ascii_case(attr, value)
}
}
fn match_attr_includes(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_includes(attr, value),
_ => self.element.match_attr_includes(attr, value)
}
}
fn match_attr_dash(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_dash(attr, value),
_ => self.element.match_attr_dash(attr, value)
}
}
fn match_attr_prefix(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_prefix(attr, value),
_ => self.element.match_attr_prefix(attr, value)
}
}
fn match_attr_substring(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_substring(attr, value),
_ => self.element.match_attr_substring(attr, value)
}
}
fn match_attr_suffix(&self,
attr: &AttrSelector<SelectorImpl>,
value: &AttrValue) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.match_attr_suffix(attr, value),
_ => self.element.match_attr_suffix(attr, value)
}
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where E: TElement,
{
fn match_non_ts_pseudo_class(&self, pseudo_class: &NonTSPseudoClass) -> bool {
let flag = SelectorImpl::pseudo_class_state_flag(pseudo_class);
if flag == ElementState::empty() {
self.element.match_non_ts_pseudo_class(pseudo_class)
} else {
match self.snapshot.and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.contains(flag),
_ => self.element.match_non_ts_pseudo_class(pseudo_class)
}
}
}
fn parent_element(&self) -> Option<Self> {
self.element.parent_element().map(ElementWrapper::new)
}
fn first_child_element(&self) -> Option<Self> {
self.element.first_child_element().map(ElementWrapper::new)
}
fn last_child_element(&self) -> Option<Self> {
self.element.last_child_element().map(ElementWrapper::new)
}
fn prev_sibling_element(&self) -> Option<Self> {
self.element.prev_sibling_element().map(ElementWrapper::new)
}
fn next_sibling_element(&self) -> Option<Self> {
self.element.next_sibling_element().map(ElementWrapper::new)
}
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
fn get_local_name(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName {
self.element.get_local_name()
}
fn get_namespace(&self) -> &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl {
self.element.get_namespace()
}
fn get_id(&self) -> Option<Atom> {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.id_attr(),
_ => self.element.get_id()
}
}
fn has_class(&self, name: &Atom) -> bool {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.has_class(name),
_ => self.element.has_class(name)
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn each_class<F>(&self, callback: F)
where F: FnMut(&Atom) {
match self.snapshot {
Some(snapshot) if snapshot.has_attrs()
=> snapshot.each_class(callback),
_ => self.element.each_class(callback)
}
}
}
fn selector_to_state(sel: &SimpleSelector<SelectorImpl>) -> ElementState {
match *sel {
SimpleSelector::NonTSPseudoClass(ref pc) => SelectorImpl::pseudo_class_state_flag(pc),
_ => ElementState::empty(),
}
}
fn is_attr_selector(sel: &SimpleSelector<SelectorImpl>) -> bool {
match *sel {
SimpleSelector::ID(_) |
SimpleSelector::Class(_) |
SimpleSelector::AttrExists(_) |
SimpleSelector::AttrEqual(_, _, _) |
SimpleSelector::AttrIncludes(_, _) |
SimpleSelector::AttrDashMatch(_, _) |
SimpleSelector::AttrPrefixMatch(_, _) |
SimpleSelector::AttrSubstringMatch(_, _) |
SimpleSelector::AttrSuffixMatch(_, _) => true,
_ => false,
}
}
fn combinator_to_restyle_hint(combinator: Option<Combinator>) -> RestyleHint {
match combinator {
None => RESTYLE_SELF,
Some(c) => match c {
Combinator::Child => RESTYLE_DESCENDANTS,
Combinator::Descendant => RESTYLE_DESCENDANTS,
Combinator::NextSibling => RESTYLE_LATER_SIBLINGS,
Combinator::LaterSibling => RESTYLE_LATER_SIBLINGS,
}
}
}
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
struct Sensitivities {
pub states: ElementState,
pub attrs: bool,
}
impl Sensitivities {
fn is_empty(&self) -> bool {
self.states.is_empty() &&!self.attrs
}
fn new() -> Sensitivities {
Sensitivities {
states: ElementState::empty(),
attrs: false,
}
}
}
/// Mapping between (partial) CompoundSelectors (and the combinator to their
/// right) and the states and attributes they depend on.
///
/// In general, for all selectors in all applicable stylesheets of the form:
///
/// |a _ b _ c _ d _ e|
///
/// Where:
/// * |b| and |d| are simple selectors that depend on state (like :hover) or
/// attributes (like [attr...],.foo, or #foo).
/// * |a|, |c|, and |e| are arbitrary simple selectors that do not depend on
/// state or attributes.
///
/// We generate a Dependency for both |a _ b:X _| and |a _ b:X _ c _ d:Y _|,
/// even though those selectors may not appear on their own in any stylesheet.
/// This allows us to quickly scan through the dependency sites of all style
/// rules and determine the maximum effect that a given state or attribute
/// change may have on the style of elements in the document.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
struct Dependency {
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
selector: Arc<ComplexSelector<SelectorImpl>>,
hint: RestyleHint,
sensitivities: Sensitivities,
}
/// A set of dependencies for a given stylist.
///
/// Note that there are measurable perf wins from storing them separately
/// depending on what kind of change they affect, and its also not a big deal to
/// do it, since the dependencies are per-document.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct DependencySet {
/// Dependencies only affected by state.
state_deps: Vec<Dependency>,
/// Dependencies only affected by attributes.
attr_deps: Vec<Dependency>,
/// Dependencies affected by both.
common_deps: Vec<Dependency>,
}
impl DependencySet {
fn add_dependency(&mut self, dep: Dependency) {
let affects_attrs = dep.sensitivities.attrs;
let affects_states =!dep.sensitivities.states.is_empty();
if affects_attrs && affects_states {
self.common_deps.push(dep)
} else if affects_attrs {
self.attr_deps.push(dep)
} else {
self.state_deps.push(dep)
}
}
/// Create an empty `DependencySet`.
pub fn new() -> Self {
DependencySet {
state_deps: vec![],
attr_deps: vec![],
common_deps: vec![],
}
}
/// Return the total number of dependencies that this set contains.
pub fn len(&self) -> usize {
self.common_deps.len() + self.attr_deps.len() + self.state_deps.len()
}
/// Create the needed dependencies that a given selector creates, and add
/// them to the set.
pub fn note_selector(&mut self, selector: &Arc<ComplexSelector<SelectorImpl>>) {
let mut cur = selector;
let mut combinator: Option<Combinator> = None;
loop {
let mut sensitivities = Sensitivities::new();
for s in &cur.compound_selector {
sensitivities.states.insert(selector_to_state(s));
if!sensitivities.attrs {
sensitivities.attrs = is_attr_selector(s);
}
}
if!sensitivities.is_empty() {
self.add_dependency(Dependency {
selector: cur.clone(),
hint: combinator_to_restyle_hint(combinator),
sensitivities: sensitivities,
});
}
cur = match cur.next {
Some((ref sel, comb)) => {
combinator = Some(comb);
sel
}
None => break,
}
}
}
/// Clear this dependency set.
pub fn clear(&mut self) {
self.common_deps.clear();
self.attr_deps.clear();
self.state_deps.clear();
}
/// Compute a restyle hint given an element and a snapshot, per the rules
/// explained in the rest of the documentation.
pub fn compute_hint<E>(&self,
el: &E,
snapshot: &Snapshot)
-> RestyleHint
where E: TElement + Clone,
{
let current_state = el.get_state();
let state_changes = snapshot.state()
.map_or_else(ElementState::empty, |old_state| current_state ^ old_state);
let attrs_changed = snapshot.has_attrs();
if state_changes.is_empty() &&!attrs_changed {
return RestyleHint::empty();
}
let mut hint = RestyleHint::empty();
let snapshot_el = ElementWrapper::new_with_snapshot(el.clone(), snapshot);
Self::compute_partial_hint(&self.common_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
if!state_changes.is_empty() {
Self::compute_partial_hint(&self.state_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
}
if attrs_changed {
Self::compute_partial_hint(&self.attr_deps, el, &snapshot_el,
&state_changes, attrs_changed, &mut hint);
}
debug!("Calculated restyle hint: {:?}. (Element={:?}, State={:?}, Snapshot={:?}, {} Deps)",
hint, el, current_state, snapshot, self.len());
trace!("Deps: {:?}", self);
hint
}
fn compute_partial_hint<E>(deps: &[Dependency],
element: &E,
snapshot: &ElementWrapper<E>,
state_changes: &ElementState,
attrs_changed: bool,
hint: &mut RestyleHint)
where E: TElement,
{
if hint.is_all() {
return;
}
for dep in deps {
debug_assert!((!state_changes.is_empty() &&!dep.sensitivities.states.is_empty()) ||
(attrs_changed && dep.sensitivities.attrs),
"Testing a known ineffective dependency?");
if (attrs_changed || state_changes.intersects(dep.sensitivities.states)) &&!hint.intersects(dep.hint) {
// We can ignore the selector flags, since they would have already been set during
// original matching for any element that might change its matching behavior here.
let matched_then =
matches_complex_selector(&dep.selector, snapshot, None,
&mut StyleRelations::empty(),
&mut ElementSelectorFlags::empty());
let matches_now =
matches_complex_selector(&dep.selector, element, None,
&mut StyleRelations::empty(),
&mut ElementSelectorFlags::empty());
if matched_then!= matches_now {
hint.insert(dep.hint);
|
{
use std::mem;
let raw_bits: u32 = unsafe { mem::transmute(raw) };
// FIXME(bholley): Finish aligning the binary representations here and
// then .expect() the result of the checked version.
if Self::from_bits(raw_bits).is_none() {
error!("stylo: dropping unsupported restyle hint bits");
}
Self::from_bits_truncate(raw_bits)
}
|
identifier_body
|
levenshtein_distance.rs
|
// http://rosettacode.org/wiki/Levenshtein_distance
#[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn levenshtein_distance(word1: &str, word2: &str) -> usize {
let word1_length = word1.len() + 1;
let word2_length = word2.len() + 1;
let mut matrix = vec![vec![0]];
for i in 1..word1_length {
matrix[0].push(i);
}
for j in 1..word2_length {
matrix.push(vec![j]);
}
for j in 1..word2_length {
for i in 1..word1_length {
let x: usize = if word1.chars().nth(i - 1) == word2.chars().nth(j - 1) {
matrix[j - 1][i - 1]
} else
|
;
matrix[j].push(x);
}
}
matrix[word2_length - 1][word1_length - 1]
}
fn main() {
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
println!("{}", levenshtein_distance("rosettacode", "raisethysword"));
}
#[test]
fn test_levenshtein_distance() {
assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
}
|
{
let min_distance = [matrix[j][i - 1], matrix[j - 1][i], matrix[j - 1][i - 1]];
*min_distance.iter().min().unwrap() + 1
}
|
conditional_block
|
levenshtein_distance.rs
|
// http://rosettacode.org/wiki/Levenshtein_distance
#[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn
|
(word1: &str, word2: &str) -> usize {
let word1_length = word1.len() + 1;
let word2_length = word2.len() + 1;
let mut matrix = vec![vec![0]];
for i in 1..word1_length {
matrix[0].push(i);
}
for j in 1..word2_length {
matrix.push(vec![j]);
}
for j in 1..word2_length {
for i in 1..word1_length {
let x: usize = if word1.chars().nth(i - 1) == word2.chars().nth(j - 1) {
matrix[j - 1][i - 1]
} else {
let min_distance = [matrix[j][i - 1], matrix[j - 1][i], matrix[j - 1][i - 1]];
*min_distance.iter().min().unwrap() + 1
};
matrix[j].push(x);
}
}
matrix[word2_length - 1][word1_length - 1]
}
fn main() {
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
println!("{}", levenshtein_distance("rosettacode", "raisethysword"));
}
#[test]
fn test_levenshtein_distance() {
assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
}
|
levenshtein_distance
|
identifier_name
|
levenshtein_distance.rs
|
// http://rosettacode.org/wiki/Levenshtein_distance
#[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn levenshtein_distance(word1: &str, word2: &str) -> usize {
let word1_length = word1.len() + 1;
let word2_length = word2.len() + 1;
let mut matrix = vec![vec![0]];
for i in 1..word1_length {
matrix[0].push(i);
}
for j in 1..word2_length {
matrix.push(vec![j]);
}
for j in 1..word2_length {
for i in 1..word1_length {
let x: usize = if word1.chars().nth(i - 1) == word2.chars().nth(j - 1) {
matrix[j - 1][i - 1]
} else {
let min_distance = [matrix[j][i - 1], matrix[j - 1][i], matrix[j - 1][i - 1]];
*min_distance.iter().min().unwrap() + 1
};
matrix[j].push(x);
}
}
matrix[word2_length - 1][word1_length - 1]
}
fn main()
|
#[test]
fn test_levenshtein_distance() {
assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
}
|
{
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
println!("{}", levenshtein_distance("rosettacode", "raisethysword"));
}
|
identifier_body
|
levenshtein_distance.rs
|
// http://rosettacode.org/wiki/Levenshtein_distance
#[cfg_attr(feature="clippy", allow(needless_range_loop))]
fn levenshtein_distance(word1: &str, word2: &str) -> usize {
let word1_length = word1.len() + 1;
let word2_length = word2.len() + 1;
let mut matrix = vec![vec![0]];
for i in 1..word1_length {
matrix[0].push(i);
}
for j in 1..word2_length {
matrix.push(vec![j]);
}
for j in 1..word2_length {
for i in 1..word1_length {
let x: usize = if word1.chars().nth(i - 1) == word2.chars().nth(j - 1) {
matrix[j - 1][i - 1]
} else {
let min_distance = [matrix[j][i - 1], matrix[j - 1][i], matrix[j - 1][i - 1]];
*min_distance.iter().min().unwrap() + 1
};
matrix[j].push(x);
}
}
matrix[word2_length - 1][word1_length - 1]
}
fn main() {
println!("{}", levenshtein_distance("kitten", "sitting"));
println!("{}", levenshtein_distance("saturday", "sunday"));
|
}
#[test]
fn test_levenshtein_distance() {
assert_eq!(levenshtein_distance("kitten", "sitting"), 3);
}
|
println!("{}", levenshtein_distance("rosettacode", "raisethysword"));
|
random_line_split
|
send_state_event.rs
|
//! `PUT /_matrix/client/*/rooms/{roomId}/state/{eventType}/{stateKey}`
pub mod v3 {
//! `/v3/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/client-server-api/#put_matrixclientv3roomsroomidstateeventtypestatekey
use ruma_common::{
api::ruma_api,
events::{AnyStateEventContent, StateEventContent},
EventId, RoomId,
};
use ruma_serde::{Outgoing, Raw};
use serde_json::value::to_raw_value as to_raw_json_value;
ruma_api! {
metadata: {
description: "Send a state event to a room associated with a given state key.",
method: PUT,
name: "send_state_event",
r0_path: "/_matrix/client/r0/rooms/:room_id/state/:event_type/:state_key",
stable_path: "/_matrix/client/v3/rooms/:room_id/state/:event_type/:state_key",
rate_limited: false,
authentication: AccessToken,
added: 1.0,
}
response: {
/// A unique identifier for the event.
pub event_id: Box<EventId>,
}
error: crate::Error
}
/// Data for a request to the `send_state_event` API endpoint.
///
/// Send a state event to a room associated with a given state key.
#[derive(Clone, Debug, Outgoing)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[incoming_derive(!Deserialize)]
pub struct
|
<'a> {
/// The room to set the state in.
pub room_id: &'a RoomId,
/// The type of event to send.
pub event_type: &'a str,
/// The state_key for the state to send.
pub state_key: &'a str,
/// The event content to send.
pub body: Raw<AnyStateEventContent>,
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room id, state key and event content.
///
/// # Errors
///
/// Since `Request` stores the request body in serialized form, this function can fail if
/// `T`s [`Serialize`][serde::Serialize] implementation can fail.
pub fn new<T: StateEventContent>(
room_id: &'a RoomId,
state_key: &'a str,
content: &'a T,
) -> serde_json::Result<Self> {
Ok(Self {
room_id,
state_key,
event_type: content.event_type(),
body: Raw::from_json(to_raw_json_value(content)?),
})
}
/// Creates a new `Request` with the given room id, event type, state key and raw event
/// content.
pub fn new_raw(
room_id: &'a RoomId,
event_type: &'a str,
state_key: &'a str,
body: Raw<AnyStateEventContent>,
) -> Self {
Self { room_id, event_type, state_key, body }
}
}
impl Response {
/// Creates a new `Response` with the given event id.
pub fn new(event_id: Box<EventId>) -> Self {
Self { event_id }
}
}
#[cfg(feature = "client")]
impl<'a> ruma_common::api::OutgoingRequest for Request<'a> {
type EndpointError = crate::Error;
type IncomingResponse = Response;
const METADATA: ruma_common::api::Metadata = METADATA;
fn try_into_http_request<T: Default + bytes::BufMut>(
self,
base_url: &str,
access_token: ruma_common::api::SendAccessToken<'_>,
considering_versions: &'_ [ruma_common::api::MatrixVersion],
) -> Result<http::Request<T>, ruma_common::api::error::IntoHttpError> {
use std::borrow::Cow;
use http::header::{self, HeaderValue};
use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
let room_id_percent = utf8_percent_encode(self.room_id.as_str(), NON_ALPHANUMERIC);
let event_type_percent = utf8_percent_encode(self.event_type, NON_ALPHANUMERIC);
let mut url = format!(
"{}{}",
base_url.strip_suffix('/').unwrap_or(base_url),
ruma_common::api::select_path(
considering_versions,
&METADATA,
None,
Some(format_args!(
"/_matrix/client/r0/rooms/{}/state/{}",
room_id_percent, event_type_percent
)),
None,
)?
);
// Last URL segment is optional, that is why this trait impl is not generated.
if!self.state_key.is_empty() {
url.push('/');
url.push_str(&Cow::from(utf8_percent_encode(self.state_key, NON_ALPHANUMERIC)));
}
let http_request = http::Request::builder()
.method(http::Method::PUT)
.uri(url)
.header(header::CONTENT_TYPE, "application/json")
.header(
header::AUTHORIZATION,
HeaderValue::from_str(&format!(
"Bearer {}",
access_token
.get_required_for_endpoint()
.ok_or(ruma_common::api::error::IntoHttpError::NeedsAuthentication)?
))?,
)
.body(ruma_serde::json_to_buf(&self.body)?)?;
Ok(http_request)
}
}
#[cfg(feature = "server")]
impl ruma_common::api::IncomingRequest for IncomingRequest {
type EndpointError = crate::Error;
type OutgoingResponse = Response;
const METADATA: ruma_common::api::Metadata = METADATA;
fn try_from_http_request<B, S>(
request: http::Request<B>,
path_args: &[S],
) -> Result<Self, ruma_common::api::error::FromHttpRequestError>
where
B: AsRef<[u8]>,
S: AsRef<str>,
{
// FIXME: find a way to make this if-else collapse with serde recognizing trailing
// Option
let (room_id, event_type, state_key): (Box<RoomId>, String, String) = if path_args.len()
== 3
{
serde::Deserialize::deserialize(serde::de::value::SeqDeserializer::<
_,
serde::de::value::Error,
>::new(
path_args.iter().map(::std::convert::AsRef::as_ref),
))?
} else {
let (a, b) = serde::Deserialize::deserialize(serde::de::value::SeqDeserializer::<
_,
serde::de::value::Error,
>::new(
path_args.iter().map(::std::convert::AsRef::as_ref),
))?;
(a, b, "".into())
};
let body = serde_json::from_slice(request.body().as_ref())?;
Ok(Self { room_id, event_type, state_key, body })
}
}
}
|
Request
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.