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 |
---|---|---|---|---|
zlib.rs
|
//! An Implementation of RFC 1950
//!
//! Decoding of zlib compressed streams.
//!
|
use std::old_io;
use std::old_io::IoResult;
use super::hash::Adler32;
use super::deflate::Inflater;
enum ZlibState {
Start,
CompressedData,
End
}
/// A Zlib compressed stream decoder.
pub struct ZlibDecoder<R> {
inflate: Inflater<R>,
adler: Adler32,
state: ZlibState,
}
impl<R: Reader> ZlibDecoder<R> {
/// Create a new decoder that decodes from a Reader
pub fn new(r: R) -> ZlibDecoder<R> {
ZlibDecoder {
inflate: Inflater::new(r),
adler: Adler32::new(),
state: ZlibState::Start,
}
}
/// Return a mutable reference to the wrapped Reader
pub fn inner(&mut self) -> &mut R {
self.inflate.inner()
}
fn read_header(&mut self) -> IoResult<()> {
let cmf = try!(self.inner().read_u8());
let _cm = cmf & 0x0F;
let _cinfo = cmf >> 4;
let flg = try!(self.inner().read_u8());
let fdict = (flg & 0b100000)!= 0;
if fdict {
let _dictid = try!(self.inner().read_be_u32());
panic!("invalid png: zlib detected fdict true")
}
assert!((cmf as u16 * 256 + flg as u16) % 31 == 0);
Ok(())
}
fn read_checksum(&mut self) -> IoResult<()> {
let stream_adler32 = try!(self.inner().read_be_u32());
let adler32 = self.adler.checksum();
assert!(adler32 == stream_adler32);
self.adler.reset();
Ok(())
}
}
impl<R: Reader> Reader for ZlibDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match self.state {
ZlibState::CompressedData => {
match self.inflate.read(buf) {
Ok(n) => {
self.adler.update(&buf[..n]);
if self.inflate.eof() {
let _ = try!(self.read_checksum());
self.state = ZlibState::End;
}
Ok(n)
}
e => e
}
}
ZlibState::Start => {
let _ = try!(self.read_header());
self.state = ZlibState::CompressedData;
self.read(buf)
}
ZlibState::End => Err(old_io::standard_error(old_io::EndOfFile))
}
}
}
|
//! # Related Links
//! *http://tools.ietf.org/html/rfc1950 - ZLIB Compressed Data Format Specification
|
random_line_split
|
zlib.rs
|
//! An Implementation of RFC 1950
//!
//! Decoding of zlib compressed streams.
//!
//! # Related Links
//! *http://tools.ietf.org/html/rfc1950 - ZLIB Compressed Data Format Specification
use std::old_io;
use std::old_io::IoResult;
use super::hash::Adler32;
use super::deflate::Inflater;
enum ZlibState {
Start,
CompressedData,
End
}
/// A Zlib compressed stream decoder.
pub struct ZlibDecoder<R> {
inflate: Inflater<R>,
adler: Adler32,
state: ZlibState,
}
impl<R: Reader> ZlibDecoder<R> {
/// Create a new decoder that decodes from a Reader
pub fn new(r: R) -> ZlibDecoder<R> {
ZlibDecoder {
inflate: Inflater::new(r),
adler: Adler32::new(),
state: ZlibState::Start,
}
}
/// Return a mutable reference to the wrapped Reader
pub fn
|
(&mut self) -> &mut R {
self.inflate.inner()
}
fn read_header(&mut self) -> IoResult<()> {
let cmf = try!(self.inner().read_u8());
let _cm = cmf & 0x0F;
let _cinfo = cmf >> 4;
let flg = try!(self.inner().read_u8());
let fdict = (flg & 0b100000)!= 0;
if fdict {
let _dictid = try!(self.inner().read_be_u32());
panic!("invalid png: zlib detected fdict true")
}
assert!((cmf as u16 * 256 + flg as u16) % 31 == 0);
Ok(())
}
fn read_checksum(&mut self) -> IoResult<()> {
let stream_adler32 = try!(self.inner().read_be_u32());
let adler32 = self.adler.checksum();
assert!(adler32 == stream_adler32);
self.adler.reset();
Ok(())
}
}
impl<R: Reader> Reader for ZlibDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match self.state {
ZlibState::CompressedData => {
match self.inflate.read(buf) {
Ok(n) => {
self.adler.update(&buf[..n]);
if self.inflate.eof() {
let _ = try!(self.read_checksum());
self.state = ZlibState::End;
}
Ok(n)
}
e => e
}
}
ZlibState::Start => {
let _ = try!(self.read_header());
self.state = ZlibState::CompressedData;
self.read(buf)
}
ZlibState::End => Err(old_io::standard_error(old_io::EndOfFile))
}
}
}
|
inner
|
identifier_name
|
zlib.rs
|
//! An Implementation of RFC 1950
//!
//! Decoding of zlib compressed streams.
//!
//! # Related Links
//! *http://tools.ietf.org/html/rfc1950 - ZLIB Compressed Data Format Specification
use std::old_io;
use std::old_io::IoResult;
use super::hash::Adler32;
use super::deflate::Inflater;
enum ZlibState {
Start,
CompressedData,
End
}
/// A Zlib compressed stream decoder.
pub struct ZlibDecoder<R> {
inflate: Inflater<R>,
adler: Adler32,
state: ZlibState,
}
impl<R: Reader> ZlibDecoder<R> {
/// Create a new decoder that decodes from a Reader
pub fn new(r: R) -> ZlibDecoder<R> {
ZlibDecoder {
inflate: Inflater::new(r),
adler: Adler32::new(),
state: ZlibState::Start,
}
}
/// Return a mutable reference to the wrapped Reader
pub fn inner(&mut self) -> &mut R {
self.inflate.inner()
}
fn read_header(&mut self) -> IoResult<()>
|
fn read_checksum(&mut self) -> IoResult<()> {
let stream_adler32 = try!(self.inner().read_be_u32());
let adler32 = self.adler.checksum();
assert!(adler32 == stream_adler32);
self.adler.reset();
Ok(())
}
}
impl<R: Reader> Reader for ZlibDecoder<R> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match self.state {
ZlibState::CompressedData => {
match self.inflate.read(buf) {
Ok(n) => {
self.adler.update(&buf[..n]);
if self.inflate.eof() {
let _ = try!(self.read_checksum());
self.state = ZlibState::End;
}
Ok(n)
}
e => e
}
}
ZlibState::Start => {
let _ = try!(self.read_header());
self.state = ZlibState::CompressedData;
self.read(buf)
}
ZlibState::End => Err(old_io::standard_error(old_io::EndOfFile))
}
}
}
|
{
let cmf = try!(self.inner().read_u8());
let _cm = cmf & 0x0F;
let _cinfo = cmf >> 4;
let flg = try!(self.inner().read_u8());
let fdict = (flg & 0b100000) != 0;
if fdict {
let _dictid = try!(self.inner().read_be_u32());
panic!("invalid png: zlib detected fdict true")
}
assert!((cmf as u16 * 256 + flg as u16) % 31 == 0);
Ok(())
}
|
identifier_body
|
regions-pattern-typing-issue-19997.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
fn main()
|
{
let a0 = 0;
let f = 1;
let mut a1 = &a0;
match (&a1,) {
(&ref b0,) => {
a1 = &f; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign to `a1` because it is borrowed
drop(b0);
}
}
}
|
identifier_body
|
|
regions-pattern-typing-issue-19997.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
fn main() {
let a0 = 0;
let f = 1;
let mut a1 = &a0;
match (&a1,) {
(&ref b0,) => {
a1 = &f; //[ast]~ ERROR cannot assign
|
drop(b0);
}
}
}
|
//[mir]~^ ERROR cannot assign to `a1` because it is borrowed
|
random_line_split
|
regions-pattern-typing-issue-19997.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
fn
|
() {
let a0 = 0;
let f = 1;
let mut a1 = &a0;
match (&a1,) {
(&ref b0,) => {
a1 = &f; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign to `a1` because it is borrowed
drop(b0);
}
}
}
|
main
|
identifier_name
|
regions-pattern-typing-issue-19997.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
fn main() {
let a0 = 0;
let f = 1;
let mut a1 = &a0;
match (&a1,) {
(&ref b0,) =>
|
}
}
|
{
a1 = &f; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign to `a1` because it is borrowed
drop(b0);
}
|
conditional_block
|
git.rs
|
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use url::Url;
use git2;
use craft::util::ProcessError;
use support::{ProjectBuilder, project, path2url};
pub struct RepoBuilder {
repo: git2::Repository,
files: Vec<PathBuf>,
}
pub fn repo(p: &Path) -> RepoBuilder {
RepoBuilder::init(p)
}
impl RepoBuilder {
pub fn init(p: &Path) -> RepoBuilder {
t!(fs::create_dir_all(p.parent().unwrap()));
let repo = t!(git2::Repository::init(p));
{
let mut config = t!(repo.config());
t!(config.set_str("user.name", "name"));
t!(config.set_str("user.email", "email"));
}
RepoBuilder {
repo: repo,
files: Vec::new(),
}
}
pub fn file(self, path: &str, contents: &str) -> RepoBuilder {
let mut me = self.nocommit_file(path, contents);
me.files.push(PathBuf::from(path));
me
}
pub fn nocommit_file(self, path: &str, contents: &str) -> RepoBuilder {
let dst = self.repo.workdir().unwrap().join(path);
t!(fs::create_dir_all(dst.parent().unwrap()));
t!(t!(File::create(&dst)).write_all(contents.as_bytes()));
self
}
pub fn build(&self) {
let mut index = t!(self.repo.index());
for file in self.files.iter() {
t!(index.add_path(file));
}
t!(index.write());
let id = t!(index.write_tree());
let tree = t!(self.repo.find_tree(id));
let sig = t!(self.repo.signature());
t!(self.repo.commit(Some("HEAD"), &sig, &sig,
"Initial commit", &tree, &[]));
}
pub fn root(&self) -> &Path {
self.repo.workdir().unwrap()
}
pub fn url(&self) -> Url
|
}
pub fn new<F>(name: &str, callback: F) -> Result<ProjectBuilder, ProcessError>
where F: FnOnce(ProjectBuilder) -> ProjectBuilder
{
let mut git_project = project(name);
git_project = callback(git_project);
git_project.build();
let repo = t!(git2::Repository::init(&git_project.root()));
let mut cfg = t!(repo.config());
t!(cfg.set_str("user.email", "[email protected]"));
t!(cfg.set_str("user.name", "Foo Bar"));
drop(cfg);
add(&repo);
commit(&repo);
Ok(git_project)
}
pub fn add(repo: &git2::Repository) {
// FIXME(libgit2/libgit2#2514): apparently add_all will add all submodules
// as well, and then fail b/c they're a directory. As a stopgap, we just
// ignore all submodules.
let mut s = t!(repo.submodules());
for submodule in s.iter_mut() {
t!(submodule.add_to_index(false));
}
let mut index = t!(repo.index());
t!(index.add_all(["*"].iter(), git2::ADD_DEFAULT,
Some(&mut (|a, _b| {
if s.iter().any(|s| a.starts_with(s.path())) {1} else {0}
}))));
t!(index.write());
}
pub fn add_submodule<'a>(repo: &'a git2::Repository, url: &str, path: &Path) -> git2::Submodule<'a> {
let path = path.to_str().unwrap().replace(r"\", "/");
let mut s = t!(repo.submodule(url, Path::new(&path), false));
let subrepo = t!(s.open());
t!(subrepo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*"));
let mut origin = t!(subrepo.find_remote("origin"));
t!(origin.fetch(&[], None, None));
t!(subrepo.checkout_head(None));
t!(s.add_finalize());
return s;
}
pub fn commit(repo: &git2::Repository) -> git2::Oid {
let tree_id = t!(t!(repo.index()).write_tree());
let sig = t!(repo.signature());
let mut parents = Vec::new();
match repo.head().ok().map(|h| h.target().unwrap()) {
Some(parent) => parents.push(t!(repo.find_commit(parent))),
None => {}
}
let parents = parents.iter().collect::<Vec<_>>();
t!(repo.commit(Some("HEAD"), &sig, &sig, "test",
&t!(repo.find_tree(tree_id)),
&parents))
}
pub fn tag(repo: &git2::Repository, name: &str) {
let head = repo.head().unwrap().target().unwrap();
t!(repo.tag(name,
&t!(repo.find_object(head, None)),
&t!(repo.signature()),
"make a new tag",
false));
}
|
{
path2url(self.repo.workdir().unwrap().to_path_buf())
}
|
identifier_body
|
git.rs
|
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use url::Url;
use git2;
use craft::util::ProcessError;
use support::{ProjectBuilder, project, path2url};
pub struct RepoBuilder {
repo: git2::Repository,
files: Vec<PathBuf>,
}
pub fn repo(p: &Path) -> RepoBuilder {
RepoBuilder::init(p)
}
impl RepoBuilder {
pub fn init(p: &Path) -> RepoBuilder {
t!(fs::create_dir_all(p.parent().unwrap()));
let repo = t!(git2::Repository::init(p));
{
let mut config = t!(repo.config());
t!(config.set_str("user.name", "name"));
t!(config.set_str("user.email", "email"));
}
RepoBuilder {
repo: repo,
files: Vec::new(),
}
}
pub fn file(self, path: &str, contents: &str) -> RepoBuilder {
let mut me = self.nocommit_file(path, contents);
me.files.push(PathBuf::from(path));
me
}
pub fn nocommit_file(self, path: &str, contents: &str) -> RepoBuilder {
let dst = self.repo.workdir().unwrap().join(path);
t!(fs::create_dir_all(dst.parent().unwrap()));
t!(t!(File::create(&dst)).write_all(contents.as_bytes()));
self
}
pub fn build(&self) {
let mut index = t!(self.repo.index());
for file in self.files.iter() {
t!(index.add_path(file));
}
t!(index.write());
let id = t!(index.write_tree());
let tree = t!(self.repo.find_tree(id));
let sig = t!(self.repo.signature());
t!(self.repo.commit(Some("HEAD"), &sig, &sig,
"Initial commit", &tree, &[]));
}
pub fn root(&self) -> &Path {
self.repo.workdir().unwrap()
}
pub fn url(&self) -> Url {
path2url(self.repo.workdir().unwrap().to_path_buf())
}
}
pub fn new<F>(name: &str, callback: F) -> Result<ProjectBuilder, ProcessError>
where F: FnOnce(ProjectBuilder) -> ProjectBuilder
{
let mut git_project = project(name);
git_project = callback(git_project);
git_project.build();
let repo = t!(git2::Repository::init(&git_project.root()));
let mut cfg = t!(repo.config());
t!(cfg.set_str("user.email", "[email protected]"));
t!(cfg.set_str("user.name", "Foo Bar"));
drop(cfg);
add(&repo);
commit(&repo);
Ok(git_project)
}
pub fn add(repo: &git2::Repository) {
// FIXME(libgit2/libgit2#2514): apparently add_all will add all submodules
// as well, and then fail b/c they're a directory. As a stopgap, we just
// ignore all submodules.
let mut s = t!(repo.submodules());
for submodule in s.iter_mut() {
t!(submodule.add_to_index(false));
}
let mut index = t!(repo.index());
t!(index.add_all(["*"].iter(), git2::ADD_DEFAULT,
Some(&mut (|a, _b| {
if s.iter().any(|s| a.starts_with(s.path())) {1} else {0}
}))));
t!(index.write());
}
pub fn add_submodule<'a>(repo: &'a git2::Repository, url: &str, path: &Path) -> git2::Submodule<'a> {
let path = path.to_str().unwrap().replace(r"\", "/");
let mut s = t!(repo.submodule(url, Path::new(&path), false));
let subrepo = t!(s.open());
t!(subrepo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*"));
let mut origin = t!(subrepo.find_remote("origin"));
t!(origin.fetch(&[], None, None));
t!(subrepo.checkout_head(None));
t!(s.add_finalize());
return s;
}
pub fn commit(repo: &git2::Repository) -> git2::Oid {
let tree_id = t!(t!(repo.index()).write_tree());
let sig = t!(repo.signature());
let mut parents = Vec::new();
|
t!(repo.commit(Some("HEAD"), &sig, &sig, "test",
&t!(repo.find_tree(tree_id)),
&parents))
}
pub fn tag(repo: &git2::Repository, name: &str) {
let head = repo.head().unwrap().target().unwrap();
t!(repo.tag(name,
&t!(repo.find_object(head, None)),
&t!(repo.signature()),
"make a new tag",
false));
}
|
match repo.head().ok().map(|h| h.target().unwrap()) {
Some(parent) => parents.push(t!(repo.find_commit(parent))),
None => {}
}
let parents = parents.iter().collect::<Vec<_>>();
|
random_line_split
|
git.rs
|
use std::fs::{self, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use url::Url;
use git2;
use craft::util::ProcessError;
use support::{ProjectBuilder, project, path2url};
pub struct RepoBuilder {
repo: git2::Repository,
files: Vec<PathBuf>,
}
pub fn repo(p: &Path) -> RepoBuilder {
RepoBuilder::init(p)
}
impl RepoBuilder {
pub fn
|
(p: &Path) -> RepoBuilder {
t!(fs::create_dir_all(p.parent().unwrap()));
let repo = t!(git2::Repository::init(p));
{
let mut config = t!(repo.config());
t!(config.set_str("user.name", "name"));
t!(config.set_str("user.email", "email"));
}
RepoBuilder {
repo: repo,
files: Vec::new(),
}
}
pub fn file(self, path: &str, contents: &str) -> RepoBuilder {
let mut me = self.nocommit_file(path, contents);
me.files.push(PathBuf::from(path));
me
}
pub fn nocommit_file(self, path: &str, contents: &str) -> RepoBuilder {
let dst = self.repo.workdir().unwrap().join(path);
t!(fs::create_dir_all(dst.parent().unwrap()));
t!(t!(File::create(&dst)).write_all(contents.as_bytes()));
self
}
pub fn build(&self) {
let mut index = t!(self.repo.index());
for file in self.files.iter() {
t!(index.add_path(file));
}
t!(index.write());
let id = t!(index.write_tree());
let tree = t!(self.repo.find_tree(id));
let sig = t!(self.repo.signature());
t!(self.repo.commit(Some("HEAD"), &sig, &sig,
"Initial commit", &tree, &[]));
}
pub fn root(&self) -> &Path {
self.repo.workdir().unwrap()
}
pub fn url(&self) -> Url {
path2url(self.repo.workdir().unwrap().to_path_buf())
}
}
pub fn new<F>(name: &str, callback: F) -> Result<ProjectBuilder, ProcessError>
where F: FnOnce(ProjectBuilder) -> ProjectBuilder
{
let mut git_project = project(name);
git_project = callback(git_project);
git_project.build();
let repo = t!(git2::Repository::init(&git_project.root()));
let mut cfg = t!(repo.config());
t!(cfg.set_str("user.email", "[email protected]"));
t!(cfg.set_str("user.name", "Foo Bar"));
drop(cfg);
add(&repo);
commit(&repo);
Ok(git_project)
}
pub fn add(repo: &git2::Repository) {
// FIXME(libgit2/libgit2#2514): apparently add_all will add all submodules
// as well, and then fail b/c they're a directory. As a stopgap, we just
// ignore all submodules.
let mut s = t!(repo.submodules());
for submodule in s.iter_mut() {
t!(submodule.add_to_index(false));
}
let mut index = t!(repo.index());
t!(index.add_all(["*"].iter(), git2::ADD_DEFAULT,
Some(&mut (|a, _b| {
if s.iter().any(|s| a.starts_with(s.path())) {1} else {0}
}))));
t!(index.write());
}
pub fn add_submodule<'a>(repo: &'a git2::Repository, url: &str, path: &Path) -> git2::Submodule<'a> {
let path = path.to_str().unwrap().replace(r"\", "/");
let mut s = t!(repo.submodule(url, Path::new(&path), false));
let subrepo = t!(s.open());
t!(subrepo.remote_add_fetch("origin", "refs/heads/*:refs/heads/*"));
let mut origin = t!(subrepo.find_remote("origin"));
t!(origin.fetch(&[], None, None));
t!(subrepo.checkout_head(None));
t!(s.add_finalize());
return s;
}
pub fn commit(repo: &git2::Repository) -> git2::Oid {
let tree_id = t!(t!(repo.index()).write_tree());
let sig = t!(repo.signature());
let mut parents = Vec::new();
match repo.head().ok().map(|h| h.target().unwrap()) {
Some(parent) => parents.push(t!(repo.find_commit(parent))),
None => {}
}
let parents = parents.iter().collect::<Vec<_>>();
t!(repo.commit(Some("HEAD"), &sig, &sig, "test",
&t!(repo.find_tree(tree_id)),
&parents))
}
pub fn tag(repo: &git2::Repository, name: &str) {
let head = repo.head().unwrap().target().unwrap();
t!(repo.tag(name,
&t!(repo.find_object(head, None)),
&t!(repo.signature()),
"make a new tag",
false));
}
|
init
|
identifier_name
|
struct.rs
|
// 一个 `Borrowed` 类型,含有一个指向 `i32` 类型的引用。
// 指向 `i32` 的引用必须比 `Borrowed` 寿命更长。
// (原望:A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.)
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// 和前面类似,这里的两个引用都必须比这个结构体长寿。
#[derive(Debug)]
struct NamedBorrowed<'a> {
x: &'a i32,
y: &'a i32,
}
// 一个枚举类型,不是 `i32` 类型就是一个指向某个量的引用。
//(原文: An enum which is either an `i32` or a reference to one.)
#[derive(Debug)]
enum Either<'a> {
Num(i32),
Ref(&'a i32),
}
fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
let reference = Either::Ref(&x);
let number = Either::Num(y);
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);
println!("x is borrowed in {:?}", reference);
|
println!("y is *not* borrowed in {:?}", number);
}
|
random_line_split
|
|
struct.rs
|
// 一个 `Borrowed` 类型,含有一个指向 `i32` 类型的引用。
// 指向 `i32` 的引用必须比 `Borrowed` 寿命更长。
// (原望:A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.)
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// 和前面类似,这里的两个引用都必须比这个结构体长寿。
#[derive(Debug)]
struct NamedBorrowed<'a> {
x: &'a i32,
y: &'a i32,
}
// 一个枚举类型,不是 `i32` 类型就是一个指向某个量的引用。
//(原文: An enum which is either an `i32` or a reference to one.)
#[derive(Debug)]
enum Either<'a> {
Num(i32),
Ref(&'a i32),
}
fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
let reference = Either::Ref(&x);
let number = Either
|
::Num(y);
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);
println!("x is borrowed in {:?}", reference);
println!("y is *not* borrowed in {:?}", number);
}
|
identifier_body
|
|
struct.rs
|
// 一个 `Borrowed` 类型,含有一个指向 `i32` 类型的引用。
// 指向 `i32` 的引用必须比 `Borrowed` 寿命更长。
// (原望:A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.)
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
// 和前面类似,这里的两个引用都必须比这个结构体长寿。
#[derive(Debug)]
struct NamedBorrowed<'a> {
x: &'a i32,
y: &'a i32,
}
// 一个枚举类型,不是 `i32` 类型就是一个指向某个量的引用。
//(原文: An enum which is either an `i32` or a reference to one.)
#[derive(Debug)]
enum Either<'a> {
Num(i32),
Ref(&'a i32),
}
fn main() {
let x = 18;
let y = 15;
let single = Borrowed(&x);
let double = NamedBorrowed { x: &x, y: &y };
l
|
erence = Either::Ref(&x);
let number = Either::Num(y);
println!("x is borrowed in {:?}", single);
println!("x and y are borrowed in {:?}", double);
println!("x is borrowed in {:?}", reference);
println!("y is *not* borrowed in {:?}", number);
}
|
et ref
|
identifier_name
|
kms.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use crate::error::{Error, KmsError, Result};
use derive_more::Deref;
use kvproto::encryptionpb::MasterKeyKms;
#[derive(Debug, Clone)]
pub struct Location {
pub region: String,
pub endpoint: String,
}
#[derive(Debug, Clone)]
pub struct Config {
pub key_id: KeyId,
pub location: Location,
pub vendor: String,
}
impl Config {
pub fn from_proto(mk: MasterKeyKms) -> Result<Self> {
Ok(Config {
key_id: KeyId::new(mk.key_id)?,
|
region: mk.region,
endpoint: mk.endpoint,
},
vendor: mk.vendor,
})
}
}
#[derive(PartialEq, Debug, Clone, Deref)]
pub struct KeyId(String);
// KeyID is a newtype to mark a String as an ID of a key
// This ID exists in a foreign system such as AWS
// The key id must be non-empty
impl KeyId {
pub fn new(id: String) -> Result<KeyId> {
if id.is_empty() {
let msg = "KMS key id can not be empty";
Err(Error::KmsError(KmsError::EmptyKey(msg.to_owned())))
} else {
Ok(KeyId(id))
}
}
}
// EncryptedKey is a newtype used to mark data as an encrypted key
// It requires the vec to be non-empty
#[derive(PartialEq, Clone, Debug, Deref)]
pub struct EncryptedKey(Vec<u8>);
impl EncryptedKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
if key.is_empty() {
Err(Error::KmsError(KmsError::EmptyKey(
"Encrypted Key".to_owned(),
)))
} else {
Ok(Self(key))
}
}
}
// PlainKey is a newtype used to mark a vector a plaintext key.
// It requires the vec to be a valid AesGcmCrypter key.
#[derive(Deref)]
pub struct PlainKey(Vec<u8>);
impl PlainKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
// TODO: crypter.rs in encryption performs additional validation
Ok(Self(key))
}
}
// Don't expose the key in a debug print
impl std::fmt::Debug for PlainKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("PlainKey")
.field(&"REDACTED".to_string())
.finish()
}
}
#[derive(Debug)]
pub struct DataKeyPair {
pub encrypted: EncryptedKey,
pub plaintext: PlainKey,
}
#[async_trait]
pub trait KmsProvider: Sync + Send +'static + std::fmt::Debug {
async fn generate_data_key(&self) -> Result<DataKeyPair>;
async fn decrypt_data_key(&self, data_key: &EncryptedKey) -> Result<Vec<u8>>;
fn name(&self) -> &str;
}
|
location: Location {
|
random_line_split
|
kms.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use crate::error::{Error, KmsError, Result};
use derive_more::Deref;
use kvproto::encryptionpb::MasterKeyKms;
#[derive(Debug, Clone)]
pub struct Location {
pub region: String,
pub endpoint: String,
}
#[derive(Debug, Clone)]
pub struct Config {
pub key_id: KeyId,
pub location: Location,
pub vendor: String,
}
impl Config {
pub fn from_proto(mk: MasterKeyKms) -> Result<Self> {
Ok(Config {
key_id: KeyId::new(mk.key_id)?,
location: Location {
region: mk.region,
endpoint: mk.endpoint,
},
vendor: mk.vendor,
})
}
}
#[derive(PartialEq, Debug, Clone, Deref)]
pub struct
|
(String);
// KeyID is a newtype to mark a String as an ID of a key
// This ID exists in a foreign system such as AWS
// The key id must be non-empty
impl KeyId {
pub fn new(id: String) -> Result<KeyId> {
if id.is_empty() {
let msg = "KMS key id can not be empty";
Err(Error::KmsError(KmsError::EmptyKey(msg.to_owned())))
} else {
Ok(KeyId(id))
}
}
}
// EncryptedKey is a newtype used to mark data as an encrypted key
// It requires the vec to be non-empty
#[derive(PartialEq, Clone, Debug, Deref)]
pub struct EncryptedKey(Vec<u8>);
impl EncryptedKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
if key.is_empty() {
Err(Error::KmsError(KmsError::EmptyKey(
"Encrypted Key".to_owned(),
)))
} else {
Ok(Self(key))
}
}
}
// PlainKey is a newtype used to mark a vector a plaintext key.
// It requires the vec to be a valid AesGcmCrypter key.
#[derive(Deref)]
pub struct PlainKey(Vec<u8>);
impl PlainKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
// TODO: crypter.rs in encryption performs additional validation
Ok(Self(key))
}
}
// Don't expose the key in a debug print
impl std::fmt::Debug for PlainKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("PlainKey")
.field(&"REDACTED".to_string())
.finish()
}
}
#[derive(Debug)]
pub struct DataKeyPair {
pub encrypted: EncryptedKey,
pub plaintext: PlainKey,
}
#[async_trait]
pub trait KmsProvider: Sync + Send +'static + std::fmt::Debug {
async fn generate_data_key(&self) -> Result<DataKeyPair>;
async fn decrypt_data_key(&self, data_key: &EncryptedKey) -> Result<Vec<u8>>;
fn name(&self) -> &str;
}
|
KeyId
|
identifier_name
|
kms.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use crate::error::{Error, KmsError, Result};
use derive_more::Deref;
use kvproto::encryptionpb::MasterKeyKms;
#[derive(Debug, Clone)]
pub struct Location {
pub region: String,
pub endpoint: String,
}
#[derive(Debug, Clone)]
pub struct Config {
pub key_id: KeyId,
pub location: Location,
pub vendor: String,
}
impl Config {
pub fn from_proto(mk: MasterKeyKms) -> Result<Self> {
Ok(Config {
key_id: KeyId::new(mk.key_id)?,
location: Location {
region: mk.region,
endpoint: mk.endpoint,
},
vendor: mk.vendor,
})
}
}
#[derive(PartialEq, Debug, Clone, Deref)]
pub struct KeyId(String);
// KeyID is a newtype to mark a String as an ID of a key
// This ID exists in a foreign system such as AWS
// The key id must be non-empty
impl KeyId {
pub fn new(id: String) -> Result<KeyId> {
if id.is_empty() {
let msg = "KMS key id can not be empty";
Err(Error::KmsError(KmsError::EmptyKey(msg.to_owned())))
} else {
Ok(KeyId(id))
}
}
}
// EncryptedKey is a newtype used to mark data as an encrypted key
// It requires the vec to be non-empty
#[derive(PartialEq, Clone, Debug, Deref)]
pub struct EncryptedKey(Vec<u8>);
impl EncryptedKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
if key.is_empty() {
Err(Error::KmsError(KmsError::EmptyKey(
"Encrypted Key".to_owned(),
)))
} else {
Ok(Self(key))
}
}
}
// PlainKey is a newtype used to mark a vector a plaintext key.
// It requires the vec to be a valid AesGcmCrypter key.
#[derive(Deref)]
pub struct PlainKey(Vec<u8>);
impl PlainKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
// TODO: crypter.rs in encryption performs additional validation
Ok(Self(key))
}
}
// Don't expose the key in a debug print
impl std::fmt::Debug for PlainKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
|
}
#[derive(Debug)]
pub struct DataKeyPair {
pub encrypted: EncryptedKey,
pub plaintext: PlainKey,
}
#[async_trait]
pub trait KmsProvider: Sync + Send +'static + std::fmt::Debug {
async fn generate_data_key(&self) -> Result<DataKeyPair>;
async fn decrypt_data_key(&self, data_key: &EncryptedKey) -> Result<Vec<u8>>;
fn name(&self) -> &str;
}
|
{
f.debug_tuple("PlainKey")
.field(&"REDACTED".to_string())
.finish()
}
|
identifier_body
|
kms.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use crate::error::{Error, KmsError, Result};
use derive_more::Deref;
use kvproto::encryptionpb::MasterKeyKms;
#[derive(Debug, Clone)]
pub struct Location {
pub region: String,
pub endpoint: String,
}
#[derive(Debug, Clone)]
pub struct Config {
pub key_id: KeyId,
pub location: Location,
pub vendor: String,
}
impl Config {
pub fn from_proto(mk: MasterKeyKms) -> Result<Self> {
Ok(Config {
key_id: KeyId::new(mk.key_id)?,
location: Location {
region: mk.region,
endpoint: mk.endpoint,
},
vendor: mk.vendor,
})
}
}
#[derive(PartialEq, Debug, Clone, Deref)]
pub struct KeyId(String);
// KeyID is a newtype to mark a String as an ID of a key
// This ID exists in a foreign system such as AWS
// The key id must be non-empty
impl KeyId {
pub fn new(id: String) -> Result<KeyId> {
if id.is_empty() {
let msg = "KMS key id can not be empty";
Err(Error::KmsError(KmsError::EmptyKey(msg.to_owned())))
} else {
Ok(KeyId(id))
}
}
}
// EncryptedKey is a newtype used to mark data as an encrypted key
// It requires the vec to be non-empty
#[derive(PartialEq, Clone, Debug, Deref)]
pub struct EncryptedKey(Vec<u8>);
impl EncryptedKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
if key.is_empty()
|
else {
Ok(Self(key))
}
}
}
// PlainKey is a newtype used to mark a vector a plaintext key.
// It requires the vec to be a valid AesGcmCrypter key.
#[derive(Deref)]
pub struct PlainKey(Vec<u8>);
impl PlainKey {
pub fn new(key: Vec<u8>) -> Result<Self> {
// TODO: crypter.rs in encryption performs additional validation
Ok(Self(key))
}
}
// Don't expose the key in a debug print
impl std::fmt::Debug for PlainKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("PlainKey")
.field(&"REDACTED".to_string())
.finish()
}
}
#[derive(Debug)]
pub struct DataKeyPair {
pub encrypted: EncryptedKey,
pub plaintext: PlainKey,
}
#[async_trait]
pub trait KmsProvider: Sync + Send +'static + std::fmt::Debug {
async fn generate_data_key(&self) -> Result<DataKeyPair>;
async fn decrypt_data_key(&self, data_key: &EncryptedKey) -> Result<Vec<u8>>;
fn name(&self) -> &str;
}
|
{
Err(Error::KmsError(KmsError::EmptyKey(
"Encrypted Key".to_owned(),
)))
}
|
conditional_block
|
ws_server.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 url;
use self::url::Url;
use foxbox_core::traits::Controller;
use std::thread;
use ws;
use ws::{ Handler, Sender, Result, Message, Handshake, CloseCode, Error };
use ws::listen;
pub struct WsServer;
pub struct WsHandler<T> {
pub out: Sender,
pub controller: T
}
impl WsServer {
pub fn
|
<T: Controller>(controller: T) {
let addrs: Vec<_> = controller.ws_as_addrs().unwrap().collect();
thread::Builder::new().name("WsServer".to_owned()).spawn(move || {
listen(addrs[0], |out| {
WsHandler {
out: out,
controller: controller.clone(),
}
}).unwrap();
}).unwrap();
}
}
impl<T: Controller> WsHandler<T> {
fn close_with_error(&mut self, reason: &'static str) -> Result<()> {
self.out.close_with_reason(ws::CloseCode::Error, reason)
}
}
impl<T: Controller> Handler for WsHandler<T> {
fn on_open(&mut self, handshake: Handshake) -> Result<()> {
info!("Hello new ws connection");
let resource = &handshake.request.resource()[..];
// creating a fake url to get the path and query parsed
let url = match Url::parse(&format!("http://box.fox{}", resource)) {
Ok(val) => val,
_ => return self.close_with_error("Invalid path"),
};
let auth = match url.query_pairs() {
Some(pairs) => {
pairs.iter()
.find(|ref set| set.0.to_lowercase() == "auth")
.map(|ref set| set.1.clone())
},
_ => return self.close_with_error("Missing authorization"),
};
let token = match auth {
Some(val) => val,
_ => return self.close_with_error("Missing authorization"),
};
if let Err(_) = self.controller.get_users_manager().verify_token(&token) {
return self.close_with_error("Authorization failed");
}
self.controller.add_websocket(self.out.clone());
Ok(())
}
fn on_message(&mut self, msg: Message) -> Result<()> {
info!("Message from websocket ({:?}): {}", self.out.token(), msg);
Ok(())
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
match code {
CloseCode::Normal => info!("The ws client is done with the connection."),
CloseCode::Away => info!("The ws client is leaving the site."),
_ => error!("The ws client encountered an error: {}.", reason),
}
self.controller.remove_websocket(self.out.clone());
}
fn on_error(&mut self, err: Error) {
error!("The ws server encountered an error: {:?}", err);
}
}
|
start
|
identifier_name
|
ws_server.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 url;
use self::url::Url;
use foxbox_core::traits::Controller;
use std::thread;
use ws;
use ws::{ Handler, Sender, Result, Message, Handshake, CloseCode, Error };
use ws::listen;
pub struct WsServer;
pub struct WsHandler<T> {
pub out: Sender,
pub controller: T
}
impl WsServer {
pub fn start<T: Controller>(controller: T) {
let addrs: Vec<_> = controller.ws_as_addrs().unwrap().collect();
thread::Builder::new().name("WsServer".to_owned()).spawn(move || {
listen(addrs[0], |out| {
WsHandler {
out: out,
controller: controller.clone(),
}
}).unwrap();
}).unwrap();
}
}
impl<T: Controller> WsHandler<T> {
fn close_with_error(&mut self, reason: &'static str) -> Result<()> {
self.out.close_with_reason(ws::CloseCode::Error, reason)
}
}
impl<T: Controller> Handler for WsHandler<T> {
fn on_open(&mut self, handshake: Handshake) -> Result<()> {
info!("Hello new ws connection");
let resource = &handshake.request.resource()[..];
// creating a fake url to get the path and query parsed
let url = match Url::parse(&format!("http://box.fox{}", resource)) {
Ok(val) => val,
_ => return self.close_with_error("Invalid path"),
};
let auth = match url.query_pairs() {
Some(pairs) => {
pairs.iter()
.find(|ref set| set.0.to_lowercase() == "auth")
.map(|ref set| set.1.clone())
},
_ => return self.close_with_error("Missing authorization"),
};
let token = match auth {
Some(val) => val,
_ => return self.close_with_error("Missing authorization"),
};
if let Err(_) = self.controller.get_users_manager().verify_token(&token) {
return self.close_with_error("Authorization failed");
}
self.controller.add_websocket(self.out.clone());
Ok(())
}
fn on_message(&mut self, msg: Message) -> Result<()> {
info!("Message from websocket ({:?}): {}", self.out.token(), msg);
Ok(())
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
match code {
CloseCode::Normal => info!("The ws client is done with the connection."),
CloseCode::Away => info!("The ws client is leaving the site."),
_ => error!("The ws client encountered an error: {}.", reason),
}
self.controller.remove_websocket(self.out.clone());
}
fn on_error(&mut self, err: Error)
|
}
|
{
error!("The ws server encountered an error: {:?}", err);
}
|
identifier_body
|
ws_server.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 url;
use self::url::Url;
use foxbox_core::traits::Controller;
use std::thread;
use ws;
use ws::{ Handler, Sender, Result, Message, Handshake, CloseCode, Error };
use ws::listen;
pub struct WsServer;
pub struct WsHandler<T> {
pub out: Sender,
pub controller: T
}
impl WsServer {
pub fn start<T: Controller>(controller: T) {
let addrs: Vec<_> = controller.ws_as_addrs().unwrap().collect();
thread::Builder::new().name("WsServer".to_owned()).spawn(move || {
listen(addrs[0], |out| {
WsHandler {
out: out,
controller: controller.clone(),
}
}).unwrap();
}).unwrap();
}
}
impl<T: Controller> WsHandler<T> {
fn close_with_error(&mut self, reason: &'static str) -> Result<()> {
self.out.close_with_reason(ws::CloseCode::Error, reason)
}
}
impl<T: Controller> Handler for WsHandler<T> {
fn on_open(&mut self, handshake: Handshake) -> Result<()> {
info!("Hello new ws connection");
let resource = &handshake.request.resource()[..];
// creating a fake url to get the path and query parsed
let url = match Url::parse(&format!("http://box.fox{}", resource)) {
Ok(val) => val,
_ => return self.close_with_error("Invalid path"),
};
let auth = match url.query_pairs() {
Some(pairs) => {
pairs.iter()
.find(|ref set| set.0.to_lowercase() == "auth")
.map(|ref set| set.1.clone())
},
_ => return self.close_with_error("Missing authorization"),
};
let token = match auth {
Some(val) => val,
_ => return self.close_with_error("Missing authorization"),
};
if let Err(_) = self.controller.get_users_manager().verify_token(&token) {
return self.close_with_error("Authorization failed");
}
self.controller.add_websocket(self.out.clone());
|
}
fn on_message(&mut self, msg: Message) -> Result<()> {
info!("Message from websocket ({:?}): {}", self.out.token(), msg);
Ok(())
}
fn on_close(&mut self, code: CloseCode, reason: &str) {
match code {
CloseCode::Normal => info!("The ws client is done with the connection."),
CloseCode::Away => info!("The ws client is leaving the site."),
_ => error!("The ws client encountered an error: {}.", reason),
}
self.controller.remove_websocket(self.out.clone());
}
fn on_error(&mut self, err: Error) {
error!("The ws server encountered an error: {:?}", err);
}
}
|
Ok(())
|
random_line_split
|
inner_template_self.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct LinkedList {
pub next: *mut LinkedList,
pub prev: *mut LinkedList,
}
impl Default for LinkedList {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct InstantiateIt {
pub m_list: LinkedList,
}
#[test]
fn bindgen_test_layout_InstantiateIt() {
assert_eq!(
::std::mem::size_of::<InstantiateIt>(),
16usize,
concat!("Size of: ", stringify!(InstantiateIt))
);
assert_eq!(
::std::mem::align_of::<InstantiateIt>(),
8usize,
concat!("Alignment of ", stringify!(InstantiateIt))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<InstantiateIt>())).m_list as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(InstantiateIt),
"::",
stringify!(m_list)
)
);
}
impl Default for InstantiateIt {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[test]
fn __bindgen_test_layout_LinkedList_open0_int_close0_instantiation() {
assert_eq!(
|
concat!("Size of template specialization: ", stringify!(LinkedList))
);
assert_eq!(
::std::mem::align_of::<LinkedList>(),
8usize,
concat!(
"Alignment of template specialization: ",
stringify!(LinkedList)
)
);
}
|
::std::mem::size_of::<LinkedList>(),
16usize,
|
random_line_split
|
inner_template_self.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct
|
{
pub next: *mut LinkedList,
pub prev: *mut LinkedList,
}
impl Default for LinkedList {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct InstantiateIt {
pub m_list: LinkedList,
}
#[test]
fn bindgen_test_layout_InstantiateIt() {
assert_eq!(
::std::mem::size_of::<InstantiateIt>(),
16usize,
concat!("Size of: ", stringify!(InstantiateIt))
);
assert_eq!(
::std::mem::align_of::<InstantiateIt>(),
8usize,
concat!("Alignment of ", stringify!(InstantiateIt))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<InstantiateIt>())).m_list as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(InstantiateIt),
"::",
stringify!(m_list)
)
);
}
impl Default for InstantiateIt {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[test]
fn __bindgen_test_layout_LinkedList_open0_int_close0_instantiation() {
assert_eq!(
::std::mem::size_of::<LinkedList>(),
16usize,
concat!("Size of template specialization: ", stringify!(LinkedList))
);
assert_eq!(
::std::mem::align_of::<LinkedList>(),
8usize,
concat!(
"Alignment of template specialization: ",
stringify!(LinkedList)
)
);
}
|
LinkedList
|
identifier_name
|
inner_template_self.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct LinkedList {
pub next: *mut LinkedList,
pub prev: *mut LinkedList,
}
impl Default for LinkedList {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct InstantiateIt {
pub m_list: LinkedList,
}
#[test]
fn bindgen_test_layout_InstantiateIt()
|
"::",
stringify!(m_list)
)
);
}
impl Default for InstantiateIt {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[test]
fn __bindgen_test_layout_LinkedList_open0_int_close0_instantiation() {
assert_eq!(
::std::mem::size_of::<LinkedList>(),
16usize,
concat!("Size of template specialization: ", stringify!(LinkedList))
);
assert_eq!(
::std::mem::align_of::<LinkedList>(),
8usize,
concat!(
"Alignment of template specialization: ",
stringify!(LinkedList)
)
);
}
|
{
assert_eq!(
::std::mem::size_of::<InstantiateIt>(),
16usize,
concat!("Size of: ", stringify!(InstantiateIt))
);
assert_eq!(
::std::mem::align_of::<InstantiateIt>(),
8usize,
concat!("Alignment of ", stringify!(InstantiateIt))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<InstantiateIt>())).m_list as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(InstantiateIt),
|
identifier_body
|
lib.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.
*/
#![deny(clippy::all)]
mod client;
mod code_action;
pub mod completion;
pub mod diagnostic_reporter;
mod explore_schema_for_type;
pub mod goto_definition;
mod graphql_tools;
pub mod hover;
pub mod js_language_server;
pub mod location;
mod lsp_extra_data_provider;
pub mod lsp_process_error;
pub mod lsp_runtime_error;
pub mod node_resolution_info;
pub mod references;
pub mod resolution_path;
mod resolved_types_at_location;
mod search_schema_items;
mod server;
mod shutdown;
mod status_reporter;
pub mod status_updater;
pub mod text_documents;
pub mod utils;
use common::PerfLogger;
pub use extract_graphql::JavaScriptSourceFeature;
pub use hover::ContentConsumerType;
pub use js_language_server::JSLanguageServer;
use log::debug;
|
use lsp_server::Connection;
use relay_compiler::config::Config;
use schema_documentation::{SchemaDocumentation, SchemaDocumentationLoader};
pub use server::LSPNotificationDispatch;
pub use server::LSPRequestDispatch;
pub use server::{GlobalState, LSPState, Schemas};
use std::sync::Arc;
pub use utils::position_to_offset;
#[cfg(test)]
#[macro_use]
extern crate assert_matches;
pub async fn start_language_server<
TPerfLogger,
TSchemaDocumentation: SchemaDocumentation +'static,
>(
config: Config,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
schema_documentation_loader: Option<Box<dyn SchemaDocumentationLoader<TSchemaDocumentation>>>,
js_language_server: Option<
Box<dyn JSLanguageServer<TState = LSPState<TPerfLogger, TSchemaDocumentation>>>,
>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
let (connection, io_handles) = Connection::stdio();
debug!("Initialized stdio transport layer");
let params = server::initialize(&connection)?;
debug!("JSON-RPC handshake completed");
server::run(
connection,
config,
params,
perf_logger,
extra_data_provider,
schema_documentation_loader,
js_language_server,
)
.await?;
io_handles.join()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::client;
use super::lsp_process_error::LSPProcessResult;
use super::server;
use lsp_server::Connection;
use lsp_types::{ClientCapabilities, InitializeParams};
#[test]
fn initialize() -> LSPProcessResult<()> {
// Test with an in-memory connection pair
let (connection, client) = Connection::memory();
// Mock set of client parameters. The `root_path` field is deprecated, but
// still required to construct the params, so we allow deprecated fields here.
#[allow(deprecated)]
let init_params = InitializeParams {
process_id: Some(1),
root_path: None,
root_uri: None,
initialization_options: None,
capabilities: ClientCapabilities::default(),
trace: None,
workspace_folders: None,
client_info: None,
locale: None,
};
client::initialize(&client, &init_params, 0);
let params = server::initialize(&connection)?;
assert_eq!(params, init_params);
Ok(())
}
}
|
pub use lsp_extra_data_provider::{
FieldDefinitionSourceInfo, FieldSchemaInfo, LSPExtraDataProvider,
};
use lsp_process_error::LSPProcessResult;
pub use lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
|
random_line_split
|
lib.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.
*/
#![deny(clippy::all)]
mod client;
mod code_action;
pub mod completion;
pub mod diagnostic_reporter;
mod explore_schema_for_type;
pub mod goto_definition;
mod graphql_tools;
pub mod hover;
pub mod js_language_server;
pub mod location;
mod lsp_extra_data_provider;
pub mod lsp_process_error;
pub mod lsp_runtime_error;
pub mod node_resolution_info;
pub mod references;
pub mod resolution_path;
mod resolved_types_at_location;
mod search_schema_items;
mod server;
mod shutdown;
mod status_reporter;
pub mod status_updater;
pub mod text_documents;
pub mod utils;
use common::PerfLogger;
pub use extract_graphql::JavaScriptSourceFeature;
pub use hover::ContentConsumerType;
pub use js_language_server::JSLanguageServer;
use log::debug;
pub use lsp_extra_data_provider::{
FieldDefinitionSourceInfo, FieldSchemaInfo, LSPExtraDataProvider,
};
use lsp_process_error::LSPProcessResult;
pub use lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
use lsp_server::Connection;
use relay_compiler::config::Config;
use schema_documentation::{SchemaDocumentation, SchemaDocumentationLoader};
pub use server::LSPNotificationDispatch;
pub use server::LSPRequestDispatch;
pub use server::{GlobalState, LSPState, Schemas};
use std::sync::Arc;
pub use utils::position_to_offset;
#[cfg(test)]
#[macro_use]
extern crate assert_matches;
pub async fn
|
<
TPerfLogger,
TSchemaDocumentation: SchemaDocumentation +'static,
>(
config: Config,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
schema_documentation_loader: Option<Box<dyn SchemaDocumentationLoader<TSchemaDocumentation>>>,
js_language_server: Option<
Box<dyn JSLanguageServer<TState = LSPState<TPerfLogger, TSchemaDocumentation>>>,
>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
let (connection, io_handles) = Connection::stdio();
debug!("Initialized stdio transport layer");
let params = server::initialize(&connection)?;
debug!("JSON-RPC handshake completed");
server::run(
connection,
config,
params,
perf_logger,
extra_data_provider,
schema_documentation_loader,
js_language_server,
)
.await?;
io_handles.join()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::client;
use super::lsp_process_error::LSPProcessResult;
use super::server;
use lsp_server::Connection;
use lsp_types::{ClientCapabilities, InitializeParams};
#[test]
fn initialize() -> LSPProcessResult<()> {
// Test with an in-memory connection pair
let (connection, client) = Connection::memory();
// Mock set of client parameters. The `root_path` field is deprecated, but
// still required to construct the params, so we allow deprecated fields here.
#[allow(deprecated)]
let init_params = InitializeParams {
process_id: Some(1),
root_path: None,
root_uri: None,
initialization_options: None,
capabilities: ClientCapabilities::default(),
trace: None,
workspace_folders: None,
client_info: None,
locale: None,
};
client::initialize(&client, &init_params, 0);
let params = server::initialize(&connection)?;
assert_eq!(params, init_params);
Ok(())
}
}
|
start_language_server
|
identifier_name
|
lib.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.
*/
#![deny(clippy::all)]
mod client;
mod code_action;
pub mod completion;
pub mod diagnostic_reporter;
mod explore_schema_for_type;
pub mod goto_definition;
mod graphql_tools;
pub mod hover;
pub mod js_language_server;
pub mod location;
mod lsp_extra_data_provider;
pub mod lsp_process_error;
pub mod lsp_runtime_error;
pub mod node_resolution_info;
pub mod references;
pub mod resolution_path;
mod resolved_types_at_location;
mod search_schema_items;
mod server;
mod shutdown;
mod status_reporter;
pub mod status_updater;
pub mod text_documents;
pub mod utils;
use common::PerfLogger;
pub use extract_graphql::JavaScriptSourceFeature;
pub use hover::ContentConsumerType;
pub use js_language_server::JSLanguageServer;
use log::debug;
pub use lsp_extra_data_provider::{
FieldDefinitionSourceInfo, FieldSchemaInfo, LSPExtraDataProvider,
};
use lsp_process_error::LSPProcessResult;
pub use lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult};
use lsp_server::Connection;
use relay_compiler::config::Config;
use schema_documentation::{SchemaDocumentation, SchemaDocumentationLoader};
pub use server::LSPNotificationDispatch;
pub use server::LSPRequestDispatch;
pub use server::{GlobalState, LSPState, Schemas};
use std::sync::Arc;
pub use utils::position_to_offset;
#[cfg(test)]
#[macro_use]
extern crate assert_matches;
pub async fn start_language_server<
TPerfLogger,
TSchemaDocumentation: SchemaDocumentation +'static,
>(
config: Config,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
schema_documentation_loader: Option<Box<dyn SchemaDocumentationLoader<TSchemaDocumentation>>>,
js_language_server: Option<
Box<dyn JSLanguageServer<TState = LSPState<TPerfLogger, TSchemaDocumentation>>>,
>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
let (connection, io_handles) = Connection::stdio();
debug!("Initialized stdio transport layer");
let params = server::initialize(&connection)?;
debug!("JSON-RPC handshake completed");
server::run(
connection,
config,
params,
perf_logger,
extra_data_provider,
schema_documentation_loader,
js_language_server,
)
.await?;
io_handles.join()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::client;
use super::lsp_process_error::LSPProcessResult;
use super::server;
use lsp_server::Connection;
use lsp_types::{ClientCapabilities, InitializeParams};
#[test]
fn initialize() -> LSPProcessResult<()>
|
Ok(())
}
}
|
{
// Test with an in-memory connection pair
let (connection, client) = Connection::memory();
// Mock set of client parameters. The `root_path` field is deprecated, but
// still required to construct the params, so we allow deprecated fields here.
#[allow(deprecated)]
let init_params = InitializeParams {
process_id: Some(1),
root_path: None,
root_uri: None,
initialization_options: None,
capabilities: ClientCapabilities::default(),
trace: None,
workspace_folders: None,
client_info: None,
locale: None,
};
client::initialize(&client, &init_params, 0);
let params = server::initialize(&connection)?;
assert_eq!(params, init_params);
|
identifier_body
|
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
}
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool
|
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction, None);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r()!= Some(self))
}
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
|
{
true // Always returns true
}
|
identifier_body
|
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
}
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn
|
(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction, None);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r()!= Some(self))
}
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
|
GetNamespaceURI
|
identifier_name
|
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
}
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
|
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction, None);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r()!= Some(self))
}
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
|
random_line_split
|
|
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element};
use dom::mutationobserver::{Mutation, MutationObserver};
use dom::node::Node;
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use dom_struct::dom_struct;
use html5ever::{Prefix, LocalName, Namespace};
use script_thread::ScriptThread;
use servo_atoms::Atom;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use style::attr::{AttrIdentifier, AttrValue};
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>,
/// the element that owns this attribute.
owner: MutNullableJS<Element>,
}
impl Attr {
fn new_inherited(local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Attr {
Attr {
reflector_: Reflector::new(),
identifier: AttrIdentifier {
local_name: local_name,
name: name,
namespace: namespace,
prefix: prefix,
},
value: DOMRefCell::new(value),
owner: MutNullableJS::new(owner),
}
}
pub fn new(window: &Window,
local_name: LocalName,
value: AttrValue,
name: LocalName,
namespace: Namespace,
prefix: Option<Prefix>,
owner: Option<&Element>)
-> Root<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name,
value,
name,
namespace,
prefix,
owner),
window,
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &LocalName {
&self.identifier.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.identifier.namespace
}
#[inline]
pub fn prefix(&self) -> Option<&Prefix> {
self.identifier.prefix.as_ref()
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&**self.local_name())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from AttrValue to DOMString
DOMString::from(&**self.value())
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
if let Some(owner) = self.owner() {
let value = owner.parse_attribute(&self.identifier.namespace,
self.local_name(),
value);
self.set_value(value, &owner);
} else {
*self.value.borrow_mut() = AttrValue::String(value.into());
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
DOMString::from(&*self.identifier.name)
}
// https://dom.spec.whatwg.org/#dom-attr-nodename
fn NodeName(&self) -> DOMString {
self.Name()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
match self.identifier.namespace {
ns!() => None,
ref url => Some(DOMString::from(&**url)),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
// FIXME(ajeffrey): convert directly from LocalName to DOMString
self.prefix().map(|p| DOMString::from(&**p))
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
let name = self.local_name().clone();
let namespace = self.namespace().clone();
let old_value = DOMString::from(&**self.value());
let new_value = DOMString::from(&*value);
let mutation = Mutation::Attribute {
name: name.clone(),
namespace: namespace.clone(),
old_value: old_value.clone(),
};
MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation);
if owner.get_custom_element_definition().is_some() {
let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace);
ScriptThread::enqueue_callback_reaction(owner, reaction, None);
}
assert!(Some(owner) == self.owner().r());
owner.will_mutate_attr(self);
self.swap_value(&mut value);
if self.identifier.namespace == ns!() {
vtable_for(owner.upcast())
.attribute_mutated(self, AttributeMutation::Set(Some(&value)));
}
}
/// Used to swap the attribute's value without triggering mutation events
pub fn swap_value(&self, value: &mut AttrValue) {
mem::swap(&mut *self.value.borrow_mut(), value);
}
pub fn identifier(&self) -> &AttrIdentifier {
&self.identifier
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &LocalName {
&self.identifier.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ns = &self.identifier.namespace;
match (self.owner(), owner) {
(Some(old), None) =>
|
(Some(old), Some(new)) => assert!(&*old == new),
_ => {},
}
self.owner.set(owner);
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get()
}
pub fn summarize(&self) -> AttrInfo {
AttrInfo {
namespace: (*self.identifier.namespace).to_owned(),
name: String::from(self.Name()),
value: String::from(self.Value()),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> LocalName;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> LocalName {
(*self.unsafe_get()).identifier.local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
|
{
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.identifier.local_name).r() != Some(self))
}
|
conditional_block
|
stack.rs
|
// http://rosettacode.org/wiki/Stack
#[derive(Debug)]
struct Stack<T> {
/// We use a vector because of simplicity
vec: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Stack<T> {
Stack { vec: Vec::new() }
}
/// Adds an element at the top of the stack
fn push(&mut self, elem: T) {
self.vec.push(elem);
}
/// Removes and returns the element at the top of the stack
fn pop(&mut self) -> Option<T> {
self.vec.pop()
}
/// Returns a reference of the element at the top of the stack
fn peek(&self) -> Option<&T> {
self.vec.last()
}
/// Returns true if the stack is empty
fn empty(&self) -> bool {
self.vec.is_empty()
}
}
fn main() {
let mut stack = Stack::new();
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// Show the element at the top
println!("{}", stack.peek().unwrap());
// Show the element we popped
println!("{}", stack.pop().unwrap());
if stack.empty() {
println!("The stack is empty.")
} else {
println!("The stack is not empty.")
}
}
#[test]
fn test_basic()
|
// The element at the top is now 8
assert!(stack.peek().unwrap() == &8);
}
|
{
let mut stack = Stack::new();
// The stack is empty
assert!(stack.empty());
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// The stack is not empty
assert!(!stack.empty());
// The element at the top is 9
assert!(stack.peek().unwrap() == &9);
// Remove one element
stack.pop();
|
identifier_body
|
stack.rs
|
// http://rosettacode.org/wiki/Stack
#[derive(Debug)]
struct Stack<T> {
/// We use a vector because of simplicity
vec: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Stack<T> {
Stack { vec: Vec::new() }
}
/// Adds an element at the top of the stack
fn push(&mut self, elem: T) {
self.vec.push(elem);
}
/// Removes and returns the element at the top of the stack
fn pop(&mut self) -> Option<T> {
self.vec.pop()
}
/// Returns a reference of the element at the top of the stack
fn peek(&self) -> Option<&T> {
self.vec.last()
}
/// Returns true if the stack is empty
fn empty(&self) -> bool {
self.vec.is_empty()
}
}
fn main() {
let mut stack = Stack::new();
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// Show the element at the top
println!("{}", stack.peek().unwrap());
// Show the element we popped
println!("{}", stack.pop().unwrap());
if stack.empty() {
println!("The stack is empty.")
} else {
println!("The stack is not empty.")
}
}
#[test]
fn test_basic() {
let mut stack = Stack::new();
// The stack is empty
assert!(stack.empty());
// Fill the stack
stack.push(5i32);
stack.push(8);
|
// The stack is not empty
assert!(!stack.empty());
// The element at the top is 9
assert!(stack.peek().unwrap() == &9);
// Remove one element
stack.pop();
// The element at the top is now 8
assert!(stack.peek().unwrap() == &8);
}
|
stack.push(9);
|
random_line_split
|
stack.rs
|
// http://rosettacode.org/wiki/Stack
#[derive(Debug)]
struct Stack<T> {
/// We use a vector because of simplicity
vec: Vec<T>,
}
impl<T> Stack<T> {
fn new() -> Stack<T> {
Stack { vec: Vec::new() }
}
/// Adds an element at the top of the stack
fn push(&mut self, elem: T) {
self.vec.push(elem);
}
/// Removes and returns the element at the top of the stack
fn pop(&mut self) -> Option<T> {
self.vec.pop()
}
/// Returns a reference of the element at the top of the stack
fn peek(&self) -> Option<&T> {
self.vec.last()
}
/// Returns true if the stack is empty
fn empty(&self) -> bool {
self.vec.is_empty()
}
}
fn main() {
let mut stack = Stack::new();
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// Show the element at the top
println!("{}", stack.peek().unwrap());
// Show the element we popped
println!("{}", stack.pop().unwrap());
if stack.empty()
|
else {
println!("The stack is not empty.")
}
}
#[test]
fn test_basic() {
let mut stack = Stack::new();
// The stack is empty
assert!(stack.empty());
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// The stack is not empty
assert!(!stack.empty());
// The element at the top is 9
assert!(stack.peek().unwrap() == &9);
// Remove one element
stack.pop();
// The element at the top is now 8
assert!(stack.peek().unwrap() == &8);
}
|
{
println!("The stack is empty.")
}
|
conditional_block
|
stack.rs
|
// http://rosettacode.org/wiki/Stack
#[derive(Debug)]
struct Stack<T> {
/// We use a vector because of simplicity
vec: Vec<T>,
}
impl<T> Stack<T> {
fn
|
() -> Stack<T> {
Stack { vec: Vec::new() }
}
/// Adds an element at the top of the stack
fn push(&mut self, elem: T) {
self.vec.push(elem);
}
/// Removes and returns the element at the top of the stack
fn pop(&mut self) -> Option<T> {
self.vec.pop()
}
/// Returns a reference of the element at the top of the stack
fn peek(&self) -> Option<&T> {
self.vec.last()
}
/// Returns true if the stack is empty
fn empty(&self) -> bool {
self.vec.is_empty()
}
}
fn main() {
let mut stack = Stack::new();
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// Show the element at the top
println!("{}", stack.peek().unwrap());
// Show the element we popped
println!("{}", stack.pop().unwrap());
if stack.empty() {
println!("The stack is empty.")
} else {
println!("The stack is not empty.")
}
}
#[test]
fn test_basic() {
let mut stack = Stack::new();
// The stack is empty
assert!(stack.empty());
// Fill the stack
stack.push(5i32);
stack.push(8);
stack.push(9);
// The stack is not empty
assert!(!stack.empty());
// The element at the top is 9
assert!(stack.peek().unwrap() == &9);
// Remove one element
stack.pop();
// The element at the top is now 8
assert!(stack.peek().unwrap() == &8);
}
|
new
|
identifier_name
|
xmlerror.rs
|
use xmlutil::{XmlParseError, Peek, Next};
use xmlutil::{characters, start_element, end_element, string_field, peek_at_name};
#[derive(Default, Debug)]
pub struct XmlError {
pub error_type: String,
pub code: String,
pub message: String,
pub detail: Option<String>,
}
pub struct XmlErrorDeserializer;
impl XmlErrorDeserializer {
pub fn deserialize<T: Peek + Next>(tag_name: &str,
stack: &mut T)
-> Result<XmlError, XmlParseError> {
try!(start_element(tag_name, stack));
let mut obj = XmlError::default();
loop {
match &try!(peek_at_name(stack))[..] {
"Type" => {
obj.error_type = try!(string_field("Type", stack));
continue;
}
"Code" => {
obj.code = try!(string_field("Code", stack));
|
continue;
}
"Detail" => {
try!(start_element("Detail", stack));
if let Ok(characters) = characters(stack) {
obj.detail = Some(characters.to_string());
try!(end_element("Detail", stack));
}
continue;
}
_ => break,
}
}
try!(end_element(tag_name, stack));
Ok(obj)
}
}
|
continue;
}
"Message" => {
obj.message = try!(string_field("Message", stack));
|
random_line_split
|
xmlerror.rs
|
use xmlutil::{XmlParseError, Peek, Next};
use xmlutil::{characters, start_element, end_element, string_field, peek_at_name};
#[derive(Default, Debug)]
pub struct XmlError {
pub error_type: String,
pub code: String,
pub message: String,
pub detail: Option<String>,
}
pub struct XmlErrorDeserializer;
impl XmlErrorDeserializer {
pub fn deserialize<T: Peek + Next>(tag_name: &str,
stack: &mut T)
-> Result<XmlError, XmlParseError> {
try!(start_element(tag_name, stack));
let mut obj = XmlError::default();
loop {
match &try!(peek_at_name(stack))[..] {
"Type" => {
obj.error_type = try!(string_field("Type", stack));
continue;
}
"Code" => {
obj.code = try!(string_field("Code", stack));
continue;
}
"Message" => {
obj.message = try!(string_field("Message", stack));
continue;
}
"Detail" =>
|
_ => break,
}
}
try!(end_element(tag_name, stack));
Ok(obj)
}
}
|
{
try!(start_element("Detail", stack));
if let Ok(characters) = characters(stack) {
obj.detail = Some(characters.to_string());
try!(end_element("Detail", stack));
}
continue;
}
|
conditional_block
|
xmlerror.rs
|
use xmlutil::{XmlParseError, Peek, Next};
use xmlutil::{characters, start_element, end_element, string_field, peek_at_name};
#[derive(Default, Debug)]
pub struct XmlError {
pub error_type: String,
pub code: String,
pub message: String,
pub detail: Option<String>,
}
pub struct
|
;
impl XmlErrorDeserializer {
pub fn deserialize<T: Peek + Next>(tag_name: &str,
stack: &mut T)
-> Result<XmlError, XmlParseError> {
try!(start_element(tag_name, stack));
let mut obj = XmlError::default();
loop {
match &try!(peek_at_name(stack))[..] {
"Type" => {
obj.error_type = try!(string_field("Type", stack));
continue;
}
"Code" => {
obj.code = try!(string_field("Code", stack));
continue;
}
"Message" => {
obj.message = try!(string_field("Message", stack));
continue;
}
"Detail" => {
try!(start_element("Detail", stack));
if let Ok(characters) = characters(stack) {
obj.detail = Some(characters.to_string());
try!(end_element("Detail", stack));
}
continue;
}
_ => break,
}
}
try!(end_element(tag_name, stack));
Ok(obj)
}
}
|
XmlErrorDeserializer
|
identifier_name
|
generation.rs
|
use std::sync::Arc;
use cge::{Network, Activation};
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// Creates a generation of random, minimal neural networks
pub fn initialize_generation<T>(population_size: usize,
offspring_count: usize,
inputs: usize,
outputs: usize,
activation: Activation,
object: Arc<T>) -> Vec<Individual<T>>
where T: NNFitnessFunction + Clone
|
}
// Make sure all inputs are connected
for individual in &mut generation {
let range = Range::new(0, outputs);
for i in 0..inputs {
if individual.get_input_copies(i) == 0 {
let id = range.ind_sample(&mut rng);
let index = individual.network.get_neuron_index(id).unwrap() + 1;
individual.add_input(i, index);
}
}
}
generation
}
|
{
let mut rng = thread_rng();
let mut generation = Vec::new();
for _ in 0..population_size * (offspring_count + 1) {
let mut network = Network {
size: 0,
genome: Vec::new(),
function: activation.clone(),
};
for i in (0..outputs).rev() {
network.add_subnetwork(i, 0, inputs)
}
network.size = network.genome.len() - 1;
generation.push(Individual::new(inputs, outputs, network, object.clone()));
|
identifier_body
|
generation.rs
|
use std::sync::Arc;
use cge::{Network, Activation};
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// Creates a generation of random, minimal neural networks
pub fn
|
<T>(population_size: usize,
offspring_count: usize,
inputs: usize,
outputs: usize,
activation: Activation,
object: Arc<T>) -> Vec<Individual<T>>
where T: NNFitnessFunction + Clone
{
let mut rng = thread_rng();
let mut generation = Vec::new();
for _ in 0..population_size * (offspring_count + 1) {
let mut network = Network {
size: 0,
genome: Vec::new(),
function: activation.clone(),
};
for i in (0..outputs).rev() {
network.add_subnetwork(i, 0, inputs)
}
network.size = network.genome.len() - 1;
generation.push(Individual::new(inputs, outputs, network, object.clone()));
}
// Make sure all inputs are connected
for individual in &mut generation {
let range = Range::new(0, outputs);
for i in 0..inputs {
if individual.get_input_copies(i) == 0 {
let id = range.ind_sample(&mut rng);
let index = individual.network.get_neuron_index(id).unwrap() + 1;
individual.add_input(i, index);
}
}
}
generation
}
|
initialize_generation
|
identifier_name
|
generation.rs
|
use std::sync::Arc;
use cge::{Network, Activation};
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// Creates a generation of random, minimal neural networks
pub fn initialize_generation<T>(population_size: usize,
offspring_count: usize,
inputs: usize,
outputs: usize,
activation: Activation,
object: Arc<T>) -> Vec<Individual<T>>
where T: NNFitnessFunction + Clone
{
let mut rng = thread_rng();
let mut generation = Vec::new();
for _ in 0..population_size * (offspring_count + 1) {
let mut network = Network {
size: 0,
genome: Vec::new(),
function: activation.clone(),
};
for i in (0..outputs).rev() {
network.add_subnetwork(i, 0, inputs)
}
network.size = network.genome.len() - 1;
generation.push(Individual::new(inputs, outputs, network, object.clone()));
}
// Make sure all inputs are connected
for individual in &mut generation {
let range = Range::new(0, outputs);
for i in 0..inputs {
|
individual.add_input(i, index);
}
}
}
generation
}
|
if individual.get_input_copies(i) == 0 {
let id = range.ind_sample(&mut rng);
let index = individual.network.get_neuron_index(id).unwrap() + 1;
|
random_line_split
|
generation.rs
|
use std::sync::Arc;
use cge::{Network, Activation};
use rand::thread_rng;
use rand::distributions::{IndependentSample, Range};
use crate::utils::Individual;
use crate::cge_utils::Mutation;
use crate::NNFitnessFunction;
// Creates a generation of random, minimal neural networks
pub fn initialize_generation<T>(population_size: usize,
offspring_count: usize,
inputs: usize,
outputs: usize,
activation: Activation,
object: Arc<T>) -> Vec<Individual<T>>
where T: NNFitnessFunction + Clone
{
let mut rng = thread_rng();
let mut generation = Vec::new();
for _ in 0..population_size * (offspring_count + 1) {
let mut network = Network {
size: 0,
genome: Vec::new(),
function: activation.clone(),
};
for i in (0..outputs).rev() {
network.add_subnetwork(i, 0, inputs)
}
network.size = network.genome.len() - 1;
generation.push(Individual::new(inputs, outputs, network, object.clone()));
}
// Make sure all inputs are connected
for individual in &mut generation {
let range = Range::new(0, outputs);
for i in 0..inputs {
if individual.get_input_copies(i) == 0
|
}
}
generation
}
|
{
let id = range.ind_sample(&mut rng);
let index = individual.network.get_neuron_index(id).unwrap() + 1;
individual.add_input(i, index);
}
|
conditional_block
|
check_static.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.
// Verifies that the types and values of static items
// are safe. The rules enforced by this module are:
//
// - For each *mutable* static item, it checks that its **type**:
// - doesn't have a destructor
// - doesn't own an owned pointer
//
// - For each *immutable* static item, it checks that its **value**:
// - doesn't own owned, managed pointers
// - doesn't contain a struct literal or a call to an enum variant / struct constructor where
// - the type of the struct/enum has a dtor
//
// Rules Enforced Elsewhere:
// - It's not possible to take the address of a static item with unsafe interior. This is enforced
// by borrowck::gather_loans
use middle::ty;
use syntax::ast;
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
use syntax::print::pprust;
fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
let node_ty = ty::node_id_to_type(cx, e.id);
let tcontents = ty::type_contents(cx, node_ty);
debug!("safe_type_for_static_mut(dtor={}, managed={}, owned={})",
tcontents.has_dtor(), tcontents.owns_managed(), tcontents.owns_owned())
let suffix = if tcontents.has_dtor() {
"destructors"
} else if tcontents.owns_managed() {
"managed pointers"
} else if tcontents.owns_owned() {
"owned pointers"
} else {
return None;
};
Some(format!("mutable static items are not allowed to have {}", suffix))
}
struct CheckStaticVisitor<'a> {
tcx: &'a ty::ctxt,
}
pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate) {
visit::walk_crate(&mut CheckStaticVisitor { tcx: tcx }, krate, false)
}
impl<'a> CheckStaticVisitor<'a> {
fn report_error(&self, span: Span, result: Option<String>) -> bool {
match result {
None => { false }
Some(msg) => {
self.tcx.sess.span_err(span, msg.as_slice());
true
}
}
}
}
impl<'a> Visitor<bool> for CheckStaticVisitor<'a> {
fn visit_item(&mut self, i: &ast::Item, _is_const: bool) {
debug!("visit_item(item={})", pprust::item_to_string(i));
match i.node {
ast::ItemStatic(_, mutability, ref expr) =>
|
_ => { visit::walk_item(self, i, false) }
}
}
/// This method is used to enforce the constraints on
/// immutable static items. It walks through the *value*
/// of the item walking down the expression and evaluating
/// every nested expression. if the expression is not part
/// of a static item, this method does nothing but walking
/// down through it.
fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) {
debug!("visit_expr(expr={})", pprust::expr_to_string(e));
if!is_const {
return visit::walk_expr(self, e, is_const);
}
match e.node {
ast::ExprField(..) | ast::ExprVec(..) |
ast::ExprBlock(..) | ast::ExprTup(..) => {
visit::walk_expr(self, e, is_const);
}
ast::ExprAddrOf(ast::MutMutable, _) => {
span_err!(self.tcx.sess, e.span, E0020,
"static items are not allowed to have mutable slices");
},
ast::ExprUnary(ast::UnBox, _) => {
span_err!(self.tcx.sess, e.span, E0021,
"static items are not allowed to have managed pointers");
}
ast::ExprBox(..) |
ast::ExprUnary(ast::UnUniq, _) => {
span_err!(self.tcx.sess, e.span, E0022,
"static items are not allowed to have custom pointers");
}
_ => {
let node_ty = ty::node_id_to_type(self.tcx, e.id);
match ty::get(node_ty).sty {
ty::ty_struct(did, _) |
ty::ty_enum(did, _) => {
if ty::has_dtor(self.tcx, did) {
self.report_error(e.span,
Some("static items are not allowed to have \
destructors".to_string()));
return;
}
}
_ => {}
}
visit::walk_expr(self, e, is_const);
}
}
}
}
|
{
match mutability {
ast::MutImmutable => {
self.visit_expr(&**expr, true);
}
ast::MutMutable => {
let safe = safe_type_for_static_mut(self.tcx, &**expr);
self.report_error(expr.span, safe);
}
}
}
|
conditional_block
|
check_static.rs
|
// Copyright 2014 The Rust Project Developers. See the 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.
// Verifies that the types and values of static items
// are safe. The rules enforced by this module are:
//
// - For each *mutable* static item, it checks that its **type**:
// - doesn't have a destructor
// - doesn't own an owned pointer
//
// - For each *immutable* static item, it checks that its **value**:
// - doesn't own owned, managed pointers
// - doesn't contain a struct literal or a call to an enum variant / struct constructor where
// - the type of the struct/enum has a dtor
//
// Rules Enforced Elsewhere:
// - It's not possible to take the address of a static item with unsafe interior. This is enforced
// by borrowck::gather_loans
use middle::ty;
use syntax::ast;
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
use syntax::print::pprust;
fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
let node_ty = ty::node_id_to_type(cx, e.id);
let tcontents = ty::type_contents(cx, node_ty);
debug!("safe_type_for_static_mut(dtor={}, managed={}, owned={})",
tcontents.has_dtor(), tcontents.owns_managed(), tcontents.owns_owned())
let suffix = if tcontents.has_dtor() {
"destructors"
} else if tcontents.owns_managed() {
"managed pointers"
} else if tcontents.owns_owned() {
"owned pointers"
} else {
return None;
};
Some(format!("mutable static items are not allowed to have {}", suffix))
}
struct CheckStaticVisitor<'a> {
tcx: &'a ty::ctxt,
}
pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate) {
visit::walk_crate(&mut CheckStaticVisitor { tcx: tcx }, krate, false)
}
impl<'a> CheckStaticVisitor<'a> {
fn report_error(&self, span: Span, result: Option<String>) -> bool {
match result {
None => { false }
Some(msg) => {
self.tcx.sess.span_err(span, msg.as_slice());
true
}
}
}
}
impl<'a> Visitor<bool> for CheckStaticVisitor<'a> {
fn visit_item(&mut self, i: &ast::Item, _is_const: bool) {
debug!("visit_item(item={})", pprust::item_to_string(i));
match i.node {
ast::ItemStatic(_, mutability, ref expr) => {
match mutability {
ast::MutImmutable => {
self.visit_expr(&**expr, true);
}
ast::MutMutable => {
let safe = safe_type_for_static_mut(self.tcx, &**expr);
self.report_error(expr.span, safe);
}
}
}
_ => { visit::walk_item(self, i, false) }
}
}
/// This method is used to enforce the constraints on
/// immutable static items. It walks through the *value*
/// of the item walking down the expression and evaluating
/// every nested expression. if the expression is not part
/// of a static item, this method does nothing but walking
/// down through it.
fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) {
debug!("visit_expr(expr={})", pprust::expr_to_string(e));
if!is_const {
return visit::walk_expr(self, e, is_const);
}
match e.node {
ast::ExprField(..) | ast::ExprVec(..) |
ast::ExprBlock(..) | ast::ExprTup(..) => {
visit::walk_expr(self, e, is_const);
}
ast::ExprAddrOf(ast::MutMutable, _) => {
span_err!(self.tcx.sess, e.span, E0020,
"static items are not allowed to have mutable slices");
},
ast::ExprUnary(ast::UnBox, _) => {
span_err!(self.tcx.sess, e.span, E0021,
"static items are not allowed to have managed pointers");
}
ast::ExprBox(..) |
ast::ExprUnary(ast::UnUniq, _) => {
span_err!(self.tcx.sess, e.span, E0022,
"static items are not allowed to have custom pointers");
}
_ => {
let node_ty = ty::node_id_to_type(self.tcx, e.id);
match ty::get(node_ty).sty {
ty::ty_struct(did, _) |
ty::ty_enum(did, _) => {
if ty::has_dtor(self.tcx, did) {
self.report_error(e.span,
Some("static items are not allowed to have \
destructors".to_string()));
return;
}
}
_ => {}
}
visit::walk_expr(self, e, is_const);
}
}
}
}
|
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
|
random_line_split
|
check_static.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.
// Verifies that the types and values of static items
// are safe. The rules enforced by this module are:
//
// - For each *mutable* static item, it checks that its **type**:
// - doesn't have a destructor
// - doesn't own an owned pointer
//
// - For each *immutable* static item, it checks that its **value**:
// - doesn't own owned, managed pointers
// - doesn't contain a struct literal or a call to an enum variant / struct constructor where
// - the type of the struct/enum has a dtor
//
// Rules Enforced Elsewhere:
// - It's not possible to take the address of a static item with unsafe interior. This is enforced
// by borrowck::gather_loans
use middle::ty;
use syntax::ast;
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
use syntax::print::pprust;
fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
let node_ty = ty::node_id_to_type(cx, e.id);
let tcontents = ty::type_contents(cx, node_ty);
debug!("safe_type_for_static_mut(dtor={}, managed={}, owned={})",
tcontents.has_dtor(), tcontents.owns_managed(), tcontents.owns_owned())
let suffix = if tcontents.has_dtor() {
"destructors"
} else if tcontents.owns_managed() {
"managed pointers"
} else if tcontents.owns_owned() {
"owned pointers"
} else {
return None;
};
Some(format!("mutable static items are not allowed to have {}", suffix))
}
struct CheckStaticVisitor<'a> {
tcx: &'a ty::ctxt,
}
pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate)
|
impl<'a> CheckStaticVisitor<'a> {
fn report_error(&self, span: Span, result: Option<String>) -> bool {
match result {
None => { false }
Some(msg) => {
self.tcx.sess.span_err(span, msg.as_slice());
true
}
}
}
}
impl<'a> Visitor<bool> for CheckStaticVisitor<'a> {
fn visit_item(&mut self, i: &ast::Item, _is_const: bool) {
debug!("visit_item(item={})", pprust::item_to_string(i));
match i.node {
ast::ItemStatic(_, mutability, ref expr) => {
match mutability {
ast::MutImmutable => {
self.visit_expr(&**expr, true);
}
ast::MutMutable => {
let safe = safe_type_for_static_mut(self.tcx, &**expr);
self.report_error(expr.span, safe);
}
}
}
_ => { visit::walk_item(self, i, false) }
}
}
/// This method is used to enforce the constraints on
/// immutable static items. It walks through the *value*
/// of the item walking down the expression and evaluating
/// every nested expression. if the expression is not part
/// of a static item, this method does nothing but walking
/// down through it.
fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) {
debug!("visit_expr(expr={})", pprust::expr_to_string(e));
if!is_const {
return visit::walk_expr(self, e, is_const);
}
match e.node {
ast::ExprField(..) | ast::ExprVec(..) |
ast::ExprBlock(..) | ast::ExprTup(..) => {
visit::walk_expr(self, e, is_const);
}
ast::ExprAddrOf(ast::MutMutable, _) => {
span_err!(self.tcx.sess, e.span, E0020,
"static items are not allowed to have mutable slices");
},
ast::ExprUnary(ast::UnBox, _) => {
span_err!(self.tcx.sess, e.span, E0021,
"static items are not allowed to have managed pointers");
}
ast::ExprBox(..) |
ast::ExprUnary(ast::UnUniq, _) => {
span_err!(self.tcx.sess, e.span, E0022,
"static items are not allowed to have custom pointers");
}
_ => {
let node_ty = ty::node_id_to_type(self.tcx, e.id);
match ty::get(node_ty).sty {
ty::ty_struct(did, _) |
ty::ty_enum(did, _) => {
if ty::has_dtor(self.tcx, did) {
self.report_error(e.span,
Some("static items are not allowed to have \
destructors".to_string()));
return;
}
}
_ => {}
}
visit::walk_expr(self, e, is_const);
}
}
}
}
|
{
visit::walk_crate(&mut CheckStaticVisitor { tcx: tcx }, krate, false)
}
|
identifier_body
|
check_static.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.
// Verifies that the types and values of static items
// are safe. The rules enforced by this module are:
//
// - For each *mutable* static item, it checks that its **type**:
// - doesn't have a destructor
// - doesn't own an owned pointer
//
// - For each *immutable* static item, it checks that its **value**:
// - doesn't own owned, managed pointers
// - doesn't contain a struct literal or a call to an enum variant / struct constructor where
// - the type of the struct/enum has a dtor
//
// Rules Enforced Elsewhere:
// - It's not possible to take the address of a static item with unsafe interior. This is enforced
// by borrowck::gather_loans
use middle::ty;
use syntax::ast;
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
use syntax::print::pprust;
fn safe_type_for_static_mut(cx: &ty::ctxt, e: &ast::Expr) -> Option<String> {
let node_ty = ty::node_id_to_type(cx, e.id);
let tcontents = ty::type_contents(cx, node_ty);
debug!("safe_type_for_static_mut(dtor={}, managed={}, owned={})",
tcontents.has_dtor(), tcontents.owns_managed(), tcontents.owns_owned())
let suffix = if tcontents.has_dtor() {
"destructors"
} else if tcontents.owns_managed() {
"managed pointers"
} else if tcontents.owns_owned() {
"owned pointers"
} else {
return None;
};
Some(format!("mutable static items are not allowed to have {}", suffix))
}
struct
|
<'a> {
tcx: &'a ty::ctxt,
}
pub fn check_crate(tcx: &ty::ctxt, krate: &ast::Crate) {
visit::walk_crate(&mut CheckStaticVisitor { tcx: tcx }, krate, false)
}
impl<'a> CheckStaticVisitor<'a> {
fn report_error(&self, span: Span, result: Option<String>) -> bool {
match result {
None => { false }
Some(msg) => {
self.tcx.sess.span_err(span, msg.as_slice());
true
}
}
}
}
impl<'a> Visitor<bool> for CheckStaticVisitor<'a> {
fn visit_item(&mut self, i: &ast::Item, _is_const: bool) {
debug!("visit_item(item={})", pprust::item_to_string(i));
match i.node {
ast::ItemStatic(_, mutability, ref expr) => {
match mutability {
ast::MutImmutable => {
self.visit_expr(&**expr, true);
}
ast::MutMutable => {
let safe = safe_type_for_static_mut(self.tcx, &**expr);
self.report_error(expr.span, safe);
}
}
}
_ => { visit::walk_item(self, i, false) }
}
}
/// This method is used to enforce the constraints on
/// immutable static items. It walks through the *value*
/// of the item walking down the expression and evaluating
/// every nested expression. if the expression is not part
/// of a static item, this method does nothing but walking
/// down through it.
fn visit_expr(&mut self, e: &ast::Expr, is_const: bool) {
debug!("visit_expr(expr={})", pprust::expr_to_string(e));
if!is_const {
return visit::walk_expr(self, e, is_const);
}
match e.node {
ast::ExprField(..) | ast::ExprVec(..) |
ast::ExprBlock(..) | ast::ExprTup(..) => {
visit::walk_expr(self, e, is_const);
}
ast::ExprAddrOf(ast::MutMutable, _) => {
span_err!(self.tcx.sess, e.span, E0020,
"static items are not allowed to have mutable slices");
},
ast::ExprUnary(ast::UnBox, _) => {
span_err!(self.tcx.sess, e.span, E0021,
"static items are not allowed to have managed pointers");
}
ast::ExprBox(..) |
ast::ExprUnary(ast::UnUniq, _) => {
span_err!(self.tcx.sess, e.span, E0022,
"static items are not allowed to have custom pointers");
}
_ => {
let node_ty = ty::node_id_to_type(self.tcx, e.id);
match ty::get(node_ty).sty {
ty::ty_struct(did, _) |
ty::ty_enum(did, _) => {
if ty::has_dtor(self.tcx, did) {
self.report_error(e.span,
Some("static items are not allowed to have \
destructors".to_string()));
return;
}
}
_ => {}
}
visit::walk_expr(self, e, is_const);
}
}
}
}
|
CheckStaticVisitor
|
identifier_name
|
generic-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.
// run-pass
#![feature(box_syntax)]
trait Foo<T> {
fn get(&self) -> T;
}
struct S {
x: isize
}
impl Foo<isize> for S {
fn get(&self) -> isize {
self.x
}
}
pub fn main()
|
{
let x = box S { x: 1 };
let y = x as Box<Foo<isize>>;
assert_eq!(y.get(), 1);
}
|
identifier_body
|
|
generic-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
|
// run-pass
#![feature(box_syntax)]
trait Foo<T> {
fn get(&self) -> T;
}
struct S {
x: isize
}
impl Foo<isize> for S {
fn get(&self) -> isize {
self.x
}
}
pub fn main() {
let x = box S { x: 1 };
let y = x as Box<Foo<isize>>;
assert_eq!(y.get(), 1);
}
|
// 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.
|
random_line_split
|
generic-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.
// run-pass
#![feature(box_syntax)]
trait Foo<T> {
fn get(&self) -> T;
}
struct S {
x: isize
}
impl Foo<isize> for S {
fn get(&self) -> isize {
self.x
}
}
pub fn
|
() {
let x = box S { x: 1 };
let y = x as Box<Foo<isize>>;
assert_eq!(y.get(), 1);
}
|
main
|
identifier_name
|
main.rs
|
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;
enum Lang {
Python,
Unknown,
}
struct CommentDelimiters {
begin: &'static str,
end: &'static str,
}
fn main() {
let fname = env::args().nth(1).unwrap();
let lang = lang_guess(&fname);
let delims = comment_delims(lang);
let path = Path::new(&fname);
let f = File::open(path);
match f {
Ok(mut fr) => {
let mut s = String::new();
fr.read_to_string(&mut s);
let v = reduce_to_comments(s, delims);
println!("_");
},
Err(_) => { },
}
}
|
fn lang_guess(s: &String) -> Lang {
let path = Path::new(&s);
let ext = path.extension();
match ext {
Some(x) => {
let y = x.to_str().unwrap();
match y {
"py" => Lang::Python,
_ => Lang::Unknown,
}
},
None => Lang::Unknown,
}
}
fn comment_delims(lang: Lang) -> CommentDelimiters {
match lang {
Lang::Python => CommentDelimiters { begin: "#", end: "\n" },
_ => CommentDelimiters { begin: "", end: "" },
}
}
fn reduce_to_comments(s: String, ds: CommentDelimiters) -> Vec<String> {
vec![]
}
|
random_line_split
|
|
main.rs
|
use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;
enum Lang {
Python,
Unknown,
}
struct CommentDelimiters {
begin: &'static str,
end: &'static str,
}
fn main() {
let fname = env::args().nth(1).unwrap();
let lang = lang_guess(&fname);
let delims = comment_delims(lang);
let path = Path::new(&fname);
let f = File::open(path);
match f {
Ok(mut fr) => {
let mut s = String::new();
fr.read_to_string(&mut s);
let v = reduce_to_comments(s, delims);
println!("_");
},
Err(_) => { },
}
}
fn
|
(s: &String) -> Lang {
let path = Path::new(&s);
let ext = path.extension();
match ext {
Some(x) => {
let y = x.to_str().unwrap();
match y {
"py" => Lang::Python,
_ => Lang::Unknown,
}
},
None => Lang::Unknown,
}
}
fn comment_delims(lang: Lang) -> CommentDelimiters {
match lang {
Lang::Python => CommentDelimiters { begin: "#", end: "\n" },
_ => CommentDelimiters { begin: "", end: "" },
}
}
fn reduce_to_comments(s: String, ds: CommentDelimiters) -> Vec<String> {
vec![]
}
|
lang_guess
|
identifier_name
|
test_multiverse_handling.rs
|
/*
* Copyright 2021 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#[cfg(test)]
mod test {
use crate::{
ast::*, compilation_top_level::*, souffle::souffle_interface::*,
test::test_queries::test::*,
};
use std::fs;
#[test]
fn test_multiverse_handling() {
setup_dirs_and_run_query_test(QueryTest {
filename: "multiverse_handling",
input_dir: "test_inputs",
|
]
})
}
}
|
output_dir: "test_outputs",
query_expects: vec![
("test_query1_true", true),
("test_query2_false", false)
|
random_line_split
|
test_multiverse_handling.rs
|
/*
* Copyright 2021 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#[cfg(test)]
mod test {
use crate::{
ast::*, compilation_top_level::*, souffle::souffle_interface::*,
test::test_queries::test::*,
};
use std::fs;
#[test]
fn
|
() {
setup_dirs_and_run_query_test(QueryTest {
filename: "multiverse_handling",
input_dir: "test_inputs",
output_dir: "test_outputs",
query_expects: vec![
("test_query1_true", true),
("test_query2_false", false)
]
})
}
}
|
test_multiverse_handling
|
identifier_name
|
test_multiverse_handling.rs
|
/*
* Copyright 2021 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#[cfg(test)]
mod test {
use crate::{
ast::*, compilation_top_level::*, souffle::souffle_interface::*,
test::test_queries::test::*,
};
use std::fs;
#[test]
fn test_multiverse_handling()
|
}
|
{
setup_dirs_and_run_query_test(QueryTest {
filename: "multiverse_handling",
input_dir: "test_inputs",
output_dir: "test_outputs",
query_expects: vec![
("test_query1_true", true),
("test_query2_false", false)
]
})
}
|
identifier_body
|
factory.rs
|
// Integration tests
extern crate txtdb;
use txtdb::controller::*;
use txtdb::factory::*;
#[test]
fn test_create_record() {
let input = String::from_str("1 payload metadata");
let expected = Record {
id: 1,
payload: String::from_str("payload"),
metadata: String::from_str("metadata"),
};
let reader = Reader::new(&Path::new("tests/base-test.txt"));
let factory: Factory = RecordFactory::new(reader);
let output: Record = factory.create(input).ok().expect("Parsing failed.");
assert_eq!(expected.id, output.id);
assert_eq!(expected.payload, output.payload);
assert_eq!(expected.metadata, output.metadata);
}
#[test]
fn
|
() {
let input = String::from_str("5 cGF5bG9hZA== bWV0YWRhdGE=");
let expected = Record {
id: 5,
payload: String::from_str("payload"),
metadata: String::from_str("metadata"),
};
let reader = Reader::new(&Path::new("tests/base-test.txt"));
let factory: Factory = RecordFactory::new(reader);
let output: Record = factory.create_from_enc(input).ok().expect("Parsing failed.");
assert_eq!(expected.id, output.id);
assert_eq!(expected.payload, output.payload);
assert_eq!(expected.metadata, output.metadata);
}
|
test_create_from_encoded
|
identifier_name
|
factory.rs
|
extern crate txtdb;
use txtdb::controller::*;
use txtdb::factory::*;
#[test]
fn test_create_record() {
let input = String::from_str("1 payload metadata");
let expected = Record {
id: 1,
payload: String::from_str("payload"),
metadata: String::from_str("metadata"),
};
let reader = Reader::new(&Path::new("tests/base-test.txt"));
let factory: Factory = RecordFactory::new(reader);
let output: Record = factory.create(input).ok().expect("Parsing failed.");
assert_eq!(expected.id, output.id);
assert_eq!(expected.payload, output.payload);
assert_eq!(expected.metadata, output.metadata);
}
#[test]
fn test_create_from_encoded() {
let input = String::from_str("5 cGF5bG9hZA== bWV0YWRhdGE=");
let expected = Record {
id: 5,
payload: String::from_str("payload"),
metadata: String::from_str("metadata"),
};
let reader = Reader::new(&Path::new("tests/base-test.txt"));
let factory: Factory = RecordFactory::new(reader);
let output: Record = factory.create_from_enc(input).ok().expect("Parsing failed.");
assert_eq!(expected.id, output.id);
assert_eq!(expected.payload, output.payload);
assert_eq!(expected.metadata, output.metadata);
}
|
// Integration tests
|
random_line_split
|
|
factory.rs
|
// Integration tests
extern crate txtdb;
use txtdb::controller::*;
use txtdb::factory::*;
#[test]
fn test_create_record()
|
#[test]
fn test_create_from_encoded() {
let input = String::from_str("5 cGF5bG9hZA== bWV0YWRhdGE=");
let expected = Record {
id: 5,
payload: String::from_str("payload"),
metadata: String::from_str("metadata"),
};
let reader = Reader::new(&Path::new("tests/base-test.txt"));
let factory: Factory = RecordFactory::new(reader);
let output: Record = factory.create_from_enc(input).ok().expect("Parsing failed.");
assert_eq!(expected.id, output.id);
assert_eq!(expected.payload, output.payload);
assert_eq!(expected.metadata, output.metadata);
}
|
{
let input = String::from_str("1 payload metadata");
let expected = Record {
id: 1,
payload: String::from_str("payload"),
metadata: String::from_str("metadata"),
};
let reader = Reader::new(&Path::new("tests/base-test.txt"));
let factory: Factory = RecordFactory::new(reader);
let output: Record = factory.create(input).ok().expect("Parsing failed.");
assert_eq!(expected.id, output.id);
assert_eq!(expected.payload, output.payload);
assert_eq!(expected.metadata, output.metadata);
}
|
identifier_body
|
road.rs
|
//! `StructureRoad` data description.
use crate::data::RoomName;
with_structure_fields_and_update_struct! {
/// A road structure - a structure that speeds up creeps without sufficient move parts.
#[derive(Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StructureRoad {
/// The next game tick when this structure's hits will decrease naturally.
pub next_decay_time: u32,
/// Whether or not an attack on this structure will send an email to the owner automatically.
pub notify_when_attacked: bool,
}
/// The update structure for a road structure.
#[derive(Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StructureRoadUpdate {
- next_decay_time: u32,
- notify_when_attacked: bool,
}
}
#[cfg(test)]
mod test {
use serde::Deserialize;
use serde_json;
use crate::data::RoomName;
use super::StructureRoad;
#[test]
fn parse_road_and_update()
|
y: 20,
id: "58a1ec36947c6c2d324a2d39".to_owned(),
hits: 2600,
hits_max: 5000,
next_decay_time: 19894066,
notify_when_attacked: true,
}
);
obj.update(
serde_json::from_value(json!({
// note: these are fake values, not a real update.
"hits": 2000,
"nextDecayTime": 20000000,
}))
.unwrap(),
);
assert_eq!(
obj,
StructureRoad {
room: RoomName::new("E4S61").unwrap(),
x: 14,
y: 20,
id: "58a1ec36947c6c2d324a2d39".to_owned(),
hits: 2000,
hits_max: 5000,
next_decay_time: 20000000,
notify_when_attacked: true,
}
);
}
}
|
{
let json = json!({
"_id": "58a1ec36947c6c2d324a2d39",
"hits": 2600,
"hitsMax": 5000,
"nextDecayTime": 19894066,
"notifyWhenAttacked": true,
"room": "E4S61",
"type": "road",
"x": 14,
"y": 20
});
let mut obj = StructureRoad::deserialize(json).unwrap();
assert_eq!(
obj,
StructureRoad {
room: RoomName::new("E4S61").unwrap(),
x: 14,
|
identifier_body
|
road.rs
|
//! `StructureRoad` data description.
use crate::data::RoomName;
with_structure_fields_and_update_struct! {
/// A road structure - a structure that speeds up creeps without sufficient move parts.
#[derive(Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StructureRoad {
/// The next game tick when this structure's hits will decrease naturally.
pub next_decay_time: u32,
/// Whether or not an attack on this structure will send an email to the owner automatically.
pub notify_when_attacked: bool,
}
/// The update structure for a road structure.
#[derive(Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StructureRoadUpdate {
- next_decay_time: u32,
- notify_when_attacked: bool,
}
}
#[cfg(test)]
mod test {
use serde::Deserialize;
use serde_json;
use crate::data::RoomName;
use super::StructureRoad;
#[test]
fn parse_road_and_update() {
let json = json!({
"_id": "58a1ec36947c6c2d324a2d39",
"hits": 2600,
"hitsMax": 5000,
"nextDecayTime": 19894066,
"notifyWhenAttacked": true,
"room": "E4S61",
"type": "road",
"x": 14,
"y": 20
});
let mut obj = StructureRoad::deserialize(json).unwrap();
assert_eq!(
obj,
StructureRoad {
room: RoomName::new("E4S61").unwrap(),
x: 14,
y: 20,
|
}
);
obj.update(
serde_json::from_value(json!({
// note: these are fake values, not a real update.
"hits": 2000,
"nextDecayTime": 20000000,
}))
.unwrap(),
);
assert_eq!(
obj,
StructureRoad {
room: RoomName::new("E4S61").unwrap(),
x: 14,
y: 20,
id: "58a1ec36947c6c2d324a2d39".to_owned(),
hits: 2000,
hits_max: 5000,
next_decay_time: 20000000,
notify_when_attacked: true,
}
);
}
}
|
id: "58a1ec36947c6c2d324a2d39".to_owned(),
hits: 2600,
hits_max: 5000,
next_decay_time: 19894066,
notify_when_attacked: true,
|
random_line_split
|
road.rs
|
//! `StructureRoad` data description.
use crate::data::RoomName;
with_structure_fields_and_update_struct! {
/// A road structure - a structure that speeds up creeps without sufficient move parts.
#[derive(Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct StructureRoad {
/// The next game tick when this structure's hits will decrease naturally.
pub next_decay_time: u32,
/// Whether or not an attack on this structure will send an email to the owner automatically.
pub notify_when_attacked: bool,
}
/// The update structure for a road structure.
#[derive(Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct StructureRoadUpdate {
- next_decay_time: u32,
- notify_when_attacked: bool,
}
}
#[cfg(test)]
mod test {
use serde::Deserialize;
use serde_json;
use crate::data::RoomName;
use super::StructureRoad;
#[test]
fn
|
() {
let json = json!({
"_id": "58a1ec36947c6c2d324a2d39",
"hits": 2600,
"hitsMax": 5000,
"nextDecayTime": 19894066,
"notifyWhenAttacked": true,
"room": "E4S61",
"type": "road",
"x": 14,
"y": 20
});
let mut obj = StructureRoad::deserialize(json).unwrap();
assert_eq!(
obj,
StructureRoad {
room: RoomName::new("E4S61").unwrap(),
x: 14,
y: 20,
id: "58a1ec36947c6c2d324a2d39".to_owned(),
hits: 2600,
hits_max: 5000,
next_decay_time: 19894066,
notify_when_attacked: true,
}
);
obj.update(
serde_json::from_value(json!({
// note: these are fake values, not a real update.
"hits": 2000,
"nextDecayTime": 20000000,
}))
.unwrap(),
);
assert_eq!(
obj,
StructureRoad {
room: RoomName::new("E4S61").unwrap(),
x: 14,
y: 20,
id: "58a1ec36947c6c2d324a2d39".to_owned(),
hits: 2000,
hits_max: 5000,
next_decay_time: 20000000,
notify_when_attacked: true,
}
);
}
}
|
parse_road_and_update
|
identifier_name
|
candidate.rs
|
use super::events::*;
use super::server::RaftServerState;
use super::server::{RaftStateTransition, NextState, Continue};
use super::server::{RaftNextState, RaftLeader, RaftFollower};
// This file contains all the callback logic for Candidate Peers in
// Raft.
//
// Rust doesn't support arbitrary methods being defined in another
// file... except with traits.
//
// I don't know how this copes with small private helper functions.
// Hopefully you won't need to declare them in the trait before you
// can define them in the impl Candidate for RaftServerState.
pub trait Candidate {
fn candidate_setup(&mut self) -> RaftStateTransition;
fn candidate_teardown(&mut self);
fn candidate_append_entries_req(&mut self, req: AppendEntriesReq, chan: Sender<AppendEntriesRes>) -> RaftStateTransition;
fn candidate_append_entries_res(&mut self, res: AppendEntriesRes) -> RaftStateTransition;
fn candidate_vote_req(&mut self, req: VoteReq, chan: Sender<VoteRes>) -> RaftStateTransition;
fn candidate_vote_res(&mut self, res: VoteRes) -> RaftStateTransition;
}
// TODO: Real Implementations
impl Candidate for RaftServerState {
fn
|
(&mut self) -> RaftStateTransition {
Continue
}
fn candidate_teardown(&mut self) {
}
fn candidate_append_entries_req(&mut self, req: AppendEntriesReq, chan: Sender<AppendEntriesRes>) -> RaftStateTransition {
Continue
}
fn candidate_append_entries_res(&mut self, res: AppendEntriesRes) -> RaftStateTransition {
Continue
}
fn candidate_vote_req(&mut self, req: VoteReq, chan: Sender<VoteRes>) -> RaftStateTransition {
Continue
}
fn candidate_vote_res(&mut self, res: VoteRes) -> RaftStateTransition {
Continue
}
}
|
candidate_setup
|
identifier_name
|
candidate.rs
|
use super::events::*;
use super::server::RaftServerState;
use super::server::{RaftStateTransition, NextState, Continue};
use super::server::{RaftNextState, RaftLeader, RaftFollower};
// This file contains all the callback logic for Candidate Peers in
// Raft.
//
// Rust doesn't support arbitrary methods being defined in another
// file... except with traits.
//
// I don't know how this copes with small private helper functions.
// Hopefully you won't need to declare them in the trait before you
// can define them in the impl Candidate for RaftServerState.
|
pub trait Candidate {
fn candidate_setup(&mut self) -> RaftStateTransition;
fn candidate_teardown(&mut self);
fn candidate_append_entries_req(&mut self, req: AppendEntriesReq, chan: Sender<AppendEntriesRes>) -> RaftStateTransition;
fn candidate_append_entries_res(&mut self, res: AppendEntriesRes) -> RaftStateTransition;
fn candidate_vote_req(&mut self, req: VoteReq, chan: Sender<VoteRes>) -> RaftStateTransition;
fn candidate_vote_res(&mut self, res: VoteRes) -> RaftStateTransition;
}
// TODO: Real Implementations
impl Candidate for RaftServerState {
fn candidate_setup(&mut self) -> RaftStateTransition {
Continue
}
fn candidate_teardown(&mut self) {
}
fn candidate_append_entries_req(&mut self, req: AppendEntriesReq, chan: Sender<AppendEntriesRes>) -> RaftStateTransition {
Continue
}
fn candidate_append_entries_res(&mut self, res: AppendEntriesRes) -> RaftStateTransition {
Continue
}
fn candidate_vote_req(&mut self, req: VoteReq, chan: Sender<VoteRes>) -> RaftStateTransition {
Continue
}
fn candidate_vote_res(&mut self, res: VoteRes) -> RaftStateTransition {
Continue
}
}
|
random_line_split
|
|
candidate.rs
|
use super::events::*;
use super::server::RaftServerState;
use super::server::{RaftStateTransition, NextState, Continue};
use super::server::{RaftNextState, RaftLeader, RaftFollower};
// This file contains all the callback logic for Candidate Peers in
// Raft.
//
// Rust doesn't support arbitrary methods being defined in another
// file... except with traits.
//
// I don't know how this copes with small private helper functions.
// Hopefully you won't need to declare them in the trait before you
// can define them in the impl Candidate for RaftServerState.
pub trait Candidate {
fn candidate_setup(&mut self) -> RaftStateTransition;
fn candidate_teardown(&mut self);
fn candidate_append_entries_req(&mut self, req: AppendEntriesReq, chan: Sender<AppendEntriesRes>) -> RaftStateTransition;
fn candidate_append_entries_res(&mut self, res: AppendEntriesRes) -> RaftStateTransition;
fn candidate_vote_req(&mut self, req: VoteReq, chan: Sender<VoteRes>) -> RaftStateTransition;
fn candidate_vote_res(&mut self, res: VoteRes) -> RaftStateTransition;
}
// TODO: Real Implementations
impl Candidate for RaftServerState {
fn candidate_setup(&mut self) -> RaftStateTransition {
Continue
}
fn candidate_teardown(&mut self) {
}
fn candidate_append_entries_req(&mut self, req: AppendEntriesReq, chan: Sender<AppendEntriesRes>) -> RaftStateTransition
|
fn candidate_append_entries_res(&mut self, res: AppendEntriesRes) -> RaftStateTransition {
Continue
}
fn candidate_vote_req(&mut self, req: VoteReq, chan: Sender<VoteRes>) -> RaftStateTransition {
Continue
}
fn candidate_vote_res(&mut self, res: VoteRes) -> RaftStateTransition {
Continue
}
}
|
{
Continue
}
|
identifier_body
|
knl.rs
|
#![feature(specialization)]
#![feature(conservative_impl_trait)]
#![feature(cfg_target_feature)]
#![feature(asm)]
#![allow(unused_imports)]
extern crate core;
extern crate typenum;
extern crate momms;
use std::time::{Instant};
use typenum::{Unsigned,U1};
use momms::kern::KernelNM;
use momms::matrix::{Scalar, Mat, ColumnPanelMatrix, RowPanelMatrix, Matrix, Hierarch};
use momms::composables::{GemmNode, AlgorithmStep, PartM, PartN, PartK, PackA, PackB, UnpackC, SpawnThreads, ParallelM, ParallelN, TheRest, Target};
use momms::thread_comm::ThreadInfo;
use momms::util;
fn test_algorithm_flat<T: Scalar, S: GemmNode<T, Matrix<T>, Matrix<T>, Matrix<T>>>
( m:usize, n: usize, k: usize, algo: &mut S, flusher: &mut Vec<f64>, n_reps: usize ) -> (f64, T)
{
let mut best_time: f64 = 9999999999.0;
let mut worst_err: T = T::zero();
for _ in 0..n_reps {
//Create matrices.
let mut a = <Matrix<T>>::new(m, k);
let mut b = <Matrix<T>>::new(k, n);
//The micro-kernel used is more efficient with row-major C.
let mut c = <Matrix<T>>::new(n, m);
c.transpose();
//Fill the matrices
a.fill_rand(); c.fill_zero(); b.fill_rand();
//Read a buffer so that A, B, and C are cold in cache.
for i in flusher.iter_mut() { *i += 1.0; }
//Time and run algorithm
let start = Instant::now();
unsafe{ algo.run( &mut a, &mut b, &mut c, &ThreadInfo::single_thread() ); }
best_time = best_time.min(util::dur_seconds(start));
let err = util::test_c_eq_a_b( &mut a, &mut b, &mut c);
worst_err = worst_err.max(err);
}
(best_time, worst_err)
}
fn test() {
use typenum::{UInt, UTerm, B0, B1, Unsigned};
//type U3000 = UInt<UInt<typenum::U750, B0>, B0>;
//type NC = U3000;
//type KC = typenum::U192;
//type MC = typenum::U120;
//type MR = typenum::U8; //typenum::U4;
//type NR = typenum::U4; //typenum::U12;
//type Goto<T,MTA,MTB,MTC>
// = SpawnThreads<T, MTA, MTB, MTC,
// PartN<T, MTA, MTB, MTC, NC,
// PartK<T, MTA, MTB, MTC, KC,
// PackB<T, MTA, MTB, MTC, ColumnPanelMatrix<T,NR>,
// PartM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MC,
// PackA<T, MTA, ColumnPanelMatrix<T,NR>, MTC, RowPanelMatrix<T,MR>,
// ParallelN<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, TheRest,
// KernelNM<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, MR>>>>>>>>;
type U14400 = UInt<UInt<UInt<UInt<typenum::U900, B0>, B0>, B0>, B0>;
type NC = U14400;
type KC = typenum::U336; //
type MC = typenum::U120;
type MR = typenum::U24;//
type NR = typenum::U8;//
type JCWAY = Target<typenum::U4>;
type Goto<T,MTA,MTB,MTC>
= SpawnThreads<T, MTA, MTB, MTC,
ParallelN<T, MTA, MTB, MTC, NR, JCWAY,
PartN<T, MTA, MTB, MTC, NC,
PartK<T, MTA, MTB, MTC, KC,
PackB<T, MTA, MTB, MTC, ColumnPanelMatrix<T,NR>,
ParallelM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MR, TheRest,
PartM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MC,
PackA<T, MTA, ColumnPanelMatrix<T,NR>, MTC, RowPanelMatrix<T,MR>,
KernelNM<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, MR>>>>>>>>>;
type NcL3 = typenum::U768;
type KcL3 = typenum::U768;
type McL2 = typenum::U120;
type KcL2 = typenum::U192;
type L3bA<T> = Hierarch<T, MR, KcL2, U1, MR>;
type L3bB<T> = Hierarch<T, KcL2, NR, NR, U1>;
type L3bC<T> = Hierarch<T, MR, NR, NR, U1>;
type L3B<T,MTA,MTB,MTC>
= SpawnThreads<T, MTA, MTB, MTC,
PartN<T, MTA, MTB, MTC, NcL3,
PartK<T, MTA, MTB, MTC, KcL3,
PackB<T, MTA, MTB, MTC, L3bB<T>,
PartM<T, MTA, L3bB<T>, MTC, McL2,
UnpackC<T, MTA, L3bB<T>, MTC, L3bC<T>, //not sure if this goes here or the beginning or never...
PartK<T, MTA, L3bB<T>, L3bC<T>, KcL2,
PackA<T, MTA, L3bB<T>, L3bC<T>, L3bA<T>,
ParallelN<T, L3bA<T>, L3bB<T>, L3bC<T>, NR, TheRest,
KernelNM<T, L3bA<T>, L3bB<T>, L3bC<T>, NR, MR>>>>>>>>>>;
let mut goto = <Goto<f64, Matrix<f64>, Matrix<f64>, Matrix<f64>>>::new();
let mut l3b = <L3B<f64, Matrix<f64>, Matrix<f64>, Matrix<f64>>>::new();
goto.set_n_threads(64);
l3b.set_n_threads(64);
//Initialize array to flush cache with
let flusher_len = 2*1024*1024; //16MB
let mut flusher : Vec<f64> = Vec::with_capacity(flusher_len);
for _ in 0..flusher_len { flusher.push(0.0); }
println!("m\tn\tk\t{: <13}{: <13}{: <15}{: <15}", "goto", "l3b", "goto", "l3b");
for index in 6..9 {
let size = index*500;
let (m, n, k) = (size, size, size);
let n_reps = 5;
let (goto_time, goto_err) = test_algorithm_flat(m, n, k, &mut goto, &mut flusher, n_reps);
let (l3b_time, l3b_err) = test_algorithm_flat(m, n, k, &mut l3b, &mut flusher, n_reps);
println!("{}\t{}\t{}\t{}{}{}{}",
m, n, k,
format!("{: <13.5}", util::gflops(m,n,k,goto_time)),
format!("{: <13.5}", util::gflops(m,n,k,l3b_time)),
format!("{: <15.5e}", goto_err.sqrt()),
format!("{: <15.5e}", l3b_err.sqrt()));
}
let mut sum = 0.0;
for a in flusher.iter() {
sum += *a;
}
println!("Flush value {}", sum);
}
fn
|
() {
test( );
}
|
main
|
identifier_name
|
knl.rs
|
#![feature(specialization)]
#![feature(conservative_impl_trait)]
#![feature(cfg_target_feature)]
#![feature(asm)]
#![allow(unused_imports)]
extern crate core;
extern crate typenum;
extern crate momms;
use std::time::{Instant};
use typenum::{Unsigned,U1};
use momms::kern::KernelNM;
use momms::matrix::{Scalar, Mat, ColumnPanelMatrix, RowPanelMatrix, Matrix, Hierarch};
use momms::composables::{GemmNode, AlgorithmStep, PartM, PartN, PartK, PackA, PackB, UnpackC, SpawnThreads, ParallelM, ParallelN, TheRest, Target};
use momms::thread_comm::ThreadInfo;
use momms::util;
fn test_algorithm_flat<T: Scalar, S: GemmNode<T, Matrix<T>, Matrix<T>, Matrix<T>>>
( m:usize, n: usize, k: usize, algo: &mut S, flusher: &mut Vec<f64>, n_reps: usize ) -> (f64, T)
{
let mut best_time: f64 = 9999999999.0;
let mut worst_err: T = T::zero();
for _ in 0..n_reps {
//Create matrices.
let mut a = <Matrix<T>>::new(m, k);
let mut b = <Matrix<T>>::new(k, n);
//The micro-kernel used is more efficient with row-major C.
let mut c = <Matrix<T>>::new(n, m);
c.transpose();
//Fill the matrices
a.fill_rand(); c.fill_zero(); b.fill_rand();
//Read a buffer so that A, B, and C are cold in cache.
for i in flusher.iter_mut() { *i += 1.0; }
//Time and run algorithm
let start = Instant::now();
unsafe{ algo.run( &mut a, &mut b, &mut c, &ThreadInfo::single_thread() ); }
best_time = best_time.min(util::dur_seconds(start));
let err = util::test_c_eq_a_b( &mut a, &mut b, &mut c);
worst_err = worst_err.max(err);
}
(best_time, worst_err)
}
fn test()
|
type NC = U14400;
type KC = typenum::U336; //
type MC = typenum::U120;
type MR = typenum::U24;//
type NR = typenum::U8;//
type JCWAY = Target<typenum::U4>;
type Goto<T,MTA,MTB,MTC>
= SpawnThreads<T, MTA, MTB, MTC,
ParallelN<T, MTA, MTB, MTC, NR, JCWAY,
PartN<T, MTA, MTB, MTC, NC,
PartK<T, MTA, MTB, MTC, KC,
PackB<T, MTA, MTB, MTC, ColumnPanelMatrix<T,NR>,
ParallelM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MR, TheRest,
PartM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MC,
PackA<T, MTA, ColumnPanelMatrix<T,NR>, MTC, RowPanelMatrix<T,MR>,
KernelNM<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, MR>>>>>>>>>;
type NcL3 = typenum::U768;
type KcL3 = typenum::U768;
type McL2 = typenum::U120;
type KcL2 = typenum::U192;
type L3bA<T> = Hierarch<T, MR, KcL2, U1, MR>;
type L3bB<T> = Hierarch<T, KcL2, NR, NR, U1>;
type L3bC<T> = Hierarch<T, MR, NR, NR, U1>;
type L3B<T,MTA,MTB,MTC>
= SpawnThreads<T, MTA, MTB, MTC,
PartN<T, MTA, MTB, MTC, NcL3,
PartK<T, MTA, MTB, MTC, KcL3,
PackB<T, MTA, MTB, MTC, L3bB<T>,
PartM<T, MTA, L3bB<T>, MTC, McL2,
UnpackC<T, MTA, L3bB<T>, MTC, L3bC<T>, //not sure if this goes here or the beginning or never...
PartK<T, MTA, L3bB<T>, L3bC<T>, KcL2,
PackA<T, MTA, L3bB<T>, L3bC<T>, L3bA<T>,
ParallelN<T, L3bA<T>, L3bB<T>, L3bC<T>, NR, TheRest,
KernelNM<T, L3bA<T>, L3bB<T>, L3bC<T>, NR, MR>>>>>>>>>>;
let mut goto = <Goto<f64, Matrix<f64>, Matrix<f64>, Matrix<f64>>>::new();
let mut l3b = <L3B<f64, Matrix<f64>, Matrix<f64>, Matrix<f64>>>::new();
goto.set_n_threads(64);
l3b.set_n_threads(64);
//Initialize array to flush cache with
let flusher_len = 2*1024*1024; //16MB
let mut flusher : Vec<f64> = Vec::with_capacity(flusher_len);
for _ in 0..flusher_len { flusher.push(0.0); }
println!("m\tn\tk\t{: <13}{: <13}{: <15}{: <15}", "goto", "l3b", "goto", "l3b");
for index in 6..9 {
let size = index*500;
let (m, n, k) = (size, size, size);
let n_reps = 5;
let (goto_time, goto_err) = test_algorithm_flat(m, n, k, &mut goto, &mut flusher, n_reps);
let (l3b_time, l3b_err) = test_algorithm_flat(m, n, k, &mut l3b, &mut flusher, n_reps);
println!("{}\t{}\t{}\t{}{}{}{}",
m, n, k,
format!("{: <13.5}", util::gflops(m,n,k,goto_time)),
format!("{: <13.5}", util::gflops(m,n,k,l3b_time)),
format!("{: <15.5e}", goto_err.sqrt()),
format!("{: <15.5e}", l3b_err.sqrt()));
}
let mut sum = 0.0;
for a in flusher.iter() {
sum += *a;
}
println!("Flush value {}", sum);
}
fn main() {
test( );
}
|
{
use typenum::{UInt, UTerm, B0, B1, Unsigned};
//type U3000 = UInt<UInt<typenum::U750, B0>, B0>;
//type NC = U3000;
//type KC = typenum::U192;
//type MC = typenum::U120;
//type MR = typenum::U8; //typenum::U4;
//type NR = typenum::U4; //typenum::U12;
//type Goto<T,MTA,MTB,MTC>
// = SpawnThreads<T, MTA, MTB, MTC,
// PartN<T, MTA, MTB, MTC, NC,
// PartK<T, MTA, MTB, MTC, KC,
// PackB<T, MTA, MTB, MTC, ColumnPanelMatrix<T,NR>,
// PartM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MC,
// PackA<T, MTA, ColumnPanelMatrix<T,NR>, MTC, RowPanelMatrix<T,MR>,
// ParallelN<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, TheRest,
// KernelNM<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, MR>>>>>>>>;
type U14400 = UInt<UInt<UInt<UInt<typenum::U900, B0>, B0>, B0>, B0>;
|
identifier_body
|
knl.rs
|
#![feature(specialization)]
#![feature(conservative_impl_trait)]
#![feature(cfg_target_feature)]
#![feature(asm)]
#![allow(unused_imports)]
extern crate core;
extern crate typenum;
extern crate momms;
use std::time::{Instant};
use typenum::{Unsigned,U1};
use momms::kern::KernelNM;
use momms::matrix::{Scalar, Mat, ColumnPanelMatrix, RowPanelMatrix, Matrix, Hierarch};
use momms::composables::{GemmNode, AlgorithmStep, PartM, PartN, PartK, PackA, PackB, UnpackC, SpawnThreads, ParallelM, ParallelN, TheRest, Target};
use momms::thread_comm::ThreadInfo;
use momms::util;
fn test_algorithm_flat<T: Scalar, S: GemmNode<T, Matrix<T>, Matrix<T>, Matrix<T>>>
( m:usize, n: usize, k: usize, algo: &mut S, flusher: &mut Vec<f64>, n_reps: usize ) -> (f64, T)
{
let mut best_time: f64 = 9999999999.0;
let mut worst_err: T = T::zero();
for _ in 0..n_reps {
//Create matrices.
let mut a = <Matrix<T>>::new(m, k);
let mut b = <Matrix<T>>::new(k, n);
//The micro-kernel used is more efficient with row-major C.
let mut c = <Matrix<T>>::new(n, m);
c.transpose();
//Fill the matrices
a.fill_rand(); c.fill_zero(); b.fill_rand();
//Read a buffer so that A, B, and C are cold in cache.
for i in flusher.iter_mut() { *i += 1.0; }
//Time and run algorithm
let start = Instant::now();
unsafe{ algo.run( &mut a, &mut b, &mut c, &ThreadInfo::single_thread() ); }
best_time = best_time.min(util::dur_seconds(start));
let err = util::test_c_eq_a_b( &mut a, &mut b, &mut c);
worst_err = worst_err.max(err);
}
(best_time, worst_err)
}
fn test() {
use typenum::{UInt, UTerm, B0, B1, Unsigned};
//type U3000 = UInt<UInt<typenum::U750, B0>, B0>;
//type NC = U3000;
//type KC = typenum::U192;
//type MC = typenum::U120;
//type MR = typenum::U8; //typenum::U4;
//type NR = typenum::U4; //typenum::U12;
//type Goto<T,MTA,MTB,MTC>
// = SpawnThreads<T, MTA, MTB, MTC,
// PartN<T, MTA, MTB, MTC, NC,
// PartK<T, MTA, MTB, MTC, KC,
// PackB<T, MTA, MTB, MTC, ColumnPanelMatrix<T,NR>,
// PartM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MC,
// PackA<T, MTA, ColumnPanelMatrix<T,NR>, MTC, RowPanelMatrix<T,MR>,
// ParallelN<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, TheRest,
// KernelNM<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, MR>>>>>>>>;
type U14400 = UInt<UInt<UInt<UInt<typenum::U900, B0>, B0>, B0>, B0>;
type NC = U14400;
type KC = typenum::U336; //
type MC = typenum::U120;
type MR = typenum::U24;//
type NR = typenum::U8;//
type JCWAY = Target<typenum::U4>;
type Goto<T,MTA,MTB,MTC>
= SpawnThreads<T, MTA, MTB, MTC,
ParallelN<T, MTA, MTB, MTC, NR, JCWAY,
PartN<T, MTA, MTB, MTC, NC,
PartK<T, MTA, MTB, MTC, KC,
PackB<T, MTA, MTB, MTC, ColumnPanelMatrix<T,NR>,
ParallelM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MR, TheRest,
PartM<T, MTA, ColumnPanelMatrix<T,NR>, MTC, MC,
PackA<T, MTA, ColumnPanelMatrix<T,NR>, MTC, RowPanelMatrix<T,MR>,
KernelNM<T, RowPanelMatrix<T,MR>, ColumnPanelMatrix<T,NR>, MTC, NR, MR>>>>>>>>>;
type NcL3 = typenum::U768;
type KcL3 = typenum::U768;
type McL2 = typenum::U120;
type KcL2 = typenum::U192;
type L3bA<T> = Hierarch<T, MR, KcL2, U1, MR>;
type L3bB<T> = Hierarch<T, KcL2, NR, NR, U1>;
type L3bC<T> = Hierarch<T, MR, NR, NR, U1>;
type L3B<T,MTA,MTB,MTC>
= SpawnThreads<T, MTA, MTB, MTC,
PartN<T, MTA, MTB, MTC, NcL3,
PartK<T, MTA, MTB, MTC, KcL3,
PackB<T, MTA, MTB, MTC, L3bB<T>,
PartM<T, MTA, L3bB<T>, MTC, McL2,
UnpackC<T, MTA, L3bB<T>, MTC, L3bC<T>, //not sure if this goes here or the beginning or never...
PartK<T, MTA, L3bB<T>, L3bC<T>, KcL2,
PackA<T, MTA, L3bB<T>, L3bC<T>, L3bA<T>,
ParallelN<T, L3bA<T>, L3bB<T>, L3bC<T>, NR, TheRest,
KernelNM<T, L3bA<T>, L3bB<T>, L3bC<T>, NR, MR>>>>>>>>>>;
let mut goto = <Goto<f64, Matrix<f64>, Matrix<f64>, Matrix<f64>>>::new();
let mut l3b = <L3B<f64, Matrix<f64>, Matrix<f64>, Matrix<f64>>>::new();
goto.set_n_threads(64);
l3b.set_n_threads(64);
//Initialize array to flush cache with
let flusher_len = 2*1024*1024; //16MB
let mut flusher : Vec<f64> = Vec::with_capacity(flusher_len);
for _ in 0..flusher_len { flusher.push(0.0); }
println!("m\tn\tk\t{: <13}{: <13}{: <15}{: <15}", "goto", "l3b", "goto", "l3b");
for index in 6..9 {
let size = index*500;
let (m, n, k) = (size, size, size);
let n_reps = 5;
let (goto_time, goto_err) = test_algorithm_flat(m, n, k, &mut goto, &mut flusher, n_reps);
let (l3b_time, l3b_err) = test_algorithm_flat(m, n, k, &mut l3b, &mut flusher, n_reps);
println!("{}\t{}\t{}\t{}{}{}{}",
m, n, k,
format!("{: <13.5}", util::gflops(m,n,k,goto_time)),
format!("{: <13.5}", util::gflops(m,n,k,l3b_time)),
format!("{: <15.5e}", goto_err.sqrt()),
format!("{: <15.5e}", l3b_err.sqrt()));
}
let mut sum = 0.0;
for a in flusher.iter() {
sum += *a;
}
println!("Flush value {}", sum);
}
|
fn main() {
test( );
}
|
random_line_split
|
|
overloaded-autoderef.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.
//
|
use std::cell::RefCell;
use std::rc::Rc;
use std::string::String;
#[deriving(PartialEq, Show)]
struct Point {
x: int,
y: int
}
pub fn main() {
assert_eq!(Rc::new(5u).to_uint(), Some(5));
assert_eq!((box &box &Rc::new(box box &box 5u)).to_uint(), Some(5));
let point = Rc::new(Point {x: 2, y: 4});
assert_eq!(point.x, 2);
assert_eq!(point.y, 4);
let i = Rc::new(RefCell::new(2));
let i_value = *i.borrow();
*i.borrow_mut() = 5;
assert_eq!((i_value, *i.borrow()), (2, 5));
let s = Rc::new("foo".to_string());
assert!(s.equiv(&("foo")));
assert_eq!(s.as_slice(), "foo");
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
mut_s.borrow_mut().push_str("bar");
// HACK assert_eq! would fail here because it stores the LHS and RHS in two locals.
assert!(mut_s.borrow().as_slice() == "foobar");
assert!(mut_s.borrow_mut().as_slice() == "foobar");
let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
p.borrow_mut().x = 3;
p.borrow_mut().y += 3;
assert_eq!(*p.borrow(), Point {x: 3, y: 5});
let v = Rc::new(RefCell::new(~[1, 2, 3]));
v.borrow_mut()[0] = 3;
v.borrow_mut()[1] += 3;
assert_eq!((v.borrow()[0], v.borrow()[1], v.borrow()[2]), (3, 5, 3));
}
|
// 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.
|
random_line_split
|
overloaded-autoderef.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::rc::Rc;
use std::string::String;
#[deriving(PartialEq, Show)]
struct Point {
x: int,
y: int
}
pub fn
|
() {
assert_eq!(Rc::new(5u).to_uint(), Some(5));
assert_eq!((box &box &Rc::new(box box &box 5u)).to_uint(), Some(5));
let point = Rc::new(Point {x: 2, y: 4});
assert_eq!(point.x, 2);
assert_eq!(point.y, 4);
let i = Rc::new(RefCell::new(2));
let i_value = *i.borrow();
*i.borrow_mut() = 5;
assert_eq!((i_value, *i.borrow()), (2, 5));
let s = Rc::new("foo".to_string());
assert!(s.equiv(&("foo")));
assert_eq!(s.as_slice(), "foo");
let mut_s = Rc::new(RefCell::new(String::from_str("foo")));
mut_s.borrow_mut().push_str("bar");
// HACK assert_eq! would fail here because it stores the LHS and RHS in two locals.
assert!(mut_s.borrow().as_slice() == "foobar");
assert!(mut_s.borrow_mut().as_slice() == "foobar");
let p = Rc::new(RefCell::new(Point {x: 1, y: 2}));
p.borrow_mut().x = 3;
p.borrow_mut().y += 3;
assert_eq!(*p.borrow(), Point {x: 3, y: 5});
let v = Rc::new(RefCell::new(~[1, 2, 3]));
v.borrow_mut()[0] = 3;
v.borrow_mut()[1] += 3;
assert_eq!((v.borrow()[0], v.borrow()[1], v.borrow()[2]), (3, 5, 3));
}
|
main
|
identifier_name
|
main.rs
|
#![feature(env, old_io, old_path)]
extern crate zip;
use std::env;
use std::old_io::File;
use zip::ZipReader;
use zip::fileinfo::FileInfo;
// this is public so that rustdoc doesn't complain
pub fn
|
() {
let args: Vec<_> = env::args().collect(); // XXX
match args.len(){
2 => list_content(&mut zip_file(&args[1])),
3 => extract_file(&mut zip_file(&args[1]), &args[2]),
4 => extract_head(&mut zip_file(&args[1]), &args[2], &args[3]),
_ => print_usage(&args[0])
}
}
macro_rules! do_or_die{
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {println!("{}",err); panic!()}
})
}
fn zip_file(file: &str) -> ZipReader<File>{
do_or_die!(zip::ZipReader::open(&Path::new(file)))
}
fn output_file(file: &str)->File{
do_or_die!(File::create(&Path::new(file)))
}
fn zip_file_info(zip: &mut ZipReader<File>, file: &str) -> FileInfo{
do_or_die!(zip.info(file))
}
fn list_content(reader: &mut ZipReader<File>)->(){
for file in reader.files(){
let (year, month, day, hour, minute, second) = file.last_modified_datetime;
let mod_time = format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", year, month, day, hour, minute, second);
println!("{} ({}): bytes: {:10}, compressed: {:10}",
file.name, mod_time, file.compressed_size, file.uncompressed_size);
}
}
fn extract_file(zip: &mut ZipReader<File>, file: &str)->(){
let mut out = output_file(file);
let info = zip_file_info(zip, file);
do_or_die!(zip.extract_file(&info, &mut out));
}
fn extract_head(zip: &mut ZipReader<File>, file: &str, length: &str)->(){
let mut out = output_file(file);
let info = zip_file_info(zip, file);
let len:usize = do_or_die!(length.parse());
do_or_die!(zip.extract_first(&info, len, &mut out));
}
fn print_usage(this: &str)->(){
println!("Usage: {} [file.zip] [file_to_extract] [bytes_to_extract]", this);
}
|
main
|
identifier_name
|
main.rs
|
#![feature(env, old_io, old_path)]
extern crate zip;
use std::env;
use std::old_io::File;
use zip::ZipReader;
use zip::fileinfo::FileInfo;
// this is public so that rustdoc doesn't complain
pub fn main() {
let args: Vec<_> = env::args().collect(); // XXX
match args.len(){
2 => list_content(&mut zip_file(&args[1])),
3 => extract_file(&mut zip_file(&args[1]), &args[2]),
4 => extract_head(&mut zip_file(&args[1]), &args[2], &args[3]),
_ => print_usage(&args[0])
}
}
macro_rules! do_or_die{
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {println!("{}",err); panic!()}
})
}
fn zip_file(file: &str) -> ZipReader<File>{
do_or_die!(zip::ZipReader::open(&Path::new(file)))
}
fn output_file(file: &str)->File{
do_or_die!(File::create(&Path::new(file)))
}
fn zip_file_info(zip: &mut ZipReader<File>, file: &str) -> FileInfo
|
fn list_content(reader: &mut ZipReader<File>)->(){
for file in reader.files(){
let (year, month, day, hour, minute, second) = file.last_modified_datetime;
let mod_time = format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", year, month, day, hour, minute, second);
println!("{} ({}): bytes: {:10}, compressed: {:10}",
file.name, mod_time, file.compressed_size, file.uncompressed_size);
}
}
fn extract_file(zip: &mut ZipReader<File>, file: &str)->(){
let mut out = output_file(file);
let info = zip_file_info(zip, file);
do_or_die!(zip.extract_file(&info, &mut out));
}
fn extract_head(zip: &mut ZipReader<File>, file: &str, length: &str)->(){
let mut out = output_file(file);
let info = zip_file_info(zip, file);
let len:usize = do_or_die!(length.parse());
do_or_die!(zip.extract_first(&info, len, &mut out));
}
fn print_usage(this: &str)->(){
println!("Usage: {} [file.zip] [file_to_extract] [bytes_to_extract]", this);
}
|
{
do_or_die!(zip.info(file))
}
|
identifier_body
|
main.rs
|
#![feature(env, old_io, old_path)]
extern crate zip;
use std::env;
use std::old_io::File;
use zip::ZipReader;
use zip::fileinfo::FileInfo;
// this is public so that rustdoc doesn't complain
|
match args.len(){
2 => list_content(&mut zip_file(&args[1])),
3 => extract_file(&mut zip_file(&args[1]), &args[2]),
4 => extract_head(&mut zip_file(&args[1]), &args[2], &args[3]),
_ => print_usage(&args[0])
}
}
macro_rules! do_or_die{
($expr:expr) => (match $expr {
Ok(val) => val,
Err(err) => {println!("{}",err); panic!()}
})
}
fn zip_file(file: &str) -> ZipReader<File>{
do_or_die!(zip::ZipReader::open(&Path::new(file)))
}
fn output_file(file: &str)->File{
do_or_die!(File::create(&Path::new(file)))
}
fn zip_file_info(zip: &mut ZipReader<File>, file: &str) -> FileInfo{
do_or_die!(zip.info(file))
}
fn list_content(reader: &mut ZipReader<File>)->(){
for file in reader.files(){
let (year, month, day, hour, minute, second) = file.last_modified_datetime;
let mod_time = format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", year, month, day, hour, minute, second);
println!("{} ({}): bytes: {:10}, compressed: {:10}",
file.name, mod_time, file.compressed_size, file.uncompressed_size);
}
}
fn extract_file(zip: &mut ZipReader<File>, file: &str)->(){
let mut out = output_file(file);
let info = zip_file_info(zip, file);
do_or_die!(zip.extract_file(&info, &mut out));
}
fn extract_head(zip: &mut ZipReader<File>, file: &str, length: &str)->(){
let mut out = output_file(file);
let info = zip_file_info(zip, file);
let len:usize = do_or_die!(length.parse());
do_or_die!(zip.extract_first(&info, len, &mut out));
}
fn print_usage(this: &str)->(){
println!("Usage: {} [file.zip] [file_to_extract] [bytes_to_extract]", this);
}
|
pub fn main() {
let args: Vec<_> = env::args().collect(); // XXX
|
random_line_split
|
lib.rs
|
//! FFI bindings to the wayland system libraries.
|
//! the `ffi_dispatch` macro, like this:
//!
//! ```ignore
//! ffi_dispatch!(HANDLE_NAME, func_name, arg1, arg2, arg3);
//! ```
//!
//! Where `HANDLE_NAME` is the name of the handle generated if the cargo feature `dlopen` is on.
//!
//! For this to work, you must ensure every needed symbol is in scope (aka the static handle
//! if `dlopen` is on, the extern function if not). The easiest way to do this is to glob import
//! the appropriate module. For example:
//!
//! ```ignore
//! #[macro_use] extern crate wayland_sys;
//!
//! use wayland_sys::client::*;
//!
//! let display_ptr = unsafe {
//! ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_connect, ::std::ptr::null())
//! };
//! ```
//!
//! Each module except `common` corresponds to a system library. They all define a function named
//! `is_lib_available()` which returns whether the library could be loaded. They always return true
//! if the feature `dlopen` is absent, as we link against the library directly in that case.
#![allow(non_camel_case_types)]
#![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
// If compiling with neither the `client` or `server` feature (non-sensical but
// it's what happens when running `cargo test --all` from the workspace root),
// dlib isn't actually used. This is not an issue, so don't warn about it.
#[allow(unused_imports)]
#[cfg(any(feature = "client", feature = "server"))]
#[macro_use]
extern crate dlib;
pub mod common;
pub mod client;
pub mod server;
#[cfg(all(feature = "egl", feature = "client"))]
pub mod egl;
#[cfg(all(feature = "cursor", feature = "client"))]
pub mod cursor;
#[cfg(feature = "server")]
pub use libc::{gid_t, pid_t, uid_t};
// Small hack while #[macro_reexport] is not stable
#[cfg(feature = "dlopen")]
#[macro_export]
macro_rules! ffi_dispatch(
($handle: ident, $func: ident, $($arg: expr),*) => (
($handle.$func)($($arg),*)
)
);
#[cfg(not(feature = "dlopen"))]
#[macro_export]
macro_rules! ffi_dispatch(
($handle: ident, $func: ident, $($arg: expr),*) => (
$func($($arg),*)
)
);
|
//!
//! The names exported by this crate should *not* be used directly, but through
|
random_line_split
|
test.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
use std::collections::BTreeMap;
use std::io::Read;
use serde_json;
use serde_json::Error;
use trie::Trie;
/// TransactionTest test deserializer.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Test(BTreeMap<String, Trie>);
impl IntoIterator for Test {
type Item = <BTreeMap<String, Trie> as IntoIterator>::Item;
type IntoIter = <BTreeMap<String, Trie> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl Test {
/// Loads test from json.
pub fn load<R>(reader: R) -> Result<Self, Error> where R: Read {
serde_json::from_reader(reader)
}
}
|
//! TransactionTest test deserializer.
|
random_line_split
|
test.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! TransactionTest test deserializer.
use std::collections::BTreeMap;
use std::io::Read;
use serde_json;
use serde_json::Error;
use trie::Trie;
/// TransactionTest test deserializer.
#[derive(Debug, PartialEq, Deserialize)]
pub struct
|
(BTreeMap<String, Trie>);
impl IntoIterator for Test {
type Item = <BTreeMap<String, Trie> as IntoIterator>::Item;
type IntoIter = <BTreeMap<String, Trie> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl Test {
/// Loads test from json.
pub fn load<R>(reader: R) -> Result<Self, Error> where R: Read {
serde_json::from_reader(reader)
}
}
|
Test
|
identifier_name
|
llrepr.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.
use trans::context::CrateContext;
use trans::type_::Type;
use llvm::ValueRef;
pub trait LlvmRepr {
|
impl<T:LlvmRepr> LlvmRepr for [T] {
fn llrepr(&self, ccx: &CrateContext) -> String {
let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect();
format!("[{}]", reprs.connect(","))
}
}
impl LlvmRepr for Type {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn().type_to_string(*self)
}
}
impl LlvmRepr for ValueRef {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn().val_to_string(*self)
}
}
|
fn llrepr(&self, ccx: &CrateContext) -> String;
}
|
random_line_split
|
llrepr.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.
use trans::context::CrateContext;
use trans::type_::Type;
use llvm::ValueRef;
pub trait LlvmRepr {
fn llrepr(&self, ccx: &CrateContext) -> String;
}
impl<T:LlvmRepr> LlvmRepr for [T] {
fn
|
(&self, ccx: &CrateContext) -> String {
let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect();
format!("[{}]", reprs.connect(","))
}
}
impl LlvmRepr for Type {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn().type_to_string(*self)
}
}
impl LlvmRepr for ValueRef {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn().val_to_string(*self)
}
}
|
llrepr
|
identifier_name
|
llrepr.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.
use trans::context::CrateContext;
use trans::type_::Type;
use llvm::ValueRef;
pub trait LlvmRepr {
fn llrepr(&self, ccx: &CrateContext) -> String;
}
impl<T:LlvmRepr> LlvmRepr for [T] {
fn llrepr(&self, ccx: &CrateContext) -> String
|
}
impl LlvmRepr for Type {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn().type_to_string(*self)
}
}
impl LlvmRepr for ValueRef {
fn llrepr(&self, ccx: &CrateContext) -> String {
ccx.tn().val_to_string(*self)
}
}
|
{
let reprs: Vec<String> = self.iter().map(|t| t.llrepr(ccx)).collect();
format!("[{}]", reprs.connect(","))
}
|
identifier_body
|
shootout-k-nucleotide-pipes.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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(slicing_syntax)]
extern crate collections;
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::string::String;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn sort_and_fmt(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{} {:0.3}\n",
k.as_slice()
.to_ascii()
.to_uppercase()
.into_string(), v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii().as_slice().to_lowercase().into_string();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.pop(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
|
let len = bb.len();
while ii < len - (nn - 1u) {
it(bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
}
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
let mut line: Vec<u8>;
loop {
line = from_parent.recv();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer);
}
// given a FASTA file on stdin, process sequence THREE
fn main() {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bin!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
from_child.push(from_child_);
let (to_child, from_parent) = channel();
spawn(proc() {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
option::Option::Some(_) => { proc_mode = true; }
option::Option::None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb);
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new());
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{}", from_child[ii].recv());
}
}
|
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry(bb: &[u8], nn: uint, it: |window: &[u8]|) -> Vec<u8> {
let mut ii = 0u;
|
random_line_split
|
shootout-k-nucleotide-pipes.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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(slicing_syntax)]
extern crate collections;
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::string::String;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn
|
(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{} {:0.3}\n",
k.as_slice()
.to_ascii()
.to_uppercase()
.into_string(), v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii().as_slice().to_lowercase().into_string();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.pop(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry(bb: &[u8], nn: uint, it: |window: &[u8]|) -> Vec<u8> {
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
}
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
let mut line: Vec<u8>;
loop {
line = from_parent.recv();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer);
}
// given a FASTA file on stdin, process sequence THREE
fn main() {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bin!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
from_child.push(from_child_);
let (to_child, from_parent) = channel();
spawn(proc() {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
option::Option::Some(_) => { proc_mode = true; }
option::Option::None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb);
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new());
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{}", from_child[ii].recv());
}
}
|
sort_and_fmt
|
identifier_name
|
shootout-k-nucleotide-pipes.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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(slicing_syntax)]
extern crate collections;
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::string::String;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn sort_and_fmt(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{} {:0.3}\n",
k.as_slice()
.to_ascii()
.to_uppercase()
.into_string(), v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii().as_slice().to_lowercase().into_string();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.pop(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry(bb: &[u8], nn: uint, it: |window: &[u8]|) -> Vec<u8> {
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
}
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
let mut line: Vec<u8>;
loop {
line = from_parent.recv();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u =>
|
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer);
}
// given a FASTA file on stdin, process sequence THREE
fn main() {
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bin!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
from_child.push(from_child_);
let (to_child, from_parent) = channel();
spawn(proc() {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
option::Option::Some(_) => { proc_mode = true; }
option::Option::None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb);
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new());
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{}", from_child[ii].recv());
}
}
|
{ format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
|
conditional_block
|
shootout-k-nucleotide-pipes.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.
// ignore-android: FIXME(#10393)
// ignore-pretty very bad with line comments
// multi tasking k-nucleotide
#![feature(slicing_syntax)]
extern crate collections;
use std::collections::HashMap;
use std::mem::replace;
use std::num::Float;
use std::option;
use std::os;
use std::string::String;
fn f64_cmp(x: f64, y: f64) -> Ordering {
// arbitrarily decide that NaNs are larger than everything.
if y.is_nan() {
Less
} else if x.is_nan() {
Greater
} else if x < y {
Less
} else if x == y {
Equal
} else {
Greater
}
}
// given a map, print a sorted version of it
fn sort_and_fmt(mm: &HashMap<Vec<u8>, uint>, total: uint) -> String {
fn pct(xx: uint, yy: uint) -> f64 {
return (xx as f64) * 100.0 / (yy as f64);
}
// sort by key, then by value
fn sortKV(mut orig: Vec<(Vec<u8>,f64)> ) -> Vec<(Vec<u8>,f64)> {
orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));
orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));
orig
}
let mut pairs = Vec::new();
// map -> [(k,%)]
for (key, &val) in mm.iter() {
pairs.push(((*key).clone(), pct(val, total)));
}
let pairs_sorted = sortKV(pairs);
let mut buffer = String::new();
for &(ref k, v) in pairs_sorted.iter() {
buffer.push_str(format!("{} {:0.3}\n",
k.as_slice()
.to_ascii()
.to_uppercase()
.into_string(), v).as_slice());
}
return buffer
}
// given a map, search for the frequency of a pattern
fn find(mm: &HashMap<Vec<u8>, uint>, key: String) -> uint {
let key = key.into_ascii().as_slice().to_lowercase().into_string();
match mm.get(key.as_bytes()) {
option::Option::None => { return 0u; }
option::Option::Some(&num) => { return num; }
}
}
// given a map, increment the counter for a key
fn update_freq(mm: &mut HashMap<Vec<u8>, uint>, key: &[u8]) {
let key = key.to_vec();
let newval = match mm.pop(&key) {
Some(v) => v + 1,
None => 1
};
mm.insert(key, newval);
}
// given a Vec<u8>, for each window call a function
// i.e., for "hello" and windows of size four,
// run it("hell") and it("ello"), then return "llo"
fn windows_with_carry(bb: &[u8], nn: uint, it: |window: &[u8]|) -> Vec<u8> {
let mut ii = 0u;
let len = bb.len();
while ii < len - (nn - 1u) {
it(bb[ii..ii+nn]);
ii += 1u;
}
return bb[len - (nn - 1u)..len].to_vec();
}
fn make_sequence_processor(sz: uint,
from_parent: &Receiver<Vec<u8>>,
to_parent: &Sender<String>) {
let mut freqs: HashMap<Vec<u8>, uint> = HashMap::new();
let mut carry = Vec::new();
let mut total: uint = 0u;
let mut line: Vec<u8>;
loop {
line = from_parent.recv();
if line == Vec::new() { break; }
carry.push_all(line.as_slice());
carry = windows_with_carry(carry.as_slice(), sz, |window| {
update_freq(&mut freqs, window);
total += 1u;
});
}
let buffer = match sz {
1u => { sort_and_fmt(&freqs, total) }
2u => { sort_and_fmt(&freqs, total) }
3u => { format!("{}\t{}", find(&freqs, "GGT".to_string()), "GGT") }
4u => { format!("{}\t{}", find(&freqs, "GGTA".to_string()), "GGTA") }
6u => { format!("{}\t{}", find(&freqs, "GGTATT".to_string()), "GGTATT") }
12u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATT".to_string()), "GGTATTTTAATT") }
18u => { format!("{}\t{}", find(&freqs, "GGTATTTTAATTTATAGT".to_string()),
"GGTATTTTAATTTATAGT") }
_ => { "".to_string() }
};
to_parent.send(buffer);
}
// given a FASTA file on stdin, process sequence THREE
fn main()
|
from_child.push(from_child_);
let (to_child, from_parent) = channel();
spawn(proc() {
make_sequence_processor(sz, &from_parent, &to_parent_);
});
to_child
}).collect::<Vec<Sender<Vec<u8> >> >();
// latch stores true after we've started
// reading the sequence of interest
let mut proc_mode = false;
for line in rdr.lines() {
let line = line.unwrap().as_slice().trim().to_string();
if line.len() == 0u { continue; }
match (line.as_bytes()[0] as char, proc_mode) {
// start processing if this is the one
('>', false) => {
match line.as_slice().slice_from(1).find_str("THREE") {
option::Option::Some(_) => { proc_mode = true; }
option::Option::None => { }
}
}
// break our processing
('>', true) => { break; }
// process the sequence for k-mers
(_, true) => {
let line_bytes = line.as_bytes();
for (ii, _sz) in sizes.iter().enumerate() {
let lb = line_bytes.to_vec();
to_child[ii].send(lb);
}
}
// whatever
_ => { }
}
}
// finish...
for (ii, _sz) in sizes.iter().enumerate() {
to_child[ii].send(Vec::new());
}
// now fetch and print result messages
for (ii, _sz) in sizes.iter().enumerate() {
println!("{}", from_child[ii].recv());
}
}
|
{
use std::io::{stdio, MemReader, BufferedReader};
let rdr = if os::getenv("RUST_BENCH").is_some() {
let foo = include_bin!("shootout-k-nucleotide.data");
box MemReader::new(foo.to_vec()) as Box<Reader>
} else {
box stdio::stdin() as Box<Reader>
};
let mut rdr = BufferedReader::new(rdr);
// initialize each sequence sorter
let sizes = vec!(1u,2,3,4,6,12,18);
let mut streams = Vec::from_fn(sizes.len(), |_| Some(channel::<String>()));
let mut from_child = Vec::new();
let to_child = sizes.iter().zip(streams.iter_mut()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = replace(stream_ref, None);
let (to_parent_, from_child_) = stream.unwrap();
|
identifier_body
|
main_dialog.rs
|
use ui;
use user32;
use winapi::*;
use super::{RcFile,RcRoot};
use std::path::{Path,PathBuf};
use std::rc::Rc;
use std::cell::RefCell;
use wtl::ctrls::CTreeItem;
pub struct MainDlgHandler{
rc_root: Rc<RefCell<RcRoot>>,
}
impl MainDlgHandler {
pub fn new()->MainDlgHandler {
MainDlgHandler{
rc_root: Rc::new(RefCell::new(RcRoot::new())),
}
}
pub fn register_handler(&self, r: &mut ui::Root) {
r.main_dialog.this_msg().on_close(|_,_|{
unsafe{user32::PostQuitMessage(0)};
});
r.main_dialog.this_msg().on_init_dialog(|_,t|{
println!("hello main dlg");
t.main_dialog.this.SetWindowText("GUI Generator");
//t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\del\\mhc.rc");
t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\design\\design.rc");
});
let rt1 = self.rc_root.clone();
r.main_dialog.btn_parse_msg().on_click(move|_,t|{
*rt1.borrow_mut() = parse_msg(t);
});
let rt2 = self.rc_root.clone();
r.main_dialog.btn_select_msg().on_click(move|_,t|{
let mut rt = rt2.borrow_mut();
SelectDialog::call(&mut *rt,t);
});
let rt3 = self.rc_root.clone();
r.main_dialog.btn_unselect_msg().on_click(move|_,t|{
let mut rt = rt3.borrow_mut();
UnSelectDialog::call(&mut *rt,t);
});
let rt4 = self.rc_root.clone();
r.main_dialog.btn_generate_msg().on_click(move|_,t|{
let mut rt = rt4.borrow_mut();
rt.write_files();
});
}
}
////////////////////////////////////////////
// use struct here intead of mod to avoid import all mod used here
struct UnSelectDialog;
impl UnSelectDialog {
// make_path get selected dlgs in RcRoot and then make the path by given path
// all dialogs should put back to ui::Root after item deleted
// otherwise,next time make_path will not work(can't find dlgs in RcRoot)
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
let sel_txt = item.GetText();
let del_strings = Self::delete_tree(&item);
for s in &del_strings {
t.main_dialog.lst_all_dlgs.AddString(&s);
}
//rc_root.delete_path(p)
// check unselected item and it's children,if the child is dlg,then add to RcRoot and listbox;if child is other container,then just delete it
}
fn delete_child(item: &CTreeItem,item_strings: &mut Vec<String>)->bool {
if item.IsNull() {
return false;
}
//delete all children first
while Self::delete_child(&item.GetChild(), item_strings){}
let t = item.GetText();
//Root can't be deleted
if t!= "Root" {
item_strings.push(t);
item.Delete();
}
return true;
}
fn delete_tree(item: &CTreeItem) ->Vec<String> {
let mut item_strings: Vec<String> = Vec::new();
Self::delete_child(item, &mut item_strings);
item_strings
}
}
fn parse_msg(t: &mut ui::Root)->RcRoot {
//delete existing items
t.main_dialog.lst_all_dlgs.ResetContent();
//this does not work
//t.main_dialog.tree_selected_dlgs.DeleteAllItems();
//delete orignal root
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
a.Delete();
// add a new root item
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
let b = a.AddHead("Root",-1);
b.Select();
let rf = RcFile;
let p = t.main_dialog.edt_rc_path.GetWindowText();
let (mut rc_root,ids) = rf.parse_rc(&p);
// show all dialog names
for id in &ids {
t.main_dialog.lst_all_dlgs.AddString(id);
}
//*rt1.borrow_mut() = rc_root;
//assume resource.h in the same directory of.rc file
let mut header_path = PathBuf::from(Path::new(&p).parent().unwrap());
header_path.push("resource.h");
let consts = rf.parse_header(header_path.to_str().unwrap());
rc_root.set_consts(consts);
rc_root
}
struct SelectDialog;
impl SelectDialog {
fn
|
(rc_root: &mut RcRoot, t: &mut ui::Root) {
/*
items in listbox are all dialogs,when selecting a dialog,all containers in it will be added as children in tree_ctrl
items in tree_ctrl store node type(dialog/container) in itemdata
when unselect a item,the item type must be check,if the item is container then delete it directly,else push it to the listbox
*/
//get selected list item
let mut lst_sel = t.main_dialog.lst_all_dlgs.GetCurSel();
if lst_sel == -1 {
return;
}
//get text of selected item
let lst_sel_txt = t.main_dialog.lst_all_dlgs.GetText(lst_sel);
//delete the selected item in listbox
t.main_dialog.lst_all_dlgs.DeleteString(lst_sel as UINT);
//select the item before the deleted one
if lst_sel > 0 {
lst_sel -= 1;
}
//do selection
t.main_dialog.lst_all_dlgs.SetCurSel(lst_sel);
//get selected item of tree_ctrl
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
//add the selected item in listbox to the tree_ctrl
//return the item inserted just now
let new_item = item.AddTail(&lst_sel_txt,-1);
//get abs path of the selected item in tree_view
let mut path = Self::get_item_path(&item);
println!("{:?}", path);
let child_container = rc_root.make_path(&lst_sel_txt,&mut path);
// if the selected item has child container,then add to the tree_view
for c in child_container {
new_item.AddTail(&c,-1);
}
//println!("{}", rc_root);
rc_root.print();
//check if the container has child containers
//expand the button of a new item manually
//http://www.go4expert.com/forums/i-refresh-expand-sign-treeview-control-t15764/
item.Expand(None);
}
//e.g [Root,IDD_MAIN_DIALOG,IDD_ABOUT_DLG]
fn get_item_path(item: &CTreeItem)->Vec<String> {
let parent = item.GetParent();
if parent.IsNull() {
//Root
let mut v = Vec::new();
v.push(item.GetText());
return v;
}
let mut v = Self::get_item_path(&parent);
v.push(item.GetText());
v
}
}
|
call
|
identifier_name
|
main_dialog.rs
|
use ui;
use user32;
use winapi::*;
use super::{RcFile,RcRoot};
use std::path::{Path,PathBuf};
use std::rc::Rc;
use std::cell::RefCell;
use wtl::ctrls::CTreeItem;
pub struct MainDlgHandler{
rc_root: Rc<RefCell<RcRoot>>,
}
impl MainDlgHandler {
pub fn new()->MainDlgHandler {
MainDlgHandler{
rc_root: Rc::new(RefCell::new(RcRoot::new())),
}
}
pub fn register_handler(&self, r: &mut ui::Root) {
r.main_dialog.this_msg().on_close(|_,_|{
unsafe{user32::PostQuitMessage(0)};
});
r.main_dialog.this_msg().on_init_dialog(|_,t|{
println!("hello main dlg");
t.main_dialog.this.SetWindowText("GUI Generator");
//t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\del\\mhc.rc");
t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\design\\design.rc");
});
let rt1 = self.rc_root.clone();
r.main_dialog.btn_parse_msg().on_click(move|_,t|{
*rt1.borrow_mut() = parse_msg(t);
});
let rt2 = self.rc_root.clone();
r.main_dialog.btn_select_msg().on_click(move|_,t|{
let mut rt = rt2.borrow_mut();
SelectDialog::call(&mut *rt,t);
});
let rt3 = self.rc_root.clone();
r.main_dialog.btn_unselect_msg().on_click(move|_,t|{
let mut rt = rt3.borrow_mut();
UnSelectDialog::call(&mut *rt,t);
});
let rt4 = self.rc_root.clone();
r.main_dialog.btn_generate_msg().on_click(move|_,t|{
let mut rt = rt4.borrow_mut();
rt.write_files();
});
}
}
////////////////////////////////////////////
// use struct here intead of mod to avoid import all mod used here
struct UnSelectDialog;
impl UnSelectDialog {
// make_path get selected dlgs in RcRoot and then make the path by given path
// all dialogs should put back to ui::Root after item deleted
// otherwise,next time make_path will not work(can't find dlgs in RcRoot)
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
let sel_txt = item.GetText();
let del_strings = Self::delete_tree(&item);
for s in &del_strings {
t.main_dialog.lst_all_dlgs.AddString(&s);
}
//rc_root.delete_path(p)
// check unselected item and it's children,if the child is dlg,then add to RcRoot and listbox;if child is other container,then just delete it
}
fn delete_child(item: &CTreeItem,item_strings: &mut Vec<String>)->bool {
if item.IsNull() {
return false;
}
//delete all children first
while Self::delete_child(&item.GetChild(), item_strings){}
|
item_strings.push(t);
item.Delete();
}
return true;
}
fn delete_tree(item: &CTreeItem) ->Vec<String> {
let mut item_strings: Vec<String> = Vec::new();
Self::delete_child(item, &mut item_strings);
item_strings
}
}
fn parse_msg(t: &mut ui::Root)->RcRoot {
//delete existing items
t.main_dialog.lst_all_dlgs.ResetContent();
//this does not work
//t.main_dialog.tree_selected_dlgs.DeleteAllItems();
//delete orignal root
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
a.Delete();
// add a new root item
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
let b = a.AddHead("Root",-1);
b.Select();
let rf = RcFile;
let p = t.main_dialog.edt_rc_path.GetWindowText();
let (mut rc_root,ids) = rf.parse_rc(&p);
// show all dialog names
for id in &ids {
t.main_dialog.lst_all_dlgs.AddString(id);
}
//*rt1.borrow_mut() = rc_root;
//assume resource.h in the same directory of.rc file
let mut header_path = PathBuf::from(Path::new(&p).parent().unwrap());
header_path.push("resource.h");
let consts = rf.parse_header(header_path.to_str().unwrap());
rc_root.set_consts(consts);
rc_root
}
struct SelectDialog;
impl SelectDialog {
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
/*
items in listbox are all dialogs,when selecting a dialog,all containers in it will be added as children in tree_ctrl
items in tree_ctrl store node type(dialog/container) in itemdata
when unselect a item,the item type must be check,if the item is container then delete it directly,else push it to the listbox
*/
//get selected list item
let mut lst_sel = t.main_dialog.lst_all_dlgs.GetCurSel();
if lst_sel == -1 {
return;
}
//get text of selected item
let lst_sel_txt = t.main_dialog.lst_all_dlgs.GetText(lst_sel);
//delete the selected item in listbox
t.main_dialog.lst_all_dlgs.DeleteString(lst_sel as UINT);
//select the item before the deleted one
if lst_sel > 0 {
lst_sel -= 1;
}
//do selection
t.main_dialog.lst_all_dlgs.SetCurSel(lst_sel);
//get selected item of tree_ctrl
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
//add the selected item in listbox to the tree_ctrl
//return the item inserted just now
let new_item = item.AddTail(&lst_sel_txt,-1);
//get abs path of the selected item in tree_view
let mut path = Self::get_item_path(&item);
println!("{:?}", path);
let child_container = rc_root.make_path(&lst_sel_txt,&mut path);
// if the selected item has child container,then add to the tree_view
for c in child_container {
new_item.AddTail(&c,-1);
}
//println!("{}", rc_root);
rc_root.print();
//check if the container has child containers
//expand the button of a new item manually
//http://www.go4expert.com/forums/i-refresh-expand-sign-treeview-control-t15764/
item.Expand(None);
}
//e.g [Root,IDD_MAIN_DIALOG,IDD_ABOUT_DLG]
fn get_item_path(item: &CTreeItem)->Vec<String> {
let parent = item.GetParent();
if parent.IsNull() {
//Root
let mut v = Vec::new();
v.push(item.GetText());
return v;
}
let mut v = Self::get_item_path(&parent);
v.push(item.GetText());
v
}
}
|
let t = item.GetText();
//Root can't be deleted
if t != "Root" {
|
random_line_split
|
main_dialog.rs
|
use ui;
use user32;
use winapi::*;
use super::{RcFile,RcRoot};
use std::path::{Path,PathBuf};
use std::rc::Rc;
use std::cell::RefCell;
use wtl::ctrls::CTreeItem;
pub struct MainDlgHandler{
rc_root: Rc<RefCell<RcRoot>>,
}
impl MainDlgHandler {
pub fn new()->MainDlgHandler {
MainDlgHandler{
rc_root: Rc::new(RefCell::new(RcRoot::new())),
}
}
pub fn register_handler(&self, r: &mut ui::Root)
|
let mut rt = rt2.borrow_mut();
SelectDialog::call(&mut *rt,t);
});
let rt3 = self.rc_root.clone();
r.main_dialog.btn_unselect_msg().on_click(move|_,t|{
let mut rt = rt3.borrow_mut();
UnSelectDialog::call(&mut *rt,t);
});
let rt4 = self.rc_root.clone();
r.main_dialog.btn_generate_msg().on_click(move|_,t|{
let mut rt = rt4.borrow_mut();
rt.write_files();
});
}
}
////////////////////////////////////////////
// use struct here intead of mod to avoid import all mod used here
struct UnSelectDialog;
impl UnSelectDialog {
// make_path get selected dlgs in RcRoot and then make the path by given path
// all dialogs should put back to ui::Root after item deleted
// otherwise,next time make_path will not work(can't find dlgs in RcRoot)
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
let sel_txt = item.GetText();
let del_strings = Self::delete_tree(&item);
for s in &del_strings {
t.main_dialog.lst_all_dlgs.AddString(&s);
}
//rc_root.delete_path(p)
// check unselected item and it's children,if the child is dlg,then add to RcRoot and listbox;if child is other container,then just delete it
}
fn delete_child(item: &CTreeItem,item_strings: &mut Vec<String>)->bool {
if item.IsNull() {
return false;
}
//delete all children first
while Self::delete_child(&item.GetChild(), item_strings){}
let t = item.GetText();
//Root can't be deleted
if t!= "Root" {
item_strings.push(t);
item.Delete();
}
return true;
}
fn delete_tree(item: &CTreeItem) ->Vec<String> {
let mut item_strings: Vec<String> = Vec::new();
Self::delete_child(item, &mut item_strings);
item_strings
}
}
fn parse_msg(t: &mut ui::Root)->RcRoot {
//delete existing items
t.main_dialog.lst_all_dlgs.ResetContent();
//this does not work
//t.main_dialog.tree_selected_dlgs.DeleteAllItems();
//delete orignal root
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
a.Delete();
// add a new root item
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
let b = a.AddHead("Root",-1);
b.Select();
let rf = RcFile;
let p = t.main_dialog.edt_rc_path.GetWindowText();
let (mut rc_root,ids) = rf.parse_rc(&p);
// show all dialog names
for id in &ids {
t.main_dialog.lst_all_dlgs.AddString(id);
}
//*rt1.borrow_mut() = rc_root;
//assume resource.h in the same directory of.rc file
let mut header_path = PathBuf::from(Path::new(&p).parent().unwrap());
header_path.push("resource.h");
let consts = rf.parse_header(header_path.to_str().unwrap());
rc_root.set_consts(consts);
rc_root
}
struct SelectDialog;
impl SelectDialog {
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
/*
items in listbox are all dialogs,when selecting a dialog,all containers in it will be added as children in tree_ctrl
items in tree_ctrl store node type(dialog/container) in itemdata
when unselect a item,the item type must be check,if the item is container then delete it directly,else push it to the listbox
*/
//get selected list item
let mut lst_sel = t.main_dialog.lst_all_dlgs.GetCurSel();
if lst_sel == -1 {
return;
}
//get text of selected item
let lst_sel_txt = t.main_dialog.lst_all_dlgs.GetText(lst_sel);
//delete the selected item in listbox
t.main_dialog.lst_all_dlgs.DeleteString(lst_sel as UINT);
//select the item before the deleted one
if lst_sel > 0 {
lst_sel -= 1;
}
//do selection
t.main_dialog.lst_all_dlgs.SetCurSel(lst_sel);
//get selected item of tree_ctrl
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
//add the selected item in listbox to the tree_ctrl
//return the item inserted just now
let new_item = item.AddTail(&lst_sel_txt,-1);
//get abs path of the selected item in tree_view
let mut path = Self::get_item_path(&item);
println!("{:?}", path);
let child_container = rc_root.make_path(&lst_sel_txt,&mut path);
// if the selected item has child container,then add to the tree_view
for c in child_container {
new_item.AddTail(&c,-1);
}
//println!("{}", rc_root);
rc_root.print();
//check if the container has child containers
//expand the button of a new item manually
//http://www.go4expert.com/forums/i-refresh-expand-sign-treeview-control-t15764/
item.Expand(None);
}
//e.g [Root,IDD_MAIN_DIALOG,IDD_ABOUT_DLG]
fn get_item_path(item: &CTreeItem)->Vec<String> {
let parent = item.GetParent();
if parent.IsNull() {
//Root
let mut v = Vec::new();
v.push(item.GetText());
return v;
}
let mut v = Self::get_item_path(&parent);
v.push(item.GetText());
v
}
}
|
{
r.main_dialog.this_msg().on_close(|_,_|{
unsafe{user32::PostQuitMessage(0)};
});
r.main_dialog.this_msg().on_init_dialog(|_,t|{
println!("hello main dlg");
t.main_dialog.this.SetWindowText("GUI Generator");
//t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\del\\mhc.rc");
t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\design\\design.rc");
});
let rt1 = self.rc_root.clone();
r.main_dialog.btn_parse_msg().on_click(move|_,t|{
*rt1.borrow_mut() = parse_msg(t);
});
let rt2 = self.rc_root.clone();
r.main_dialog.btn_select_msg().on_click(move|_,t|{
|
identifier_body
|
main_dialog.rs
|
use ui;
use user32;
use winapi::*;
use super::{RcFile,RcRoot};
use std::path::{Path,PathBuf};
use std::rc::Rc;
use std::cell::RefCell;
use wtl::ctrls::CTreeItem;
pub struct MainDlgHandler{
rc_root: Rc<RefCell<RcRoot>>,
}
impl MainDlgHandler {
pub fn new()->MainDlgHandler {
MainDlgHandler{
rc_root: Rc::new(RefCell::new(RcRoot::new())),
}
}
pub fn register_handler(&self, r: &mut ui::Root) {
r.main_dialog.this_msg().on_close(|_,_|{
unsafe{user32::PostQuitMessage(0)};
});
r.main_dialog.this_msg().on_init_dialog(|_,t|{
println!("hello main dlg");
t.main_dialog.this.SetWindowText("GUI Generator");
//t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\del\\mhc.rc");
t.main_dialog.edt_rc_path.SetWindowText("K:\\software\\pc\\rust\\wtl-rs\\tools\\ui_gen\\src\\design\\design.rc");
});
let rt1 = self.rc_root.clone();
r.main_dialog.btn_parse_msg().on_click(move|_,t|{
*rt1.borrow_mut() = parse_msg(t);
});
let rt2 = self.rc_root.clone();
r.main_dialog.btn_select_msg().on_click(move|_,t|{
let mut rt = rt2.borrow_mut();
SelectDialog::call(&mut *rt,t);
});
let rt3 = self.rc_root.clone();
r.main_dialog.btn_unselect_msg().on_click(move|_,t|{
let mut rt = rt3.borrow_mut();
UnSelectDialog::call(&mut *rt,t);
});
let rt4 = self.rc_root.clone();
r.main_dialog.btn_generate_msg().on_click(move|_,t|{
let mut rt = rt4.borrow_mut();
rt.write_files();
});
}
}
////////////////////////////////////////////
// use struct here intead of mod to avoid import all mod used here
struct UnSelectDialog;
impl UnSelectDialog {
// make_path get selected dlgs in RcRoot and then make the path by given path
// all dialogs should put back to ui::Root after item deleted
// otherwise,next time make_path will not work(can't find dlgs in RcRoot)
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
let sel_txt = item.GetText();
let del_strings = Self::delete_tree(&item);
for s in &del_strings {
t.main_dialog.lst_all_dlgs.AddString(&s);
}
//rc_root.delete_path(p)
// check unselected item and it's children,if the child is dlg,then add to RcRoot and listbox;if child is other container,then just delete it
}
fn delete_child(item: &CTreeItem,item_strings: &mut Vec<String>)->bool {
if item.IsNull() {
return false;
}
//delete all children first
while Self::delete_child(&item.GetChild(), item_strings){}
let t = item.GetText();
//Root can't be deleted
if t!= "Root" {
item_strings.push(t);
item.Delete();
}
return true;
}
fn delete_tree(item: &CTreeItem) ->Vec<String> {
let mut item_strings: Vec<String> = Vec::new();
Self::delete_child(item, &mut item_strings);
item_strings
}
}
fn parse_msg(t: &mut ui::Root)->RcRoot {
//delete existing items
t.main_dialog.lst_all_dlgs.ResetContent();
//this does not work
//t.main_dialog.tree_selected_dlgs.DeleteAllItems();
//delete orignal root
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
a.Delete();
// add a new root item
let a = t.main_dialog.tree_selected_dlgs.GetRootItem();
let b = a.AddHead("Root",-1);
b.Select();
let rf = RcFile;
let p = t.main_dialog.edt_rc_path.GetWindowText();
let (mut rc_root,ids) = rf.parse_rc(&p);
// show all dialog names
for id in &ids {
t.main_dialog.lst_all_dlgs.AddString(id);
}
//*rt1.borrow_mut() = rc_root;
//assume resource.h in the same directory of.rc file
let mut header_path = PathBuf::from(Path::new(&p).parent().unwrap());
header_path.push("resource.h");
let consts = rf.parse_header(header_path.to_str().unwrap());
rc_root.set_consts(consts);
rc_root
}
struct SelectDialog;
impl SelectDialog {
fn call(rc_root: &mut RcRoot, t: &mut ui::Root) {
/*
items in listbox are all dialogs,when selecting a dialog,all containers in it will be added as children in tree_ctrl
items in tree_ctrl store node type(dialog/container) in itemdata
when unselect a item,the item type must be check,if the item is container then delete it directly,else push it to the listbox
*/
//get selected list item
let mut lst_sel = t.main_dialog.lst_all_dlgs.GetCurSel();
if lst_sel == -1 {
return;
}
//get text of selected item
let lst_sel_txt = t.main_dialog.lst_all_dlgs.GetText(lst_sel);
//delete the selected item in listbox
t.main_dialog.lst_all_dlgs.DeleteString(lst_sel as UINT);
//select the item before the deleted one
if lst_sel > 0 {
lst_sel -= 1;
}
//do selection
t.main_dialog.lst_all_dlgs.SetCurSel(lst_sel);
//get selected item of tree_ctrl
let item = t.main_dialog.tree_selected_dlgs.GetSelectedItem();
//add the selected item in listbox to the tree_ctrl
//return the item inserted just now
let new_item = item.AddTail(&lst_sel_txt,-1);
//get abs path of the selected item in tree_view
let mut path = Self::get_item_path(&item);
println!("{:?}", path);
let child_container = rc_root.make_path(&lst_sel_txt,&mut path);
// if the selected item has child container,then add to the tree_view
for c in child_container {
new_item.AddTail(&c,-1);
}
//println!("{}", rc_root);
rc_root.print();
//check if the container has child containers
//expand the button of a new item manually
//http://www.go4expert.com/forums/i-refresh-expand-sign-treeview-control-t15764/
item.Expand(None);
}
//e.g [Root,IDD_MAIN_DIALOG,IDD_ABOUT_DLG]
fn get_item_path(item: &CTreeItem)->Vec<String> {
let parent = item.GetParent();
if parent.IsNull()
|
let mut v = Self::get_item_path(&parent);
v.push(item.GetText());
v
}
}
|
{
//Root
let mut v = Vec::new();
v.push(item.GetText());
return v;
}
|
conditional_block
|
rust.rs
|
// Location of the person
struct Location {
lat: float64,
long: float64,
}
// An application
struct Web {
name: String,
url: String,
}
// An simple author element with some description
struct Author {
title: String,
email: String,
categories: Vec<String>,
locations: Vec<Location>,
origin: Location,
}
type Meta = HashMap<String, String>() {
}
// An general news entry
struct News {
config: Meta,
inlineConfig: HashMap<String, String>,
tags: Vec<String>,
receiver: Vec<Author>,
resources: Vec<Object>,
profileImage: String,
read: bool,
source: Object,
author: Author,
meta: Meta,
sendDate: time.Time,
readDate: time.Time,
expires: time.Duration,
|
question: String,
version: String,
coffeeTime: time.Time,
profileUri: String,
captcha: String,
payload: Object,
}
|
price: float64,
rating: u64,
content: String,
|
random_line_split
|
rust.rs
|
// Location of the person
struct Location {
lat: float64,
long: float64,
}
// An application
struct Web {
name: String,
url: String,
}
// An simple author element with some description
struct Author {
title: String,
email: String,
categories: Vec<String>,
locations: Vec<Location>,
origin: Location,
}
type Meta = HashMap<String, String>() {
}
// An general news entry
struct
|
{
config: Meta,
inlineConfig: HashMap<String, String>,
tags: Vec<String>,
receiver: Vec<Author>,
resources: Vec<Object>,
profileImage: String,
read: bool,
source: Object,
author: Author,
meta: Meta,
sendDate: time.Time,
readDate: time.Time,
expires: time.Duration,
price: float64,
rating: u64,
content: String,
question: String,
version: String,
coffeeTime: time.Time,
profileUri: String,
captcha: String,
payload: Object,
}
|
News
|
identifier_name
|
day17.rs
|
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use itertools::MinMaxResult;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Default)]
pub struct Day17 {
clays: HashSet<Coordinate>,
flowing: HashSet<Coordinate>,
contained: HashSet<Coordinate>,
ymin: usize,
ymax: usize,
}
impl Day17 {
pub fn new() -> Self {
Default::default()
}
fn read_input(&mut self, input: &mut dyn Read) {
let matcher = Regex::new(r"(.)=(\d+), (.)=(\d+)\.\.(\d+)").unwrap();
let reader = BufReader::new(input);
for line in reader.lines() {
let line = line.unwrap();
let captures = matcher.captures(&line).unwrap();
let fixed: usize = captures[2].parse().unwrap();
let a: usize = captures[4].parse().unwrap();
let b: usize = captures[5].parse().unwrap();
match &captures[1] {
"x" => {
for y in a..=b {
self.clays.insert((fixed, y));
}
}
"y" => {
for x in a..=b {
self.clays.insert((x, fixed));
}
}
_ => panic!(),
}
}
match self.clays.iter().map(|(_, y)| y).minmax() {
MinMaxResult::MinMax(a, b) => {
self.ymin = *a;
self.ymax = *b;
}
_ => panic!(),
};
}
fn support_end<T>(&mut self, center: usize, range: T, y: usize) -> (usize, bool)
where
T: Iterator<Item = usize>,
{
let mut prev = center;
for x in range {
let pos = (x, y);
if self.clays.contains(&pos) {
return (prev, true);
}
prev = x;
let below = (x, y + 1);
self.descend(below);
if!self.is_supported(&below) {
return (x, false);
}
}
unreachable!();
}
fn is_supported(&self, pos: &Coordinate) -> bool {
self.clays.contains(pos) || self.contained.contains(pos)
}
fn descend(&mut self, pos: Coordinate)
|
if left_contained && right_contained {
self.contained.extend(range);
} else {
self.flowing.extend(range);
}
} else {
self.flowing.insert(pos);
}
}
}
impl Solution for Day17 {
fn part1(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
let result = self.contained.len() + self.flowing.len() - self.ymin;
result.to_string()
}
fn part2(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
self.contained.len().to_string()
}
}
#[cfg(test)]
mod tests {
use common::Solution;
use day17::Day17;
const SAMPLE_INPUT: &[u8] = include_bytes!("samples/17.txt");
#[test]
fn sample_part1() {
let mut instance = Day17::new();
assert_eq!("57", instance.part1(&mut SAMPLE_INPUT));
}
#[test]
fn sample_part2() {
let mut instance = Day17::new();
assert_eq!("29", instance.part2(&mut SAMPLE_INPUT));
}
}
|
{
let (x, y) = pos;
if y > self.ymax
|| self.clays.contains(&pos)
|| self.flowing.contains(&pos)
|| self.contained.contains(&pos)
{
return;
}
let below = (x, y + 1);
self.descend(below);
if self.is_supported(&below) {
let (right, right_contained) = self.support_end(x, (x + 1).., y);
let (left, left_contained) = self.support_end(x, (0..x).rev(), y);
let range = (left..=right).map(|x| (x, y));
|
identifier_body
|
day17.rs
|
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use itertools::MinMaxResult;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Default)]
pub struct Day17 {
clays: HashSet<Coordinate>,
flowing: HashSet<Coordinate>,
contained: HashSet<Coordinate>,
ymin: usize,
ymax: usize,
}
impl Day17 {
pub fn new() -> Self {
Default::default()
}
fn read_input(&mut self, input: &mut dyn Read) {
let matcher = Regex::new(r"(.)=(\d+), (.)=(\d+)\.\.(\d+)").unwrap();
let reader = BufReader::new(input);
for line in reader.lines() {
let line = line.unwrap();
let captures = matcher.captures(&line).unwrap();
let fixed: usize = captures[2].parse().unwrap();
let a: usize = captures[4].parse().unwrap();
let b: usize = captures[5].parse().unwrap();
match &captures[1] {
"x" => {
for y in a..=b {
self.clays.insert((fixed, y));
}
}
"y" => {
for x in a..=b {
self.clays.insert((x, fixed));
}
}
_ => panic!(),
}
}
match self.clays.iter().map(|(_, y)| y).minmax() {
MinMaxResult::MinMax(a, b) => {
self.ymin = *a;
self.ymax = *b;
}
_ => panic!(),
};
}
fn support_end<T>(&mut self, center: usize, range: T, y: usize) -> (usize, bool)
where
T: Iterator<Item = usize>,
{
let mut prev = center;
for x in range {
let pos = (x, y);
if self.clays.contains(&pos) {
return (prev, true);
}
prev = x;
let below = (x, y + 1);
self.descend(below);
if!self.is_supported(&below) {
return (x, false);
}
}
unreachable!();
}
fn is_supported(&self, pos: &Coordinate) -> bool {
self.clays.contains(pos) || self.contained.contains(pos)
}
fn descend(&mut self, pos: Coordinate) {
let (x, y) = pos;
if y > self.ymax
|| self.clays.contains(&pos)
|| self.flowing.contains(&pos)
|| self.contained.contains(&pos)
{
return;
}
let below = (x, y + 1);
self.descend(below);
if self.is_supported(&below)
|
else {
self.flowing.insert(pos);
}
}
}
impl Solution for Day17 {
fn part1(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
let result = self.contained.len() + self.flowing.len() - self.ymin;
result.to_string()
}
fn part2(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
self.contained.len().to_string()
}
}
#[cfg(test)]
mod tests {
use common::Solution;
use day17::Day17;
const SAMPLE_INPUT: &[u8] = include_bytes!("samples/17.txt");
#[test]
fn sample_part1() {
let mut instance = Day17::new();
assert_eq!("57", instance.part1(&mut SAMPLE_INPUT));
}
#[test]
fn sample_part2() {
let mut instance = Day17::new();
assert_eq!("29", instance.part2(&mut SAMPLE_INPUT));
}
}
|
{
let (right, right_contained) = self.support_end(x, (x + 1).., y);
let (left, left_contained) = self.support_end(x, (0..x).rev(), y);
let range = (left..=right).map(|x| (x, y));
if left_contained && right_contained {
self.contained.extend(range);
} else {
self.flowing.extend(range);
}
}
|
conditional_block
|
day17.rs
|
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use itertools::MinMaxResult;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Default)]
pub struct Day17 {
clays: HashSet<Coordinate>,
flowing: HashSet<Coordinate>,
contained: HashSet<Coordinate>,
ymin: usize,
ymax: usize,
}
impl Day17 {
pub fn new() -> Self {
Default::default()
}
fn read_input(&mut self, input: &mut dyn Read) {
let matcher = Regex::new(r"(.)=(\d+), (.)=(\d+)\.\.(\d+)").unwrap();
let reader = BufReader::new(input);
for line in reader.lines() {
let line = line.unwrap();
let captures = matcher.captures(&line).unwrap();
let fixed: usize = captures[2].parse().unwrap();
let a: usize = captures[4].parse().unwrap();
let b: usize = captures[5].parse().unwrap();
match &captures[1] {
"x" => {
for y in a..=b {
self.clays.insert((fixed, y));
}
}
"y" => {
for x in a..=b {
self.clays.insert((x, fixed));
}
}
_ => panic!(),
}
}
match self.clays.iter().map(|(_, y)| y).minmax() {
MinMaxResult::MinMax(a, b) => {
self.ymin = *a;
self.ymax = *b;
}
_ => panic!(),
};
}
fn support_end<T>(&mut self, center: usize, range: T, y: usize) -> (usize, bool)
where
T: Iterator<Item = usize>,
{
let mut prev = center;
for x in range {
let pos = (x, y);
if self.clays.contains(&pos) {
return (prev, true);
}
prev = x;
let below = (x, y + 1);
self.descend(below);
if!self.is_supported(&below) {
return (x, false);
}
}
unreachable!();
}
fn is_supported(&self, pos: &Coordinate) -> bool {
self.clays.contains(pos) || self.contained.contains(pos)
}
fn descend(&mut self, pos: Coordinate) {
let (x, y) = pos;
if y > self.ymax
|| self.clays.contains(&pos)
|| self.flowing.contains(&pos)
|| self.contained.contains(&pos)
{
return;
}
let below = (x, y + 1);
self.descend(below);
if self.is_supported(&below) {
let (right, right_contained) = self.support_end(x, (x + 1).., y);
let (left, left_contained) = self.support_end(x, (0..x).rev(), y);
let range = (left..=right).map(|x| (x, y));
if left_contained && right_contained {
self.contained.extend(range);
} else {
self.flowing.extend(range);
}
} else {
self.flowing.insert(pos);
}
}
}
impl Solution for Day17 {
fn
|
(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
let result = self.contained.len() + self.flowing.len() - self.ymin;
result.to_string()
}
fn part2(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
self.contained.len().to_string()
}
}
#[cfg(test)]
mod tests {
use common::Solution;
use day17::Day17;
const SAMPLE_INPUT: &[u8] = include_bytes!("samples/17.txt");
#[test]
fn sample_part1() {
let mut instance = Day17::new();
assert_eq!("57", instance.part1(&mut SAMPLE_INPUT));
}
#[test]
fn sample_part2() {
let mut instance = Day17::new();
assert_eq!("29", instance.part2(&mut SAMPLE_INPUT));
}
}
|
part1
|
identifier_name
|
day17.rs
|
use std::collections::HashSet;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Read;
use itertools::Itertools;
use itertools::MinMaxResult;
use regex::Regex;
use common::Solution;
type Coordinate = (usize, usize);
#[derive(Default)]
pub struct Day17 {
clays: HashSet<Coordinate>,
flowing: HashSet<Coordinate>,
contained: HashSet<Coordinate>,
ymin: usize,
ymax: usize,
}
impl Day17 {
pub fn new() -> Self {
Default::default()
}
fn read_input(&mut self, input: &mut dyn Read) {
let matcher = Regex::new(r"(.)=(\d+), (.)=(\d+)\.\.(\d+)").unwrap();
let reader = BufReader::new(input);
for line in reader.lines() {
let line = line.unwrap();
let captures = matcher.captures(&line).unwrap();
let fixed: usize = captures[2].parse().unwrap();
let a: usize = captures[4].parse().unwrap();
let b: usize = captures[5].parse().unwrap();
match &captures[1] {
"x" => {
for y in a..=b {
self.clays.insert((fixed, y));
}
}
"y" => {
for x in a..=b {
self.clays.insert((x, fixed));
}
}
_ => panic!(),
}
}
match self.clays.iter().map(|(_, y)| y).minmax() {
MinMaxResult::MinMax(a, b) => {
self.ymin = *a;
self.ymax = *b;
}
_ => panic!(),
};
}
fn support_end<T>(&mut self, center: usize, range: T, y: usize) -> (usize, bool)
where
T: Iterator<Item = usize>,
{
let mut prev = center;
for x in range {
let pos = (x, y);
if self.clays.contains(&pos) {
return (prev, true);
}
prev = x;
let below = (x, y + 1);
self.descend(below);
if!self.is_supported(&below) {
return (x, false);
}
}
|
}
fn is_supported(&self, pos: &Coordinate) -> bool {
self.clays.contains(pos) || self.contained.contains(pos)
}
fn descend(&mut self, pos: Coordinate) {
let (x, y) = pos;
if y > self.ymax
|| self.clays.contains(&pos)
|| self.flowing.contains(&pos)
|| self.contained.contains(&pos)
{
return;
}
let below = (x, y + 1);
self.descend(below);
if self.is_supported(&below) {
let (right, right_contained) = self.support_end(x, (x + 1).., y);
let (left, left_contained) = self.support_end(x, (0..x).rev(), y);
let range = (left..=right).map(|x| (x, y));
if left_contained && right_contained {
self.contained.extend(range);
} else {
self.flowing.extend(range);
}
} else {
self.flowing.insert(pos);
}
}
}
impl Solution for Day17 {
fn part1(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
let result = self.contained.len() + self.flowing.len() - self.ymin;
result.to_string()
}
fn part2(&mut self, input: &mut dyn Read) -> String {
self.read_input(input);
self.descend((500, 0));
self.contained.len().to_string()
}
}
#[cfg(test)]
mod tests {
use common::Solution;
use day17::Day17;
const SAMPLE_INPUT: &[u8] = include_bytes!("samples/17.txt");
#[test]
fn sample_part1() {
let mut instance = Day17::new();
assert_eq!("57", instance.part1(&mut SAMPLE_INPUT));
}
#[test]
fn sample_part2() {
let mut instance = Day17::new();
assert_eq!("29", instance.part2(&mut SAMPLE_INPUT));
}
}
|
unreachable!();
|
random_line_split
|
version.rs
|
use crate::config::{Config, Container};
use crate::build_step::{BuildStep, Digest};
use super::error::Error;
#[cfg(feature="containers")]
fn
|
(container: &Container, cfg: &Config, debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
debug!("Versioning items: {}", container.setup.len());
let mut hash = Digest::new(debug_info, dump);
hash.field("uids", &container.uids);
hash.field("gids", &container.gids);
for b in container.setup.iter() {
debug!("Versioning setup: {:?}", b);
hash.command(b.name());
b.hash(&cfg, &mut hash).map_err(|e| (format!("{:?}", b), e))?;
}
if!container.data_dirs.is_empty() {
hash.field("data_dirs", &container.data_dirs);
}
if debug_info {
hash.print_debug_info();
}
if dump {
hash.dump_info();
}
Ok(format!("{:x}", hash))
}
#[cfg(feature="containers")]
pub fn short_version(container: &Container, cfg: &Config)
-> Result<String, (String, Error)>
{
let hash_str = all(container, cfg, false, false)?;
Ok(hash_str[..8].to_string())
}
#[cfg(feature="containers")]
pub fn long_version(container: &Container, cfg: &Config,
debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
let hash_str = all(&container, cfg, debug_info, dump)?;
Ok(hash_str)
}
|
all
|
identifier_name
|
version.rs
|
use crate::config::{Config, Container};
use crate::build_step::{BuildStep, Digest};
use super::error::Error;
#[cfg(feature="containers")]
fn all(container: &Container, cfg: &Config, debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
debug!("Versioning items: {}", container.setup.len());
let mut hash = Digest::new(debug_info, dump);
hash.field("uids", &container.uids);
hash.field("gids", &container.gids);
for b in container.setup.iter() {
debug!("Versioning setup: {:?}", b);
hash.command(b.name());
b.hash(&cfg, &mut hash).map_err(|e| (format!("{:?}", b), e))?;
}
if!container.data_dirs.is_empty()
|
if debug_info {
hash.print_debug_info();
}
if dump {
hash.dump_info();
}
Ok(format!("{:x}", hash))
}
#[cfg(feature="containers")]
pub fn short_version(container: &Container, cfg: &Config)
-> Result<String, (String, Error)>
{
let hash_str = all(container, cfg, false, false)?;
Ok(hash_str[..8].to_string())
}
#[cfg(feature="containers")]
pub fn long_version(container: &Container, cfg: &Config,
debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
let hash_str = all(&container, cfg, debug_info, dump)?;
Ok(hash_str)
}
|
{
hash.field("data_dirs", &container.data_dirs);
}
|
conditional_block
|
version.rs
|
use crate::config::{Config, Container};
use crate::build_step::{BuildStep, Digest};
use super::error::Error;
#[cfg(feature="containers")]
fn all(container: &Container, cfg: &Config, debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
debug!("Versioning items: {}", container.setup.len());
let mut hash = Digest::new(debug_info, dump);
hash.field("uids", &container.uids);
hash.field("gids", &container.gids);
for b in container.setup.iter() {
debug!("Versioning setup: {:?}", b);
hash.command(b.name());
b.hash(&cfg, &mut hash).map_err(|e| (format!("{:?}", b), e))?;
}
if!container.data_dirs.is_empty() {
hash.field("data_dirs", &container.data_dirs);
}
if debug_info {
hash.print_debug_info();
}
if dump {
hash.dump_info();
}
Ok(format!("{:x}", hash))
}
#[cfg(feature="containers")]
pub fn short_version(container: &Container, cfg: &Config)
-> Result<String, (String, Error)>
|
#[cfg(feature="containers")]
pub fn long_version(container: &Container, cfg: &Config,
debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
let hash_str = all(&container, cfg, debug_info, dump)?;
Ok(hash_str)
}
|
{
let hash_str = all(container, cfg, false, false)?;
Ok(hash_str[..8].to_string())
}
|
identifier_body
|
version.rs
|
use crate::config::{Config, Container};
use crate::build_step::{BuildStep, Digest};
use super::error::Error;
#[cfg(feature="containers")]
fn all(container: &Container, cfg: &Config, debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
debug!("Versioning items: {}", container.setup.len());
let mut hash = Digest::new(debug_info, dump);
hash.field("uids", &container.uids);
hash.field("gids", &container.gids);
for b in container.setup.iter() {
debug!("Versioning setup: {:?}", b);
hash.command(b.name());
b.hash(&cfg, &mut hash).map_err(|e| (format!("{:?}", b), e))?;
}
if!container.data_dirs.is_empty() {
hash.field("data_dirs", &container.data_dirs);
}
if debug_info {
hash.print_debug_info();
}
if dump {
hash.dump_info();
}
Ok(format!("{:x}", hash))
}
#[cfg(feature="containers")]
pub fn short_version(container: &Container, cfg: &Config)
|
{
let hash_str = all(container, cfg, false, false)?;
Ok(hash_str[..8].to_string())
}
#[cfg(feature="containers")]
pub fn long_version(container: &Container, cfg: &Config,
debug_info: bool, dump: bool)
-> Result<String, (String, Error)>
{
let hash_str = all(&container, cfg, debug_info, dump)?;
Ok(hash_str)
}
|
-> Result<String, (String, Error)>
|
random_line_split
|
unrooted_must_root.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 syntax::{ast, codemap, visit};
use syntax::attr::AttrMetaMethods;
use rustc::ast_map;
use rustc::lint::{Context, LintPass, LintArray};
use rustc::middle::ty::expr_ty;
use rustc::middle::{ty, def};
use utils::unsafe_context;
declare_lint!(UNROOTED_MUST_ROOT, Deny,
"Warn and report usage of unrooted jsmanaged objects");
/// Lint for ensuring safe usage of unrooted pointers
///
/// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]`
/// values are used correctly.
///
/// "Incorrect" usage includes:
///
/// - Not being used in a struct/enum field which is not `#[must_root]` itself
/// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`)
/// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement.
///
/// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a
/// GC pass.
pub struct UnrootedPass;
// Checks if a type has the #[must_root] annotation.
// Unwraps pointers as well
// TODO (#3874, sort of): unwrap other types like Vec/Option/HashMap/etc
fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) {
match ty.node {
ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) =>
lint_unrooted_ty(cx, &**t, warning),
ast::TyPath(..) => {
match cx.tcx.def_map.borrow()[&ty.id] {
def::PathResolution{ base_def: def::DefTy(def_id, _),.. } => {
if ty::has_attr(cx.tcx, def_id, "must_root") {
cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning);
}
}
_ => (),
}
}
_ => (),
};
}
impl LintPass for UnrootedPass {
fn get_lints(&self) -> LintArray {
lint_array!(UNROOTED_MUST_ROOT)
}
/// All structs containing #[must_root] types must be #[must_root] themselves
fn check_struct_def(&mut self,
cx: &Context,
def: &ast::StructDef,
_i: ast::Ident,
_gen: &ast::Generics,
id: ast::NodeId) {
let item = match cx.tcx.map.get(id) {
ast_map::Node::NodeItem(item) => item,
_ => cx.tcx.map.expect_item(cx.tcx.map.get_parent(id)),
};
if item.attrs.iter().all(|a|!a.check_name("must_root")) {
for ref field in def.fields.iter() {
lint_unrooted_ty(cx, &*field.node.ty,
"Type must be rooted, use #[must_root] on the struct definition to propagate");
}
}
}
/// All enums containing #[must_root] types must be #[must_root] themselves
fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) {
let ref map = cx.tcx.map;
if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a|!a.check_name("must_root")) {
match var.node.kind {
ast::TupleVariantKind(ref vec) => {
for ty in vec.iter() {
lint_unrooted_ty(cx, &*ty.ty,
"Type must be rooted, use #[must_root] on the enum definition to propagate")
}
}
_ => () // Struct variants already caught by check_struct_def
}
}
}
/// Function arguments that are #[must_root] types are not allowed
fn check_fn(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl,
block: &ast::Block, _span: codemap::Span, id: ast::NodeId) {
match kind {
visit::FkItemFn(i, _, _, _, _, _) |
visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => {
return;
},
visit::FkItemFn(_, _, style, _, _, _) => match style {
ast::Unsafety::Unsafe => return,
_ => ()
|
},
_ => ()
}
if unsafe_context(&cx.tcx.map, id) {
return;
}
match block.rules {
ast::DefaultBlock => {
for arg in decl.inputs.iter() {
lint_unrooted_ty(cx, &*arg.ty,
"Type must be rooted")
}
}
_ => () // fn is `unsafe`
}
}
// Partially copied from rustc::middle::lint::builtin
// Catches `let` statements and assignments which store a #[must_root] value
// Expressions which return out of blocks eventually end up in a `let` or assignment
// statement or a function return (which will be caught when it is used elsewhere)
fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
match s.node {
ast::StmtDecl(_, id) |
ast::StmtExpr(_, id) |
ast::StmtSemi(_, id) if unsafe_context(&cx.tcx.map, id) => {
return
},
_ => ()
};
let expr = match s.node {
// Catch a `let` binding
ast::StmtDecl(ref decl, _) => match decl.node {
ast::DeclLocal(ref loc) => match loc.init {
Some(ref e) => &**e,
_ => return
},
_ => return
},
ast::StmtExpr(ref expr, _) => match expr.node {
// This catches deferred `let` statements
ast::ExprAssign(_, ref e) |
// Match statements allow you to bind onto the variable later in an arm
// We need not check arms individually since enum/struct fields are already
// linted in `check_struct_def` and `check_variant`
// (so there is no way of destructuring out a `#[must_root]` field)
ast::ExprMatch(ref e, _, _) |
// For loops allow you to bind a return value locally
ast::ExprForLoop(_, ref e, _, _) => &**e,
// XXXManishearth look into `if let` once it lands in our rustc
_ => return
},
_ => return
};
let t = expr_ty(cx.tcx, &*expr);
match t.sty {
ty::TyStruct(did, _) |
ty::TyEnum(did, _) => {
if ty::has_attr(cx.tcx, did, "must_root") {
cx.span_lint(UNROOTED_MUST_ROOT, expr.span,
&format!("Expression of type {:?} must be rooted", t));
}
}
_ => {}
}
}
}
|
random_line_split
|
|
unrooted_must_root.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 syntax::{ast, codemap, visit};
use syntax::attr::AttrMetaMethods;
use rustc::ast_map;
use rustc::lint::{Context, LintPass, LintArray};
use rustc::middle::ty::expr_ty;
use rustc::middle::{ty, def};
use utils::unsafe_context;
declare_lint!(UNROOTED_MUST_ROOT, Deny,
"Warn and report usage of unrooted jsmanaged objects");
/// Lint for ensuring safe usage of unrooted pointers
///
/// This lint (disable with `-A unrooted-must-root`/`#[allow(unrooted_must_root)]`) ensures that `#[must_root]`
/// values are used correctly.
///
/// "Incorrect" usage includes:
///
/// - Not being used in a struct/enum field which is not `#[must_root]` itself
/// - Not being used as an argument to a function (Except onces named `new` and `new_inherited`)
/// - Not being bound locally in a `let` statement, assignment, `for` loop, or `match` statement.
///
/// This helps catch most situations where pointers like `JS<T>` are used in a way that they can be invalidated by a
/// GC pass.
pub struct
|
;
// Checks if a type has the #[must_root] annotation.
// Unwraps pointers as well
// TODO (#3874, sort of): unwrap other types like Vec/Option/HashMap/etc
fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) {
match ty.node {
ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) =>
lint_unrooted_ty(cx, &**t, warning),
ast::TyPath(..) => {
match cx.tcx.def_map.borrow()[&ty.id] {
def::PathResolution{ base_def: def::DefTy(def_id, _),.. } => {
if ty::has_attr(cx.tcx, def_id, "must_root") {
cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning);
}
}
_ => (),
}
}
_ => (),
};
}
impl LintPass for UnrootedPass {
fn get_lints(&self) -> LintArray {
lint_array!(UNROOTED_MUST_ROOT)
}
/// All structs containing #[must_root] types must be #[must_root] themselves
fn check_struct_def(&mut self,
cx: &Context,
def: &ast::StructDef,
_i: ast::Ident,
_gen: &ast::Generics,
id: ast::NodeId) {
let item = match cx.tcx.map.get(id) {
ast_map::Node::NodeItem(item) => item,
_ => cx.tcx.map.expect_item(cx.tcx.map.get_parent(id)),
};
if item.attrs.iter().all(|a|!a.check_name("must_root")) {
for ref field in def.fields.iter() {
lint_unrooted_ty(cx, &*field.node.ty,
"Type must be rooted, use #[must_root] on the struct definition to propagate");
}
}
}
/// All enums containing #[must_root] types must be #[must_root] themselves
fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) {
let ref map = cx.tcx.map;
if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a|!a.check_name("must_root")) {
match var.node.kind {
ast::TupleVariantKind(ref vec) => {
for ty in vec.iter() {
lint_unrooted_ty(cx, &*ty.ty,
"Type must be rooted, use #[must_root] on the enum definition to propagate")
}
}
_ => () // Struct variants already caught by check_struct_def
}
}
}
/// Function arguments that are #[must_root] types are not allowed
fn check_fn(&mut self, cx: &Context, kind: visit::FnKind, decl: &ast::FnDecl,
block: &ast::Block, _span: codemap::Span, id: ast::NodeId) {
match kind {
visit::FkItemFn(i, _, _, _, _, _) |
visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => {
return;
},
visit::FkItemFn(_, _, style, _, _, _) => match style {
ast::Unsafety::Unsafe => return,
_ => ()
},
_ => ()
}
if unsafe_context(&cx.tcx.map, id) {
return;
}
match block.rules {
ast::DefaultBlock => {
for arg in decl.inputs.iter() {
lint_unrooted_ty(cx, &*arg.ty,
"Type must be rooted")
}
}
_ => () // fn is `unsafe`
}
}
// Partially copied from rustc::middle::lint::builtin
// Catches `let` statements and assignments which store a #[must_root] value
// Expressions which return out of blocks eventually end up in a `let` or assignment
// statement or a function return (which will be caught when it is used elsewhere)
fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) {
match s.node {
ast::StmtDecl(_, id) |
ast::StmtExpr(_, id) |
ast::StmtSemi(_, id) if unsafe_context(&cx.tcx.map, id) => {
return
},
_ => ()
};
let expr = match s.node {
// Catch a `let` binding
ast::StmtDecl(ref decl, _) => match decl.node {
ast::DeclLocal(ref loc) => match loc.init {
Some(ref e) => &**e,
_ => return
},
_ => return
},
ast::StmtExpr(ref expr, _) => match expr.node {
// This catches deferred `let` statements
ast::ExprAssign(_, ref e) |
// Match statements allow you to bind onto the variable later in an arm
// We need not check arms individually since enum/struct fields are already
// linted in `check_struct_def` and `check_variant`
// (so there is no way of destructuring out a `#[must_root]` field)
ast::ExprMatch(ref e, _, _) |
// For loops allow you to bind a return value locally
ast::ExprForLoop(_, ref e, _, _) => &**e,
// XXXManishearth look into `if let` once it lands in our rustc
_ => return
},
_ => return
};
let t = expr_ty(cx.tcx, &*expr);
match t.sty {
ty::TyStruct(did, _) |
ty::TyEnum(did, _) => {
if ty::has_attr(cx.tcx, did, "must_root") {
cx.span_lint(UNROOTED_MUST_ROOT, expr.span,
&format!("Expression of type {:?} must be rooted", t));
}
}
_ => {}
}
}
}
|
UnrootedPass
|
identifier_name
|
issue-16151.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.
// run-pass
use std::mem;
static mut DROP_COUNT: usize = 0;
struct Fragment;
impl Drop for Fragment {
fn
|
(&mut self) {
unsafe {
DROP_COUNT += 1;
}
}
}
fn main() {
{
let mut fragments = vec![Fragment, Fragment, Fragment];
let _new_fragments: Vec<Fragment> = mem::replace(&mut fragments, vec![])
.into_iter()
.skip_while(|_fragment| {
true
}).collect();
}
unsafe {
assert_eq!(DROP_COUNT, 3);
}
}
|
drop
|
identifier_name
|
issue-16151.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.
// run-pass
use std::mem;
static mut DROP_COUNT: usize = 0;
struct Fragment;
impl Drop for Fragment {
fn drop(&mut self) {
unsafe {
DROP_COUNT += 1;
}
}
}
fn main() {
{
let mut fragments = vec![Fragment, Fragment, Fragment];
let _new_fragments: Vec<Fragment> = mem::replace(&mut fragments, vec![])
.into_iter()
.skip_while(|_fragment| {
true
}).collect();
}
unsafe {
assert_eq!(DROP_COUNT, 3);
|
}
}
|
random_line_split
|
|
issue-16151.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.
// run-pass
use std::mem;
static mut DROP_COUNT: usize = 0;
struct Fragment;
impl Drop for Fragment {
fn drop(&mut self) {
unsafe {
DROP_COUNT += 1;
}
}
}
fn main()
|
{
{
let mut fragments = vec![Fragment, Fragment, Fragment];
let _new_fragments: Vec<Fragment> = mem::replace(&mut fragments, vec![])
.into_iter()
.skip_while(|_fragment| {
true
}).collect();
}
unsafe {
assert_eq!(DROP_COUNT, 3);
}
}
|
identifier_body
|
|
build.rs
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::env;
use std::process::Command;
use std::str::{self, FromStr};
fn main() {
println!("cargo:rustc-cfg=build_script_ran");
let minor = match rustc_minor_version() {
Some(minor) => minor,
None => return,
};
let target = env::var("TARGET").unwrap();
if minor >= 34 {
println!("cargo:rustc-cfg=is_new_rustc");
} else {
println!("cargo:rustc-cfg=is_old_rustc");
}
if target.contains("android") {
println!("cargo:rustc-cfg=is_android");
|
if target.contains("darwin") {
println!("cargo:rustc-cfg=is_mac");
}
}
fn rustc_minor_version() -> Option<u32> {
let rustc = match env::var_os("RUSTC") {
Some(rustc) => rustc,
None => return None,
};
let output = match Command::new(rustc).arg("--version").output() {
Ok(output) => output,
Err(_) => return None,
};
let version = match str::from_utf8(&output.stdout) {
Ok(version) => version,
Err(_) => return None,
};
let mut pieces = version.split('.');
if pieces.next()!= Some("rustc 1") {
return None;
}
let next = match pieces.next() {
Some(next) => next,
None => return None,
};
u32::from_str(next).ok()
}
|
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.