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 |
---|---|---|---|---|
serviceworkercontainer.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 crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions;
use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{
ServiceWorkerContainerMethods, Wrap,
};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::USVString;
use crate::dom::client::Client;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise;
use crate::dom::serviceworker::ServiceWorker;
use crate::script_thread::ScriptThread;
use crate::serviceworkerjob::{Job, JobType};
use dom_struct::dom_struct;
use std::default::Default;
use std::rc::Rc;
#[dom_struct]
pub struct ServiceWorkerContainer {
eventtarget: EventTarget,
controller: MutNullableDom<ServiceWorker>,
client: Dom<Client>,
}
impl ServiceWorkerContainer {
fn new_inherited(client: &Client) -> ServiceWorkerContainer {
ServiceWorkerContainer {
eventtarget: EventTarget::new_inherited(),
controller: Default::default(),
client: Dom::from_ref(client),
}
}
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> {
let client = Client::new(&global.as_window());
let container = ServiceWorkerContainer::new_inherited(&*client);
reflect_dom_object(Box::new(container), global, Wrap)
}
}
impl ServiceWorkerContainerMethods for ServiceWorkerContainer {
// https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute
fn GetController(&self) -> Option<DomRoot<ServiceWorker>> {
self.client.get_controller()
|
}
#[allow(unrooted_must_root)]
// https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A
// https://w3c.github.io/ServiceWorker/#start-register-algorithm - B
fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> {
// A: Step 1
let promise = Promise::new(&*self.global());
let USVString(ref script_url) = script_url;
let api_base_url = self.global().api_base_url();
// A: Step 3-5
let script_url = match api_base_url.join(script_url) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid script URL".to_owned()));
return promise;
},
};
// B: Step 2
match script_url.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 3
if script_url.path().to_ascii_lowercase().contains("%2f") ||
script_url.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Script URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 4-5
let scope = match options.scope {
Some(ref scope) => {
let &USVString(ref inner_scope) = scope;
match api_base_url.join(inner_scope) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid scope URL".to_owned()));
return promise;
},
}
},
None => script_url.join("./").unwrap(),
};
// B: Step 6
match scope.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 7
if scope.path().to_ascii_lowercase().contains("%2f") ||
scope.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Scope URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 8
let job = Job::create_job(
JobType::Register,
scope,
script_url,
promise.clone(),
&*self.client,
);
ScriptThread::schedule_job(job);
promise
}
}
|
random_line_split
|
|
serviceworkercontainer.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 crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions;
use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{
ServiceWorkerContainerMethods, Wrap,
};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::USVString;
use crate::dom::client::Client;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise;
use crate::dom::serviceworker::ServiceWorker;
use crate::script_thread::ScriptThread;
use crate::serviceworkerjob::{Job, JobType};
use dom_struct::dom_struct;
use std::default::Default;
use std::rc::Rc;
#[dom_struct]
pub struct ServiceWorkerContainer {
eventtarget: EventTarget,
controller: MutNullableDom<ServiceWorker>,
client: Dom<Client>,
}
impl ServiceWorkerContainer {
fn new_inherited(client: &Client) -> ServiceWorkerContainer {
ServiceWorkerContainer {
eventtarget: EventTarget::new_inherited(),
controller: Default::default(),
client: Dom::from_ref(client),
}
}
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> {
let client = Client::new(&global.as_window());
let container = ServiceWorkerContainer::new_inherited(&*client);
reflect_dom_object(Box::new(container), global, Wrap)
}
}
impl ServiceWorkerContainerMethods for ServiceWorkerContainer {
// https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute
fn GetController(&self) -> Option<DomRoot<ServiceWorker>>
|
#[allow(unrooted_must_root)]
// https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A
// https://w3c.github.io/ServiceWorker/#start-register-algorithm - B
fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> {
// A: Step 1
let promise = Promise::new(&*self.global());
let USVString(ref script_url) = script_url;
let api_base_url = self.global().api_base_url();
// A: Step 3-5
let script_url = match api_base_url.join(script_url) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid script URL".to_owned()));
return promise;
},
};
// B: Step 2
match script_url.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 3
if script_url.path().to_ascii_lowercase().contains("%2f") ||
script_url.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Script URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 4-5
let scope = match options.scope {
Some(ref scope) => {
let &USVString(ref inner_scope) = scope;
match api_base_url.join(inner_scope) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid scope URL".to_owned()));
return promise;
},
}
},
None => script_url.join("./").unwrap(),
};
// B: Step 6
match scope.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 7
if scope.path().to_ascii_lowercase().contains("%2f") ||
scope.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Scope URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 8
let job = Job::create_job(
JobType::Register,
scope,
script_url,
promise.clone(),
&*self.client,
);
ScriptThread::schedule_job(job);
promise
}
}
|
{
self.client.get_controller()
}
|
identifier_body
|
serviceworkercontainer.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 crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions;
use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{
ServiceWorkerContainerMethods, Wrap,
};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::USVString;
use crate::dom::client::Client;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise;
use crate::dom::serviceworker::ServiceWorker;
use crate::script_thread::ScriptThread;
use crate::serviceworkerjob::{Job, JobType};
use dom_struct::dom_struct;
use std::default::Default;
use std::rc::Rc;
#[dom_struct]
pub struct
|
{
eventtarget: EventTarget,
controller: MutNullableDom<ServiceWorker>,
client: Dom<Client>,
}
impl ServiceWorkerContainer {
fn new_inherited(client: &Client) -> ServiceWorkerContainer {
ServiceWorkerContainer {
eventtarget: EventTarget::new_inherited(),
controller: Default::default(),
client: Dom::from_ref(client),
}
}
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> {
let client = Client::new(&global.as_window());
let container = ServiceWorkerContainer::new_inherited(&*client);
reflect_dom_object(Box::new(container), global, Wrap)
}
}
impl ServiceWorkerContainerMethods for ServiceWorkerContainer {
// https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute
fn GetController(&self) -> Option<DomRoot<ServiceWorker>> {
self.client.get_controller()
}
#[allow(unrooted_must_root)]
// https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A
// https://w3c.github.io/ServiceWorker/#start-register-algorithm - B
fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> {
// A: Step 1
let promise = Promise::new(&*self.global());
let USVString(ref script_url) = script_url;
let api_base_url = self.global().api_base_url();
// A: Step 3-5
let script_url = match api_base_url.join(script_url) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid script URL".to_owned()));
return promise;
},
};
// B: Step 2
match script_url.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 3
if script_url.path().to_ascii_lowercase().contains("%2f") ||
script_url.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Script URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 4-5
let scope = match options.scope {
Some(ref scope) => {
let &USVString(ref inner_scope) = scope;
match api_base_url.join(inner_scope) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid scope URL".to_owned()));
return promise;
},
}
},
None => script_url.join("./").unwrap(),
};
// B: Step 6
match scope.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 7
if scope.path().to_ascii_lowercase().contains("%2f") ||
scope.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Scope URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 8
let job = Job::create_job(
JobType::Register,
scope,
script_url,
promise.clone(),
&*self.client,
);
ScriptThread::schedule_job(job);
promise
}
}
|
ServiceWorkerContainer
|
identifier_name
|
serviceworkercontainer.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 crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions;
use crate::dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{
ServiceWorkerContainerMethods, Wrap,
};
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::USVString;
use crate::dom::client::Client;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
use crate::dom::promise::Promise;
use crate::dom::serviceworker::ServiceWorker;
use crate::script_thread::ScriptThread;
use crate::serviceworkerjob::{Job, JobType};
use dom_struct::dom_struct;
use std::default::Default;
use std::rc::Rc;
#[dom_struct]
pub struct ServiceWorkerContainer {
eventtarget: EventTarget,
controller: MutNullableDom<ServiceWorker>,
client: Dom<Client>,
}
impl ServiceWorkerContainer {
fn new_inherited(client: &Client) -> ServiceWorkerContainer {
ServiceWorkerContainer {
eventtarget: EventTarget::new_inherited(),
controller: Default::default(),
client: Dom::from_ref(client),
}
}
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope) -> DomRoot<ServiceWorkerContainer> {
let client = Client::new(&global.as_window());
let container = ServiceWorkerContainer::new_inherited(&*client);
reflect_dom_object(Box::new(container), global, Wrap)
}
}
impl ServiceWorkerContainerMethods for ServiceWorkerContainer {
// https://w3c.github.io/ServiceWorker/#service-worker-container-controller-attribute
fn GetController(&self) -> Option<DomRoot<ServiceWorker>> {
self.client.get_controller()
}
#[allow(unrooted_must_root)]
// https://w3c.github.io/ServiceWorker/#service-worker-container-register-method and - A
// https://w3c.github.io/ServiceWorker/#start-register-algorithm - B
fn Register(&self, script_url: USVString, options: &RegistrationOptions) -> Rc<Promise> {
// A: Step 1
let promise = Promise::new(&*self.global());
let USVString(ref script_url) = script_url;
let api_base_url = self.global().api_base_url();
// A: Step 3-5
let script_url = match api_base_url.join(script_url) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid script URL".to_owned()));
return promise;
},
};
// B: Step 2
match script_url.scheme() {
"https" | "http" => {},
_ =>
|
,
}
// B: Step 3
if script_url.path().to_ascii_lowercase().contains("%2f") ||
script_url.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Script URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 4-5
let scope = match options.scope {
Some(ref scope) => {
let &USVString(ref inner_scope) = scope;
match api_base_url.join(inner_scope) {
Ok(url) => url,
Err(_) => {
promise.reject_error(Error::Type("Invalid scope URL".to_owned()));
return promise;
},
}
},
None => script_url.join("./").unwrap(),
};
// B: Step 6
match scope.scheme() {
"https" | "http" => {},
_ => {
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
},
}
// B: Step 7
if scope.path().to_ascii_lowercase().contains("%2f") ||
scope.path().to_ascii_lowercase().contains("%5c")
{
promise.reject_error(Error::Type(
"Scope URL contains forbidden characters".to_owned(),
));
return promise;
}
// B: Step 8
let job = Job::create_job(
JobType::Register,
scope,
script_url,
promise.clone(),
&*self.client,
);
ScriptThread::schedule_job(job);
promise
}
}
|
{
promise.reject_error(Error::Type("Only secure origins are allowed".to_owned()));
return promise;
}
|
conditional_block
|
fact.rs
|
#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ExprItem {
pub data: Option<String>, // pub type: Option<String>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct FactcContent {
pub expr: Option<Vec<ExprItem>>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct FactBody {
pub content: FactcContent,
|
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct Fact {
pub fact: FactBody,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ObjectsFactBody {
pub paging: super::MetadataPaging,
pub items: Vec<Fact>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ObjectsFact {
pub objects: ObjectsFactBody,
}
|
pub meta: super::MetadataMeta,
}
|
random_line_split
|
fact.rs
|
#[allow(non_snake_case)]
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ExprItem {
pub data: Option<String>, // pub type: Option<String>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct
|
{
pub expr: Option<Vec<ExprItem>>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct FactBody {
pub content: FactcContent,
pub meta: super::MetadataMeta,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct Fact {
pub fact: FactBody,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ObjectsFactBody {
pub paging: super::MetadataPaging,
pub items: Vec<Fact>,
}
#[derive(RustcDecodable, RustcEncodable, Debug, Clone)]
pub struct ObjectsFact {
pub objects: ObjectsFactBody,
}
|
FactcContent
|
identifier_name
|
celleditable.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! Interface for widgets which can are used for editing cells
use gtk::{mod, ffi};
use gtk::cast::GTK_CELL_EDITABLE;
pub trait CellEditableTrait : gtk::WidgetTrait {
fn editing_done(&self)
|
fn remove_widget(&self) {
unsafe { ffi::gtk_cell_editable_remove_widget(GTK_CELL_EDITABLE(self.get_widget())) }
}
}
|
{
unsafe { ffi::gtk_cell_editable_editing_done(GTK_CELL_EDITABLE(self.get_widget())) }
}
|
identifier_body
|
celleditable.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
|
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! Interface for widgets which can are used for editing cells
use gtk::{mod, ffi};
use gtk::cast::GTK_CELL_EDITABLE;
pub trait CellEditableTrait : gtk::WidgetTrait {
fn editing_done(&self) {
unsafe { ffi::gtk_cell_editable_editing_done(GTK_CELL_EDITABLE(self.get_widget())) }
}
fn remove_widget(&self) {
unsafe { ffi::gtk_cell_editable_remove_widget(GTK_CELL_EDITABLE(self.get_widget())) }
}
}
|
random_line_split
|
|
celleditable.rs
|
// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk. If not, see <http://www.gnu.org/licenses/>.
//! Interface for widgets which can are used for editing cells
use gtk::{mod, ffi};
use gtk::cast::GTK_CELL_EDITABLE;
pub trait CellEditableTrait : gtk::WidgetTrait {
fn editing_done(&self) {
unsafe { ffi::gtk_cell_editable_editing_done(GTK_CELL_EDITABLE(self.get_widget())) }
}
fn
|
(&self) {
unsafe { ffi::gtk_cell_editable_remove_widget(GTK_CELL_EDITABLE(self.get_widget())) }
}
}
|
remove_widget
|
identifier_name
|
newweave.rs
|
//! Writer for new weaves
use std::{
collections::BTreeMap,
fs::rename,
io::{self, Write},
mem::replace,
};
use crate::{header::Header, Error, NamingConvention, Result, WriterInfo};
#[allow(unused)]
use crate::Compression;
/// A builder for a new weave file. The data should be written as a writer. Closing the weaver
/// will finish up the write and move the new file into place. If the weaver is just dropped, the
/// file will not be moved into place.
pub struct NewWeave<'n> {
naming: &'n dyn NamingConvention,
temp: Option<WriterInfo>,
}
impl<'n> NewWeave<'n> {
pub fn new<'a, 'b, I>(nc: &dyn NamingConvention, tags: I) -> Result<NewWeave>
where
I: Iterator<Item = (&'a str, &'b str)>,
{
let mut writeinfo = nc.new_temp()?;
let mut ntags = BTreeMap::new();
for (k, v) in tags {
ntags.insert(k.to_owned(), v.to_owned());
}
let mut header: Header = Default::default();
let delta = header.add(ntags)?;
header.write(&mut writeinfo.writer)?;
writeln!(&mut writeinfo.writer, "\x01I {}", delta)?;
Ok(NewWeave {
naming: nc,
temp: Some(writeinfo),
})
}
pub fn
|
(mut self) -> Result<()> {
let temp = replace(&mut self.temp, None);
let name = match temp {
Some(mut wi) => {
writeln!(&mut wi.writer, "\x01E 1")?;
wi.name
}
None => return Err(Error::AlreadyClosed),
};
let _ = rename(self.naming.main_file(), self.naming.backup_file());
rename(name, self.naming.main_file())?;
Ok(())
}
}
impl<'n> Write for NewWeave<'n> {
// Write the data out, just passing it through to the underlying file write. We assume the
// last line is terminated, or the resulting weave will be invalid.
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.temp
.as_mut()
.expect("Attempt to write to NewWeave that is closed")
.writer
.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.temp
.as_mut()
.expect("Attempt to flush NewWeave that is closed")
.writer
.flush()
}
}
#[test]
#[ignore]
fn try_tag() {
use crate::SimpleNaming;
let mut tags = BTreeMap::new();
tags.insert("name".to_owned(), "initial revision".to_owned());
// Add a whole bunch of longer tags to show it works.
for i in 1..100 {
tags.insert(format!("key{}", i), format!("This is the {}th value", i));
}
let nc = SimpleNaming::new(".", "tags", "weave", Compression::Gzip);
let t2 = tags.iter().map(|(k, v)| (k.as_ref(), v.as_ref()));
let mut wr = NewWeave::new(&nc, t2).unwrap();
writeln!(&mut wr, "This is the only line in the file").unwrap();
wr.close().unwrap();
}
|
close
|
identifier_name
|
newweave.rs
|
//! Writer for new weaves
use std::{
collections::BTreeMap,
fs::rename,
io::{self, Write},
mem::replace,
};
use crate::{header::Header, Error, NamingConvention, Result, WriterInfo};
#[allow(unused)]
use crate::Compression;
/// A builder for a new weave file. The data should be written as a writer. Closing the weaver
/// will finish up the write and move the new file into place. If the weaver is just dropped, the
/// file will not be moved into place.
pub struct NewWeave<'n> {
naming: &'n dyn NamingConvention,
temp: Option<WriterInfo>,
}
impl<'n> NewWeave<'n> {
pub fn new<'a, 'b, I>(nc: &dyn NamingConvention, tags: I) -> Result<NewWeave>
where
I: Iterator<Item = (&'a str, &'b str)>,
{
let mut writeinfo = nc.new_temp()?;
let mut ntags = BTreeMap::new();
for (k, v) in tags {
ntags.insert(k.to_owned(), v.to_owned());
}
|
let mut header: Header = Default::default();
let delta = header.add(ntags)?;
header.write(&mut writeinfo.writer)?;
writeln!(&mut writeinfo.writer, "\x01I {}", delta)?;
Ok(NewWeave {
naming: nc,
temp: Some(writeinfo),
})
}
pub fn close(mut self) -> Result<()> {
let temp = replace(&mut self.temp, None);
let name = match temp {
Some(mut wi) => {
writeln!(&mut wi.writer, "\x01E 1")?;
wi.name
}
None => return Err(Error::AlreadyClosed),
};
let _ = rename(self.naming.main_file(), self.naming.backup_file());
rename(name, self.naming.main_file())?;
Ok(())
}
}
impl<'n> Write for NewWeave<'n> {
// Write the data out, just passing it through to the underlying file write. We assume the
// last line is terminated, or the resulting weave will be invalid.
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.temp
.as_mut()
.expect("Attempt to write to NewWeave that is closed")
.writer
.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.temp
.as_mut()
.expect("Attempt to flush NewWeave that is closed")
.writer
.flush()
}
}
#[test]
#[ignore]
fn try_tag() {
use crate::SimpleNaming;
let mut tags = BTreeMap::new();
tags.insert("name".to_owned(), "initial revision".to_owned());
// Add a whole bunch of longer tags to show it works.
for i in 1..100 {
tags.insert(format!("key{}", i), format!("This is the {}th value", i));
}
let nc = SimpleNaming::new(".", "tags", "weave", Compression::Gzip);
let t2 = tags.iter().map(|(k, v)| (k.as_ref(), v.as_ref()));
let mut wr = NewWeave::new(&nc, t2).unwrap();
writeln!(&mut wr, "This is the only line in the file").unwrap();
wr.close().unwrap();
}
|
random_line_split
|
|
newweave.rs
|
//! Writer for new weaves
use std::{
collections::BTreeMap,
fs::rename,
io::{self, Write},
mem::replace,
};
use crate::{header::Header, Error, NamingConvention, Result, WriterInfo};
#[allow(unused)]
use crate::Compression;
/// A builder for a new weave file. The data should be written as a writer. Closing the weaver
/// will finish up the write and move the new file into place. If the weaver is just dropped, the
/// file will not be moved into place.
pub struct NewWeave<'n> {
naming: &'n dyn NamingConvention,
temp: Option<WriterInfo>,
}
impl<'n> NewWeave<'n> {
pub fn new<'a, 'b, I>(nc: &dyn NamingConvention, tags: I) -> Result<NewWeave>
where
I: Iterator<Item = (&'a str, &'b str)>,
{
let mut writeinfo = nc.new_temp()?;
let mut ntags = BTreeMap::new();
for (k, v) in tags {
ntags.insert(k.to_owned(), v.to_owned());
}
let mut header: Header = Default::default();
let delta = header.add(ntags)?;
header.write(&mut writeinfo.writer)?;
writeln!(&mut writeinfo.writer, "\x01I {}", delta)?;
Ok(NewWeave {
naming: nc,
temp: Some(writeinfo),
})
}
pub fn close(mut self) -> Result<()> {
let temp = replace(&mut self.temp, None);
let name = match temp {
Some(mut wi) =>
|
None => return Err(Error::AlreadyClosed),
};
let _ = rename(self.naming.main_file(), self.naming.backup_file());
rename(name, self.naming.main_file())?;
Ok(())
}
}
impl<'n> Write for NewWeave<'n> {
// Write the data out, just passing it through to the underlying file write. We assume the
// last line is terminated, or the resulting weave will be invalid.
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.temp
.as_mut()
.expect("Attempt to write to NewWeave that is closed")
.writer
.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.temp
.as_mut()
.expect("Attempt to flush NewWeave that is closed")
.writer
.flush()
}
}
#[test]
#[ignore]
fn try_tag() {
use crate::SimpleNaming;
let mut tags = BTreeMap::new();
tags.insert("name".to_owned(), "initial revision".to_owned());
// Add a whole bunch of longer tags to show it works.
for i in 1..100 {
tags.insert(format!("key{}", i), format!("This is the {}th value", i));
}
let nc = SimpleNaming::new(".", "tags", "weave", Compression::Gzip);
let t2 = tags.iter().map(|(k, v)| (k.as_ref(), v.as_ref()));
let mut wr = NewWeave::new(&nc, t2).unwrap();
writeln!(&mut wr, "This is the only line in the file").unwrap();
wr.close().unwrap();
}
|
{
writeln!(&mut wi.writer, "\x01E 1")?;
wi.name
}
|
conditional_block
|
newweave.rs
|
//! Writer for new weaves
use std::{
collections::BTreeMap,
fs::rename,
io::{self, Write},
mem::replace,
};
use crate::{header::Header, Error, NamingConvention, Result, WriterInfo};
#[allow(unused)]
use crate::Compression;
/// A builder for a new weave file. The data should be written as a writer. Closing the weaver
/// will finish up the write and move the new file into place. If the weaver is just dropped, the
/// file will not be moved into place.
pub struct NewWeave<'n> {
naming: &'n dyn NamingConvention,
temp: Option<WriterInfo>,
}
impl<'n> NewWeave<'n> {
pub fn new<'a, 'b, I>(nc: &dyn NamingConvention, tags: I) -> Result<NewWeave>
where
I: Iterator<Item = (&'a str, &'b str)>,
|
pub fn close(mut self) -> Result<()> {
let temp = replace(&mut self.temp, None);
let name = match temp {
Some(mut wi) => {
writeln!(&mut wi.writer, "\x01E 1")?;
wi.name
}
None => return Err(Error::AlreadyClosed),
};
let _ = rename(self.naming.main_file(), self.naming.backup_file());
rename(name, self.naming.main_file())?;
Ok(())
}
}
impl<'n> Write for NewWeave<'n> {
// Write the data out, just passing it through to the underlying file write. We assume the
// last line is terminated, or the resulting weave will be invalid.
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.temp
.as_mut()
.expect("Attempt to write to NewWeave that is closed")
.writer
.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.temp
.as_mut()
.expect("Attempt to flush NewWeave that is closed")
.writer
.flush()
}
}
#[test]
#[ignore]
fn try_tag() {
use crate::SimpleNaming;
let mut tags = BTreeMap::new();
tags.insert("name".to_owned(), "initial revision".to_owned());
// Add a whole bunch of longer tags to show it works.
for i in 1..100 {
tags.insert(format!("key{}", i), format!("This is the {}th value", i));
}
let nc = SimpleNaming::new(".", "tags", "weave", Compression::Gzip);
let t2 = tags.iter().map(|(k, v)| (k.as_ref(), v.as_ref()));
let mut wr = NewWeave::new(&nc, t2).unwrap();
writeln!(&mut wr, "This is the only line in the file").unwrap();
wr.close().unwrap();
}
|
{
let mut writeinfo = nc.new_temp()?;
let mut ntags = BTreeMap::new();
for (k, v) in tags {
ntags.insert(k.to_owned(), v.to_owned());
}
let mut header: Header = Default::default();
let delta = header.add(ntags)?;
header.write(&mut writeinfo.writer)?;
writeln!(&mut writeinfo.writer, "\x01I {}", delta)?;
Ok(NewWeave {
naming: nc,
temp: Some(writeinfo),
})
}
|
identifier_body
|
tests.rs
|
use crate::direct_transport::{DirectTransport, DirectTransportOptions};
use crate::router::{Router, RouterOptions};
use crate::transport::Transport;
use crate::worker::WorkerSettings;
use crate::worker_manager::WorkerManager;
use futures_lite::future;
use std::env;
async fn init() -> (Router, DirectTransport) {
{
let mut builder = env_logger::builder();
if env::var(env_logger::DEFAULT_FILTER_ENV).is_err()
|
let _ = builder.is_test(true).try_init();
}
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await
.expect("Failed to create worker");
let router = worker
.create_router(RouterOptions::default())
.await
.expect("Failed to create router");
let transport = router
.create_direct_transport(DirectTransportOptions::default())
.await
.expect("Failed to create transport1");
(router, transport)
}
#[test]
fn router_close_event() {
future::block_on(async move {
let (router, transport) = init().await;
let (mut close_tx, close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_close(Box::new(move || {
let _ = close_tx.send(());
}));
let (mut router_close_tx, router_close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_router_close(Box::new(move || {
let _ = router_close_tx.send(());
}));
router.close();
router_close_rx
.await
.expect("Failed to receive router_close event");
close_rx.await.expect("Failed to receive close event");
assert_eq!(transport.closed(), true);
});
}
|
{
builder.filter_level(log::LevelFilter::Off);
}
|
conditional_block
|
tests.rs
|
use crate::direct_transport::{DirectTransport, DirectTransportOptions};
use crate::router::{Router, RouterOptions};
use crate::transport::Transport;
use crate::worker::WorkerSettings;
use crate::worker_manager::WorkerManager;
use futures_lite::future;
use std::env;
async fn init() -> (Router, DirectTransport) {
{
let mut builder = env_logger::builder();
if env::var(env_logger::DEFAULT_FILTER_ENV).is_err() {
builder.filter_level(log::LevelFilter::Off);
}
let _ = builder.is_test(true).try_init();
}
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await
.expect("Failed to create worker");
let router = worker
.create_router(RouterOptions::default())
.await
.expect("Failed to create router");
let transport = router
.create_direct_transport(DirectTransportOptions::default())
.await
.expect("Failed to create transport1");
(router, transport)
|
#[test]
fn router_close_event() {
future::block_on(async move {
let (router, transport) = init().await;
let (mut close_tx, close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_close(Box::new(move || {
let _ = close_tx.send(());
}));
let (mut router_close_tx, router_close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_router_close(Box::new(move || {
let _ = router_close_tx.send(());
}));
router.close();
router_close_rx
.await
.expect("Failed to receive router_close event");
close_rx.await.expect("Failed to receive close event");
assert_eq!(transport.closed(), true);
});
}
|
}
|
random_line_split
|
tests.rs
|
use crate::direct_transport::{DirectTransport, DirectTransportOptions};
use crate::router::{Router, RouterOptions};
use crate::transport::Transport;
use crate::worker::WorkerSettings;
use crate::worker_manager::WorkerManager;
use futures_lite::future;
use std::env;
async fn
|
() -> (Router, DirectTransport) {
{
let mut builder = env_logger::builder();
if env::var(env_logger::DEFAULT_FILTER_ENV).is_err() {
builder.filter_level(log::LevelFilter::Off);
}
let _ = builder.is_test(true).try_init();
}
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await
.expect("Failed to create worker");
let router = worker
.create_router(RouterOptions::default())
.await
.expect("Failed to create router");
let transport = router
.create_direct_transport(DirectTransportOptions::default())
.await
.expect("Failed to create transport1");
(router, transport)
}
#[test]
fn router_close_event() {
future::block_on(async move {
let (router, transport) = init().await;
let (mut close_tx, close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_close(Box::new(move || {
let _ = close_tx.send(());
}));
let (mut router_close_tx, router_close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_router_close(Box::new(move || {
let _ = router_close_tx.send(());
}));
router.close();
router_close_rx
.await
.expect("Failed to receive router_close event");
close_rx.await.expect("Failed to receive close event");
assert_eq!(transport.closed(), true);
});
}
|
init
|
identifier_name
|
tests.rs
|
use crate::direct_transport::{DirectTransport, DirectTransportOptions};
use crate::router::{Router, RouterOptions};
use crate::transport::Transport;
use crate::worker::WorkerSettings;
use crate::worker_manager::WorkerManager;
use futures_lite::future;
use std::env;
async fn init() -> (Router, DirectTransport)
|
let transport = router
.create_direct_transport(DirectTransportOptions::default())
.await
.expect("Failed to create transport1");
(router, transport)
}
#[test]
fn router_close_event() {
future::block_on(async move {
let (router, transport) = init().await;
let (mut close_tx, close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_close(Box::new(move || {
let _ = close_tx.send(());
}));
let (mut router_close_tx, router_close_rx) = async_oneshot::oneshot::<()>();
let _handler = transport.on_router_close(Box::new(move || {
let _ = router_close_tx.send(());
}));
router.close();
router_close_rx
.await
.expect("Failed to receive router_close event");
close_rx.await.expect("Failed to receive close event");
assert_eq!(transport.closed(), true);
});
}
|
{
{
let mut builder = env_logger::builder();
if env::var(env_logger::DEFAULT_FILTER_ENV).is_err() {
builder.filter_level(log::LevelFilter::Off);
}
let _ = builder.is_test(true).try_init();
}
let worker_manager = WorkerManager::new();
let worker = worker_manager
.create_worker(WorkerSettings::default())
.await
.expect("Failed to create worker");
let router = worker
.create_router(RouterOptions::default())
.await
.expect("Failed to create router");
|
identifier_body
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use string_cache::Atom;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
image: RefCell<Option<Url>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.window().root();
let image_cache = window.image_cache_task();
match value {
None => {
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, prefix, document),
image: RefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
make_setter!(SetAlt, "alt")
make_url_getter!(Src)
make_setter!(SetSrc, "src")
make_getter!(UseMap)
make_setter!(SetUseMap, "usemap")
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
}
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn
|
(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("width"), width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("height"), height)
}
make_getter!(Name)
make_setter!(SetName, "name")
make_getter!(Align)
make_setter!(SetAlign, "align")
make_uint_getter!(Hspace)
make_uint_setter!(SetHspace, "hspace")
make_uint_getter!(Vspace)
make_uint_setter!(SetVspace, "vspace")
make_getter!(LongDesc)
make_setter!(SetLongDesc, "longdesc")
make_getter!(Border)
make_setter!(SetBorder, "border")
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
let window = window_from_node(*self).root();
let url = window.get_url();
self.update_image(Some((value, &url)));
}
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if atom!("src") == *name {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
SetWidth
|
identifier_name
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use string_cache::Atom;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
image: RefCell<Option<Url>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.window().root();
let image_cache = window.image_cache_task();
match value {
None => {
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, prefix, document),
image: RefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
make_setter!(SetAlt, "alt")
make_url_getter!(Src)
make_setter!(SetSrc, "src")
make_getter!(UseMap)
make_setter!(SetUseMap, "usemap")
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool)
|
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn SetWidth(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("width"), width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("height"), height)
}
make_getter!(Name)
make_setter!(SetName, "name")
make_getter!(Align)
make_setter!(SetAlign, "align")
make_uint_getter!(Hspace)
make_uint_setter!(SetHspace, "hspace")
make_uint_getter!(Vspace)
make_uint_setter!(SetVspace, "vspace")
make_getter!(LongDesc)
make_setter!(SetLongDesc, "longdesc")
make_getter!(Border)
make_setter!(SetBorder, "border")
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
let window = window_from_node(*self).root();
let url = window.get_url();
self.update_image(Some((value, &url)));
}
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if atom!("src") == *name {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
{
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
}
|
identifier_body
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use string_cache::Atom;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[dom_struct]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
image: RefCell<Option<Url>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.window().root();
let image_cache = window.image_cache_task();
match value {
None => {
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, prefix, document),
image: RefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
make_setter!(SetAlt, "alt")
make_url_getter!(Src)
make_setter!(SetSrc, "src")
make_getter!(UseMap)
make_setter!(SetUseMap, "usemap")
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
}
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn SetWidth(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("width"), width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("height"), height)
}
make_getter!(Name)
make_setter!(SetName, "name")
make_getter!(Align)
make_setter!(SetAlign, "align")
make_uint_getter!(Hspace)
make_uint_setter!(SetHspace, "hspace")
make_uint_getter!(Vspace)
make_uint_setter!(SetVspace, "vspace")
make_getter!(LongDesc)
make_setter!(SetLongDesc, "longdesc")
make_getter!(Border)
make_setter!(SetBorder, "border")
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
let window = window_from_node(*self).root();
let url = window.get_url();
|
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if atom!("src") == *name {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
self.update_image(Some((value, &url)));
}
}
|
random_line_split
|
net.rs
|
use {io};
use sys::unix::{nix, Io};
use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
pub use net::tcp::Shutdown;
pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> {
let opts = if nonblock {
nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
} else {
nix::SOCK_CLOEXEC
};
nix::socket(family, ty, opts, 0)
.map_err(super::from_nix_error)
}
pub fn connect(io: &Io, addr: &nix::SockAddr) -> io::Result<bool>
|
pub fn bind(io: &Io, addr: &nix::SockAddr) -> io::Result<()> {
nix::bind(io.as_raw_fd(), addr)
.map_err(super::from_nix_error)
}
pub fn listen(io: &Io, backlog: usize) -> io::Result<()> {
nix::listen(io.as_raw_fd(), backlog)
.map_err(super::from_nix_error)
}
pub fn accept(io: &Io, nonblock: bool) -> io::Result<RawFd> {
let opts = if nonblock {
nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
} else {
nix::SOCK_CLOEXEC
};
nix::accept4(io.as_raw_fd(), opts)
.map_err(super::from_nix_error)
}
// UDP & UDS
#[inline]
pub fn dup(io: &Io) -> io::Result<Io> {
nix::dup(io.as_raw_fd())
.map_err(super::from_nix_error)
.map(|fd| unsafe { Io::from_raw_fd(fd) })
}
|
{
match nix::connect(io.as_raw_fd(), addr) {
Ok(_) => Ok(true),
Err(e) => {
match e {
nix::Error::Sys(nix::EINPROGRESS) => Ok(false),
_ => Err(super::from_nix_error(e))
}
}
}
}
|
identifier_body
|
net.rs
|
use {io};
use sys::unix::{nix, Io};
use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
pub use net::tcp::Shutdown;
pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> {
let opts = if nonblock {
nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
} else {
nix::SOCK_CLOEXEC
};
nix::socket(family, ty, opts, 0)
.map_err(super::from_nix_error)
}
pub fn
|
(io: &Io, addr: &nix::SockAddr) -> io::Result<bool> {
match nix::connect(io.as_raw_fd(), addr) {
Ok(_) => Ok(true),
Err(e) => {
match e {
nix::Error::Sys(nix::EINPROGRESS) => Ok(false),
_ => Err(super::from_nix_error(e))
}
}
}
}
pub fn bind(io: &Io, addr: &nix::SockAddr) -> io::Result<()> {
nix::bind(io.as_raw_fd(), addr)
.map_err(super::from_nix_error)
}
pub fn listen(io: &Io, backlog: usize) -> io::Result<()> {
nix::listen(io.as_raw_fd(), backlog)
.map_err(super::from_nix_error)
}
pub fn accept(io: &Io, nonblock: bool) -> io::Result<RawFd> {
let opts = if nonblock {
nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
} else {
nix::SOCK_CLOEXEC
};
nix::accept4(io.as_raw_fd(), opts)
.map_err(super::from_nix_error)
}
// UDP & UDS
#[inline]
pub fn dup(io: &Io) -> io::Result<Io> {
nix::dup(io.as_raw_fd())
.map_err(super::from_nix_error)
.map(|fd| unsafe { Io::from_raw_fd(fd) })
}
|
connect
|
identifier_name
|
net.rs
|
use {io};
use sys::unix::{nix, Io};
use std::os::unix::io::{AsRawFd, RawFd, FromRawFd};
pub use net::tcp::Shutdown;
pub fn socket(family: nix::AddressFamily, ty: nix::SockType, nonblock: bool) -> io::Result<RawFd> {
let opts = if nonblock {
nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
|
nix::SOCK_CLOEXEC
};
nix::socket(family, ty, opts, 0)
.map_err(super::from_nix_error)
}
pub fn connect(io: &Io, addr: &nix::SockAddr) -> io::Result<bool> {
match nix::connect(io.as_raw_fd(), addr) {
Ok(_) => Ok(true),
Err(e) => {
match e {
nix::Error::Sys(nix::EINPROGRESS) => Ok(false),
_ => Err(super::from_nix_error(e))
}
}
}
}
pub fn bind(io: &Io, addr: &nix::SockAddr) -> io::Result<()> {
nix::bind(io.as_raw_fd(), addr)
.map_err(super::from_nix_error)
}
pub fn listen(io: &Io, backlog: usize) -> io::Result<()> {
nix::listen(io.as_raw_fd(), backlog)
.map_err(super::from_nix_error)
}
pub fn accept(io: &Io, nonblock: bool) -> io::Result<RawFd> {
let opts = if nonblock {
nix::SOCK_NONBLOCK | nix::SOCK_CLOEXEC
} else {
nix::SOCK_CLOEXEC
};
nix::accept4(io.as_raw_fd(), opts)
.map_err(super::from_nix_error)
}
// UDP & UDS
#[inline]
pub fn dup(io: &Io) -> io::Result<Io> {
nix::dup(io.as_raw_fd())
.map_err(super::from_nix_error)
.map(|fd| unsafe { Io::from_raw_fd(fd) })
}
|
} else {
|
random_line_split
|
binary.rs
|
// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors β BSD license
//! Monte-Carlo simulation of a binary mixture of H20 and CO2.
extern crate lumol;
extern crate lumol_input as input;
use lumol::Logger;
use lumol::sys::{Molecule, Particle, Trajectory, UnitCell};
use lumol::sys::{read_molecule, molecule_type};
use lumol::sim::Simulation;
use lumol::sim::mc::{MonteCarlo, Translate, Rotate};
use lumol::units;
use input::InteractionsInput;
fn ma
|
{
Logger::stdout();
let mut system = Trajectory::open("data/binary.xyz")
.and_then(|mut traj| traj.read())
.unwrap();
// Add bonds in the system
for i in 0..system.molecules().len() / 3 {
system.add_bond(3 * i, 3 * i + 1);
system.add_bond(3 * i + 1, 3 * i + 2);
}
system.set_cell(UnitCell::cubic(25.0));
let input = InteractionsInput::new("data/binary.toml").unwrap();
input.read(&mut system).unwrap();
let co2 = {
// We can read files to get molecule type
let (molecule, atoms) = read_molecule("data/CO2.xyz").unwrap();
molecule_type(&molecule, &atoms)
};
let h2o = {
// Or define a new molecule by hand
let mut molecule = Molecule::new(0);
molecule.merge_with(Molecule::new(1));
molecule.merge_with(Molecule::new(2));
molecule.add_bond(0, 1);
molecule.add_bond(1, 2);
molecule_type(&molecule, &[Particle::new("H"), Particle::new("O"), Particle::new("H")])
};
let mut mc = MonteCarlo::new(units::from(500.0, "K").unwrap());
// Use the molecular types of CO2 and H2O to specify different probabilities
mc.add(Box::new(Translate::with_moltype(units::from(0.5, "A").unwrap(), co2)), 1.0);
mc.add(Box::new(Rotate::with_moltype(units::from(10.0, "deg").unwrap(), co2)), 1.0);
mc.add(Box::new(Translate::with_moltype(units::from(10.0, "A").unwrap(), h2o)), 2.0);
mc.add(Box::new(Rotate::with_moltype(units::from(20.0, "deg").unwrap(), h2o)), 2.0);
let mut simulation = Simulation::new(Box::new(mc));
simulation.run(&mut system, 200_000_000);
}
|
in()
|
identifier_name
|
binary.rs
|
// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors β BSD license
//! Monte-Carlo simulation of a binary mixture of H20 and CO2.
extern crate lumol;
extern crate lumol_input as input;
use lumol::Logger;
use lumol::sys::{Molecule, Particle, Trajectory, UnitCell};
use lumol::sys::{read_molecule, molecule_type};
use lumol::sim::Simulation;
use lumol::sim::mc::{MonteCarlo, Translate, Rotate};
use lumol::units;
use input::InteractionsInput;
fn main() {
|
let h2o = {
// Or define a new molecule by hand
let mut molecule = Molecule::new(0);
molecule.merge_with(Molecule::new(1));
molecule.merge_with(Molecule::new(2));
molecule.add_bond(0, 1);
molecule.add_bond(1, 2);
molecule_type(&molecule, &[Particle::new("H"), Particle::new("O"), Particle::new("H")])
};
let mut mc = MonteCarlo::new(units::from(500.0, "K").unwrap());
// Use the molecular types of CO2 and H2O to specify different probabilities
mc.add(Box::new(Translate::with_moltype(units::from(0.5, "A").unwrap(), co2)), 1.0);
mc.add(Box::new(Rotate::with_moltype(units::from(10.0, "deg").unwrap(), co2)), 1.0);
mc.add(Box::new(Translate::with_moltype(units::from(10.0, "A").unwrap(), h2o)), 2.0);
mc.add(Box::new(Rotate::with_moltype(units::from(20.0, "deg").unwrap(), h2o)), 2.0);
let mut simulation = Simulation::new(Box::new(mc));
simulation.run(&mut system, 200_000_000);
}
|
Logger::stdout();
let mut system = Trajectory::open("data/binary.xyz")
.and_then(|mut traj| traj.read())
.unwrap();
// Add bonds in the system
for i in 0..system.molecules().len() / 3 {
system.add_bond(3 * i, 3 * i + 1);
system.add_bond(3 * i + 1, 3 * i + 2);
}
system.set_cell(UnitCell::cubic(25.0));
let input = InteractionsInput::new("data/binary.toml").unwrap();
input.read(&mut system).unwrap();
let co2 = {
// We can read files to get molecule type
let (molecule, atoms) = read_molecule("data/CO2.xyz").unwrap();
molecule_type(&molecule, &atoms)
};
|
identifier_body
|
binary.rs
|
// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 Lumol's contributors β BSD license
//! Monte-Carlo simulation of a binary mixture of H20 and CO2.
extern crate lumol;
extern crate lumol_input as input;
use lumol::Logger;
use lumol::sys::{Molecule, Particle, Trajectory, UnitCell};
use lumol::sys::{read_molecule, molecule_type};
use lumol::sim::Simulation;
use lumol::sim::mc::{MonteCarlo, Translate, Rotate};
use lumol::units;
|
use input::InteractionsInput;
fn main() {
Logger::stdout();
let mut system = Trajectory::open("data/binary.xyz")
.and_then(|mut traj| traj.read())
.unwrap();
// Add bonds in the system
for i in 0..system.molecules().len() / 3 {
system.add_bond(3 * i, 3 * i + 1);
system.add_bond(3 * i + 1, 3 * i + 2);
}
system.set_cell(UnitCell::cubic(25.0));
let input = InteractionsInput::new("data/binary.toml").unwrap();
input.read(&mut system).unwrap();
let co2 = {
// We can read files to get molecule type
let (molecule, atoms) = read_molecule("data/CO2.xyz").unwrap();
molecule_type(&molecule, &atoms)
};
let h2o = {
// Or define a new molecule by hand
let mut molecule = Molecule::new(0);
molecule.merge_with(Molecule::new(1));
molecule.merge_with(Molecule::new(2));
molecule.add_bond(0, 1);
molecule.add_bond(1, 2);
molecule_type(&molecule, &[Particle::new("H"), Particle::new("O"), Particle::new("H")])
};
let mut mc = MonteCarlo::new(units::from(500.0, "K").unwrap());
// Use the molecular types of CO2 and H2O to specify different probabilities
mc.add(Box::new(Translate::with_moltype(units::from(0.5, "A").unwrap(), co2)), 1.0);
mc.add(Box::new(Rotate::with_moltype(units::from(10.0, "deg").unwrap(), co2)), 1.0);
mc.add(Box::new(Translate::with_moltype(units::from(10.0, "A").unwrap(), h2o)), 2.0);
mc.add(Box::new(Rotate::with_moltype(units::from(20.0, "deg").unwrap(), h2o)), 2.0);
let mut simulation = Simulation::new(Box::new(mc));
simulation.run(&mut system, 200_000_000);
}
|
random_line_split
|
|
parser.rs
|
use std::str::from_utf8;
use std::result::Result;
use nom::*;
/*
* Core structs
*/
#[derive(Debug,PartialEq,Eq)]
pub struct TarEntry<'a> {
pub header: PosixHeader<'a>,
pub contents: &'a [u8]
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixHeader<'a> {
pub name: &'a str,
pub mode: &'a str,
pub uid: u64,
pub gid: u64,
pub size: u64,
pub mtime: u64,
pub chksum: &'a str,
pub typeflag: TypeFlag,
pub linkname: &'a str,
pub ustar: ExtraHeader<'a>
}
/* TODO: support vendor specific */
#[derive(Debug,PartialEq,Eq)]
pub enum TypeFlag {
NormalFile,
HardLink,
SymbolicLink,
CharacterSpecial,
BlockSpecial,
Directory,
FIFO,
ContiguousFile,
PaxInterexchangeFormat,
PaxExtendedAttributes,
VendorSpecific
}
#[derive(Debug,PartialEq,Eq)]
pub enum ExtraHeader<'a> {
UStar(UStarHeader<'a>),
Padding
}
#[derive(Debug,PartialEq,Eq)]
pub struct UStarHeader<'a> {
pub magic: &'a str,
pub version: &'a str,
pub uname: &'a str,
pub gname: &'a str,
pub devmajor: u64,
pub devminor: u64,
pub extra: UStarExtraHeader<'a>
}
#[derive(Debug,PartialEq,Eq)]
pub enum UStarExtraHeader<'a> {
PosixUStar(PosixUStarHeader<'a>),
Pax(PaxHeader<'a>)
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixUStarHeader<'a> {
pub prefix: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PaxHeader<'a> {
pub atime: u64,
pub ctime: u64,
pub offset: u64,
pub longnames: &'a str,
pub sparses: Vec<Sparse>,
pub isextended: bool,
pub realsize: u64,
}
#[derive(Debug,PartialEq,Eq)]
pub struct Sparse {
pub offset: u64,
pub numbytes: u64
}
#[derive(Debug,PartialEq,Eq)]
pub struct Padding;
/*
* Useful macros
*/
macro_rules! take_str_eat_garbage (
( $i:expr, $size:expr ) => (
chain!($i,
s: map_res!(take_until!("\0"), from_utf8) ~
take!($size - s.len()),
||{
s
}
)
);
);
named!(parse_str4<&[u8], &str>, take_str_eat_garbage!(4));
named!(parse_str8<&[u8], &str>, take_str_eat_garbage!(8));
named!(parse_str32<&[u8], &str>, take_str_eat_garbage!(32));
named!(parse_str100<&[u8], &str>, take_str_eat_garbage!(100));
named!(parse_str155<&[u8], &str>, take_str_eat_garbage!(155));
macro_rules! take_until_expr_with_limit_consume(
($i:expr, $submac:ident!( $($args:tt)* ), $stop: expr, $limit: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
let mut cnt = 0;
let mut err = false;
let mut append = true;
loop {
match $submac!(&$i[begin..], $($args)*) {
IResult::Done(i,o) => {
if append {
if $stop(&o) {
append = false;
} else {
res.push(o);
}
}
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $limit {
break
}
},
IResult::Error(_) => {
err = true;
break;
},
IResult::Incomplete(_) => {
break;
}
}
}
if err {
IResult::Error(Err::Position(ErrorKind::Count,$i))
} else if cnt == $limit {
IResult::Done(&$i[begin..], res)
} else {
IResult::Incomplete(Needed::Unknown)
}
}
);
($i:expr, $f:expr, $stop: expr, $limit: expr) => (
take_until_expr_with_limit_consume!($i, call!($f), $stop, $limit);
);
);
/*
* Octal string parsing
*/
pub fn octal_to_u64(s: &str) -> Result<u64, &'static str> {
let mut u = 0;
for c in s.chars() {
if c < '0' || c > '7' {
return Err("invalid octal string received");
}
u *= 8;
u += (c as u64) - ('0' as u64);
}
Ok(u)
}
fn parse_octal(i: &[u8], n: usize) -> IResult<&[u8], u64> {
map_res!(i, take_str_eat_garbage!(n), octal_to_u64)
}
named!(parse_octal8<&[u8], u64>, apply!(parse_octal, 8));
named!(parse_octal12<&[u8], u64>, apply!(parse_octal, 12));
/*
* TypeFlag parsing
*/
fn char_to_type_flag(c: char) -> TypeFlag {
match c {
'0' | '\0' => TypeFlag::NormalFile,
'1' => TypeFlag::HardLink,
'2' => TypeFlag::SymbolicLink,
'3' => TypeFlag::CharacterSpecial,
'4' => TypeFlag::BlockSpecial,
'5' => TypeFlag::Directory,
'6' => TypeFlag::FIFO,
'7' => TypeFlag::ContiguousFile,
'g' => TypeFlag::PaxInterexchangeFormat,
'x' => TypeFlag::PaxExtendedAttributes,
'A'... 'Z' => TypeFlag::VendorSpecific,
_ => TypeFlag::NormalFile
}
}
fn bytes_to_type_flag(i: &[u8]) -> TypeFlag {
char_to_type_flag(i[0] as char)
}
named!(parse_type_flag<&[u8], TypeFlag>, map!(take!(1), bytes_to_type_flag));
/*
* Sparse parsing
*/
fn parse_one_sparse(i: &[u8]) -> IResult<&[u8], Sparse> {
chain!(i,
offset: parse_octal12 ~
numbytes: parse_octal12,
||{
Sparse {
offset: offset,
numbytes: numbytes
}
}
)
}
fn parse_sparses_with_limit(i: &[u8], limit: usize) -> IResult<&[u8], Vec<Sparse>> {
take_until_expr_with_limit_consume!(i, parse_one_sparse, |s: &Sparse| s.offset == 0 && s.numbytes == 0, limit)
}
fn add_to_vec<'a, 'b>(sparses: &'a mut Vec<Sparse>, extra: &'b mut Vec<Sparse>) -> &'a mut Vec<Sparse> {
while sparses.len()!= 0 {
extra.pop().map(|s| sparses.push(s));
}
sparses
}
fn parse_extra_sparses<'a,'b>(i: &'a[u8], isextended: bool, sparses: &'b mut Vec<Sparse>) -> IResult< &'a [u8], &'b mut Vec<Sparse>> {
if isextended {
chain!(i,
mut sps: apply!(parse_sparses_with_limit, 21) ~
extended: parse_bool ~
take!(7) /* padding to 512 */ ~
extra_sparses: apply!(parse_extra_sparses, extended, add_to_vec(sparses, &mut sps)),
||{
extra_sparses
}
)
} else {
IResult::Done(i, sparses)
}
}
fn parse_pax_extra_sparses<'a, 'b>(i: &'a [u8], h: &'b mut PaxHeader) -> IResult<&'a [u8], &'b mut Vec<Sparse>> {
parse_extra_sparses(i, h.isextended, &mut h.sparses)
}
/*
* Boolean parsing
*/
fn to_bool(i: &[u8]) -> bool {
i[0]!= 0
}
named!(parse_bool<&[u8], bool>, map!(take!(1), to_bool));
/*
* UStar PAX extended parsing
*/
fn parse_ustar00_extra_pax(i: &[u8]) -> IResult<&[u8], PaxHeader> {
chain!(i,
atime: parse_octal12 ~
ctime: parse_octal12 ~
offset: parse_octal12 ~
longnames: parse_str4 ~
take!(1) ~
sparses: apply!(parse_sparses_with_limit, 4) ~
isextended: parse_bool ~
realsize: parse_octal12 ~
take!(17), /* padding to 512 */
||{
PaxHeader {
atime: atime,
ctime: ctime,
offset: offset,
longnames: longnames,
sparses: sparses,
isextended: isextended,
realsize: realsize,
}
}
)
}
/*
* UStar Posix parsing
*/
fn
|
(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
chain!(i,
prefix: parse_str155 ~
take!(12),
||{
UStarExtraHeader::PosixUStar(PosixUStarHeader {
prefix: prefix
})
}
)
}
fn parse_ustar00_extra<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult< &'a [u8], UStarExtraHeader<'a>> {
match *flag {
TypeFlag::PaxInterexchangeFormat => {
chain!(i,
mut header: parse_ustar00_extra_pax ~
apply!(parse_pax_extra_sparses, &mut header),
||{
UStarExtraHeader::Pax(header)
}
)
},
_ => parse_ustar00_extra_posix(i)
}
}
fn parse_ustar00<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult<&'a [u8], ExtraHeader<'a>> {
chain!(i,
tag!("00") ~
uname: parse_str32 ~
gname: parse_str32 ~
devmajor: parse_octal8 ~
devminor: parse_octal8 ~
extra: apply!(parse_ustar00_extra, flag),
||{
ExtraHeader::UStar(UStarHeader {
magic: "ustar\0",
version: "00",
uname: uname,
gname: gname,
devmajor: devmajor,
devminor: devminor,
extra: extra
})
}
)
}
fn parse_ustar<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult<&'a [u8], ExtraHeader<'a>> {
chain!(i,
tag!("ustar\0") ~
ustar: apply!(parse_ustar00, flag),
||{
ustar
}
)
}
/*
* Posix tar archive header parsing
*/
fn parse_posix(i: &[u8]) -> IResult<&[u8], ExtraHeader> {
chain!(i,
take!(255), /* padding to 512 */
||{
ExtraHeader::Padding
}
)
}
fn parse_header(i: &[u8]) -> IResult<&[u8], PosixHeader> {
chain!(i,
name: parse_str100 ~
mode: parse_str8 ~
uid: parse_octal8 ~
gid: parse_octal8 ~
size: parse_octal12 ~
mtime: parse_octal12 ~
chksum: parse_str8 ~
typeflag: parse_type_flag ~
linkname: parse_str100 ~
ustar: alt!(apply!(parse_ustar, &typeflag) | parse_posix),
||{
PosixHeader {
name: name,
mode: mode,
uid: uid,
gid: gid,
size: size,
mtime: mtime,
chksum: chksum,
typeflag: typeflag,
linkname: linkname,
ustar: ustar
}
}
)
}
/*
* Contents parsing
*/
fn parse_contents(i: &[u8], size: u64) -> IResult<&[u8], &[u8]> {
let trailing = size % 512;
let padding = match trailing {
0 => 0,
t => 512 - t
};
chain!(i,
contents: take!(size as usize) ~
take!(padding as usize),
||{
contents
}
)
}
/*
* Tar entry header + contents parsing
*/
fn parse_entry(i: &[u8]) -> IResult<&[u8], TarEntry> {
chain!(i,
header: parse_header ~
contents: apply!(parse_contents, header.size),
||{
TarEntry {
header: header,
contents: contents
}
}
)
}
/*
* Tar archive parsing
*/
fn filter_entries(entries: Vec<TarEntry>) -> Vec<TarEntry> {
/* Filter out empty entries */
entries.into_iter().filter(|e| e.header.name!= "").collect::<Vec<TarEntry>>()
}
pub fn parse_tar(i: &[u8]) -> IResult<&[u8], Vec<TarEntry>> {
chain!(i,
entries: map!(many0!(parse_entry), filter_entries) ~
eof,
||{
entries
}
)
}
/*
* Tests
*/
#[cfg(test)]
mod tests {
use super::*;
use std::str::from_utf8;
use nom::IResult;
#[test]
fn octal_to_u64_ok_test() {
assert_eq!(octal_to_u64("756"), Ok(494));
assert_eq!(octal_to_u64(""), Ok(0));
}
#[test]
fn octal_to_u64_error_test() {
assert_eq!(octal_to_u64("1238"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("a"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("A"), Err("invalid octal string received"));
}
#[test]
fn take_str_eat_garbage_test() {
let s = b"foobar\0\0\0\0baz";
let baz = b"baz";
assert_eq!(take_str_eat_garbage!(&s[..], 10), IResult::Done(&baz[..], "foobar"));
}
}
|
parse_ustar00_extra_posix
|
identifier_name
|
parser.rs
|
use std::str::from_utf8;
use std::result::Result;
use nom::*;
/*
* Core structs
*/
#[derive(Debug,PartialEq,Eq)]
pub struct TarEntry<'a> {
pub header: PosixHeader<'a>,
pub contents: &'a [u8]
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixHeader<'a> {
pub name: &'a str,
pub mode: &'a str,
pub uid: u64,
pub gid: u64,
pub size: u64,
pub mtime: u64,
pub chksum: &'a str,
pub typeflag: TypeFlag,
pub linkname: &'a str,
pub ustar: ExtraHeader<'a>
}
/* TODO: support vendor specific */
#[derive(Debug,PartialEq,Eq)]
pub enum TypeFlag {
NormalFile,
HardLink,
SymbolicLink,
CharacterSpecial,
BlockSpecial,
Directory,
FIFO,
ContiguousFile,
PaxInterexchangeFormat,
PaxExtendedAttributes,
VendorSpecific
}
#[derive(Debug,PartialEq,Eq)]
pub enum ExtraHeader<'a> {
UStar(UStarHeader<'a>),
Padding
}
|
pub magic: &'a str,
pub version: &'a str,
pub uname: &'a str,
pub gname: &'a str,
pub devmajor: u64,
pub devminor: u64,
pub extra: UStarExtraHeader<'a>
}
#[derive(Debug,PartialEq,Eq)]
pub enum UStarExtraHeader<'a> {
PosixUStar(PosixUStarHeader<'a>),
Pax(PaxHeader<'a>)
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixUStarHeader<'a> {
pub prefix: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PaxHeader<'a> {
pub atime: u64,
pub ctime: u64,
pub offset: u64,
pub longnames: &'a str,
pub sparses: Vec<Sparse>,
pub isextended: bool,
pub realsize: u64,
}
#[derive(Debug,PartialEq,Eq)]
pub struct Sparse {
pub offset: u64,
pub numbytes: u64
}
#[derive(Debug,PartialEq,Eq)]
pub struct Padding;
/*
* Useful macros
*/
macro_rules! take_str_eat_garbage (
( $i:expr, $size:expr ) => (
chain!($i,
s: map_res!(take_until!("\0"), from_utf8) ~
take!($size - s.len()),
||{
s
}
)
);
);
named!(parse_str4<&[u8], &str>, take_str_eat_garbage!(4));
named!(parse_str8<&[u8], &str>, take_str_eat_garbage!(8));
named!(parse_str32<&[u8], &str>, take_str_eat_garbage!(32));
named!(parse_str100<&[u8], &str>, take_str_eat_garbage!(100));
named!(parse_str155<&[u8], &str>, take_str_eat_garbage!(155));
macro_rules! take_until_expr_with_limit_consume(
($i:expr, $submac:ident!( $($args:tt)* ), $stop: expr, $limit: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
let mut cnt = 0;
let mut err = false;
let mut append = true;
loop {
match $submac!(&$i[begin..], $($args)*) {
IResult::Done(i,o) => {
if append {
if $stop(&o) {
append = false;
} else {
res.push(o);
}
}
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $limit {
break
}
},
IResult::Error(_) => {
err = true;
break;
},
IResult::Incomplete(_) => {
break;
}
}
}
if err {
IResult::Error(Err::Position(ErrorKind::Count,$i))
} else if cnt == $limit {
IResult::Done(&$i[begin..], res)
} else {
IResult::Incomplete(Needed::Unknown)
}
}
);
($i:expr, $f:expr, $stop: expr, $limit: expr) => (
take_until_expr_with_limit_consume!($i, call!($f), $stop, $limit);
);
);
/*
* Octal string parsing
*/
pub fn octal_to_u64(s: &str) -> Result<u64, &'static str> {
let mut u = 0;
for c in s.chars() {
if c < '0' || c > '7' {
return Err("invalid octal string received");
}
u *= 8;
u += (c as u64) - ('0' as u64);
}
Ok(u)
}
fn parse_octal(i: &[u8], n: usize) -> IResult<&[u8], u64> {
map_res!(i, take_str_eat_garbage!(n), octal_to_u64)
}
named!(parse_octal8<&[u8], u64>, apply!(parse_octal, 8));
named!(parse_octal12<&[u8], u64>, apply!(parse_octal, 12));
/*
* TypeFlag parsing
*/
fn char_to_type_flag(c: char) -> TypeFlag {
match c {
'0' | '\0' => TypeFlag::NormalFile,
'1' => TypeFlag::HardLink,
'2' => TypeFlag::SymbolicLink,
'3' => TypeFlag::CharacterSpecial,
'4' => TypeFlag::BlockSpecial,
'5' => TypeFlag::Directory,
'6' => TypeFlag::FIFO,
'7' => TypeFlag::ContiguousFile,
'g' => TypeFlag::PaxInterexchangeFormat,
'x' => TypeFlag::PaxExtendedAttributes,
'A'... 'Z' => TypeFlag::VendorSpecific,
_ => TypeFlag::NormalFile
}
}
fn bytes_to_type_flag(i: &[u8]) -> TypeFlag {
char_to_type_flag(i[0] as char)
}
named!(parse_type_flag<&[u8], TypeFlag>, map!(take!(1), bytes_to_type_flag));
/*
* Sparse parsing
*/
fn parse_one_sparse(i: &[u8]) -> IResult<&[u8], Sparse> {
chain!(i,
offset: parse_octal12 ~
numbytes: parse_octal12,
||{
Sparse {
offset: offset,
numbytes: numbytes
}
}
)
}
fn parse_sparses_with_limit(i: &[u8], limit: usize) -> IResult<&[u8], Vec<Sparse>> {
take_until_expr_with_limit_consume!(i, parse_one_sparse, |s: &Sparse| s.offset == 0 && s.numbytes == 0, limit)
}
fn add_to_vec<'a, 'b>(sparses: &'a mut Vec<Sparse>, extra: &'b mut Vec<Sparse>) -> &'a mut Vec<Sparse> {
while sparses.len()!= 0 {
extra.pop().map(|s| sparses.push(s));
}
sparses
}
fn parse_extra_sparses<'a,'b>(i: &'a[u8], isextended: bool, sparses: &'b mut Vec<Sparse>) -> IResult< &'a [u8], &'b mut Vec<Sparse>> {
if isextended {
chain!(i,
mut sps: apply!(parse_sparses_with_limit, 21) ~
extended: parse_bool ~
take!(7) /* padding to 512 */ ~
extra_sparses: apply!(parse_extra_sparses, extended, add_to_vec(sparses, &mut sps)),
||{
extra_sparses
}
)
} else {
IResult::Done(i, sparses)
}
}
fn parse_pax_extra_sparses<'a, 'b>(i: &'a [u8], h: &'b mut PaxHeader) -> IResult<&'a [u8], &'b mut Vec<Sparse>> {
parse_extra_sparses(i, h.isextended, &mut h.sparses)
}
/*
* Boolean parsing
*/
fn to_bool(i: &[u8]) -> bool {
i[0]!= 0
}
named!(parse_bool<&[u8], bool>, map!(take!(1), to_bool));
/*
* UStar PAX extended parsing
*/
fn parse_ustar00_extra_pax(i: &[u8]) -> IResult<&[u8], PaxHeader> {
chain!(i,
atime: parse_octal12 ~
ctime: parse_octal12 ~
offset: parse_octal12 ~
longnames: parse_str4 ~
take!(1) ~
sparses: apply!(parse_sparses_with_limit, 4) ~
isextended: parse_bool ~
realsize: parse_octal12 ~
take!(17), /* padding to 512 */
||{
PaxHeader {
atime: atime,
ctime: ctime,
offset: offset,
longnames: longnames,
sparses: sparses,
isextended: isextended,
realsize: realsize,
}
}
)
}
/*
* UStar Posix parsing
*/
fn parse_ustar00_extra_posix(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
chain!(i,
prefix: parse_str155 ~
take!(12),
||{
UStarExtraHeader::PosixUStar(PosixUStarHeader {
prefix: prefix
})
}
)
}
fn parse_ustar00_extra<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult< &'a [u8], UStarExtraHeader<'a>> {
match *flag {
TypeFlag::PaxInterexchangeFormat => {
chain!(i,
mut header: parse_ustar00_extra_pax ~
apply!(parse_pax_extra_sparses, &mut header),
||{
UStarExtraHeader::Pax(header)
}
)
},
_ => parse_ustar00_extra_posix(i)
}
}
fn parse_ustar00<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult<&'a [u8], ExtraHeader<'a>> {
chain!(i,
tag!("00") ~
uname: parse_str32 ~
gname: parse_str32 ~
devmajor: parse_octal8 ~
devminor: parse_octal8 ~
extra: apply!(parse_ustar00_extra, flag),
||{
ExtraHeader::UStar(UStarHeader {
magic: "ustar\0",
version: "00",
uname: uname,
gname: gname,
devmajor: devmajor,
devminor: devminor,
extra: extra
})
}
)
}
fn parse_ustar<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult<&'a [u8], ExtraHeader<'a>> {
chain!(i,
tag!("ustar\0") ~
ustar: apply!(parse_ustar00, flag),
||{
ustar
}
)
}
/*
* Posix tar archive header parsing
*/
fn parse_posix(i: &[u8]) -> IResult<&[u8], ExtraHeader> {
chain!(i,
take!(255), /* padding to 512 */
||{
ExtraHeader::Padding
}
)
}
fn parse_header(i: &[u8]) -> IResult<&[u8], PosixHeader> {
chain!(i,
name: parse_str100 ~
mode: parse_str8 ~
uid: parse_octal8 ~
gid: parse_octal8 ~
size: parse_octal12 ~
mtime: parse_octal12 ~
chksum: parse_str8 ~
typeflag: parse_type_flag ~
linkname: parse_str100 ~
ustar: alt!(apply!(parse_ustar, &typeflag) | parse_posix),
||{
PosixHeader {
name: name,
mode: mode,
uid: uid,
gid: gid,
size: size,
mtime: mtime,
chksum: chksum,
typeflag: typeflag,
linkname: linkname,
ustar: ustar
}
}
)
}
/*
* Contents parsing
*/
fn parse_contents(i: &[u8], size: u64) -> IResult<&[u8], &[u8]> {
let trailing = size % 512;
let padding = match trailing {
0 => 0,
t => 512 - t
};
chain!(i,
contents: take!(size as usize) ~
take!(padding as usize),
||{
contents
}
)
}
/*
* Tar entry header + contents parsing
*/
fn parse_entry(i: &[u8]) -> IResult<&[u8], TarEntry> {
chain!(i,
header: parse_header ~
contents: apply!(parse_contents, header.size),
||{
TarEntry {
header: header,
contents: contents
}
}
)
}
/*
* Tar archive parsing
*/
fn filter_entries(entries: Vec<TarEntry>) -> Vec<TarEntry> {
/* Filter out empty entries */
entries.into_iter().filter(|e| e.header.name!= "").collect::<Vec<TarEntry>>()
}
pub fn parse_tar(i: &[u8]) -> IResult<&[u8], Vec<TarEntry>> {
chain!(i,
entries: map!(many0!(parse_entry), filter_entries) ~
eof,
||{
entries
}
)
}
/*
* Tests
*/
#[cfg(test)]
mod tests {
use super::*;
use std::str::from_utf8;
use nom::IResult;
#[test]
fn octal_to_u64_ok_test() {
assert_eq!(octal_to_u64("756"), Ok(494));
assert_eq!(octal_to_u64(""), Ok(0));
}
#[test]
fn octal_to_u64_error_test() {
assert_eq!(octal_to_u64("1238"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("a"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("A"), Err("invalid octal string received"));
}
#[test]
fn take_str_eat_garbage_test() {
let s = b"foobar\0\0\0\0baz";
let baz = b"baz";
assert_eq!(take_str_eat_garbage!(&s[..], 10), IResult::Done(&baz[..], "foobar"));
}
}
|
#[derive(Debug,PartialEq,Eq)]
pub struct UStarHeader<'a> {
|
random_line_split
|
parser.rs
|
use std::str::from_utf8;
use std::result::Result;
use nom::*;
/*
* Core structs
*/
#[derive(Debug,PartialEq,Eq)]
pub struct TarEntry<'a> {
pub header: PosixHeader<'a>,
pub contents: &'a [u8]
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixHeader<'a> {
pub name: &'a str,
pub mode: &'a str,
pub uid: u64,
pub gid: u64,
pub size: u64,
pub mtime: u64,
pub chksum: &'a str,
pub typeflag: TypeFlag,
pub linkname: &'a str,
pub ustar: ExtraHeader<'a>
}
/* TODO: support vendor specific */
#[derive(Debug,PartialEq,Eq)]
pub enum TypeFlag {
NormalFile,
HardLink,
SymbolicLink,
CharacterSpecial,
BlockSpecial,
Directory,
FIFO,
ContiguousFile,
PaxInterexchangeFormat,
PaxExtendedAttributes,
VendorSpecific
}
#[derive(Debug,PartialEq,Eq)]
pub enum ExtraHeader<'a> {
UStar(UStarHeader<'a>),
Padding
}
#[derive(Debug,PartialEq,Eq)]
pub struct UStarHeader<'a> {
pub magic: &'a str,
pub version: &'a str,
pub uname: &'a str,
pub gname: &'a str,
pub devmajor: u64,
pub devminor: u64,
pub extra: UStarExtraHeader<'a>
}
#[derive(Debug,PartialEq,Eq)]
pub enum UStarExtraHeader<'a> {
PosixUStar(PosixUStarHeader<'a>),
Pax(PaxHeader<'a>)
}
#[derive(Debug,PartialEq,Eq)]
pub struct PosixUStarHeader<'a> {
pub prefix: &'a str
}
#[derive(Debug,PartialEq,Eq)]
pub struct PaxHeader<'a> {
pub atime: u64,
pub ctime: u64,
pub offset: u64,
pub longnames: &'a str,
pub sparses: Vec<Sparse>,
pub isextended: bool,
pub realsize: u64,
}
#[derive(Debug,PartialEq,Eq)]
pub struct Sparse {
pub offset: u64,
pub numbytes: u64
}
#[derive(Debug,PartialEq,Eq)]
pub struct Padding;
/*
* Useful macros
*/
macro_rules! take_str_eat_garbage (
( $i:expr, $size:expr ) => (
chain!($i,
s: map_res!(take_until!("\0"), from_utf8) ~
take!($size - s.len()),
||{
s
}
)
);
);
named!(parse_str4<&[u8], &str>, take_str_eat_garbage!(4));
named!(parse_str8<&[u8], &str>, take_str_eat_garbage!(8));
named!(parse_str32<&[u8], &str>, take_str_eat_garbage!(32));
named!(parse_str100<&[u8], &str>, take_str_eat_garbage!(100));
named!(parse_str155<&[u8], &str>, take_str_eat_garbage!(155));
macro_rules! take_until_expr_with_limit_consume(
($i:expr, $submac:ident!( $($args:tt)* ), $stop: expr, $limit: expr) => (
{
let mut begin = 0;
let mut remaining = $i.len();
let mut res = Vec::new();
let mut cnt = 0;
let mut err = false;
let mut append = true;
loop {
match $submac!(&$i[begin..], $($args)*) {
IResult::Done(i,o) => {
if append {
if $stop(&o) {
append = false;
} else {
res.push(o);
}
}
begin += remaining - i.len();
remaining = i.len();
cnt = cnt + 1;
if cnt == $limit {
break
}
},
IResult::Error(_) => {
err = true;
break;
},
IResult::Incomplete(_) => {
break;
}
}
}
if err {
IResult::Error(Err::Position(ErrorKind::Count,$i))
} else if cnt == $limit {
IResult::Done(&$i[begin..], res)
} else {
IResult::Incomplete(Needed::Unknown)
}
}
);
($i:expr, $f:expr, $stop: expr, $limit: expr) => (
take_until_expr_with_limit_consume!($i, call!($f), $stop, $limit);
);
);
/*
* Octal string parsing
*/
pub fn octal_to_u64(s: &str) -> Result<u64, &'static str> {
let mut u = 0;
for c in s.chars() {
if c < '0' || c > '7' {
return Err("invalid octal string received");
}
u *= 8;
u += (c as u64) - ('0' as u64);
}
Ok(u)
}
fn parse_octal(i: &[u8], n: usize) -> IResult<&[u8], u64> {
map_res!(i, take_str_eat_garbage!(n), octal_to_u64)
}
named!(parse_octal8<&[u8], u64>, apply!(parse_octal, 8));
named!(parse_octal12<&[u8], u64>, apply!(parse_octal, 12));
/*
* TypeFlag parsing
*/
fn char_to_type_flag(c: char) -> TypeFlag {
match c {
'0' | '\0' => TypeFlag::NormalFile,
'1' => TypeFlag::HardLink,
'2' => TypeFlag::SymbolicLink,
'3' => TypeFlag::CharacterSpecial,
'4' => TypeFlag::BlockSpecial,
'5' => TypeFlag::Directory,
'6' => TypeFlag::FIFO,
'7' => TypeFlag::ContiguousFile,
'g' => TypeFlag::PaxInterexchangeFormat,
'x' => TypeFlag::PaxExtendedAttributes,
'A'... 'Z' => TypeFlag::VendorSpecific,
_ => TypeFlag::NormalFile
}
}
fn bytes_to_type_flag(i: &[u8]) -> TypeFlag {
char_to_type_flag(i[0] as char)
}
named!(parse_type_flag<&[u8], TypeFlag>, map!(take!(1), bytes_to_type_flag));
/*
* Sparse parsing
*/
fn parse_one_sparse(i: &[u8]) -> IResult<&[u8], Sparse> {
chain!(i,
offset: parse_octal12 ~
numbytes: parse_octal12,
||{
Sparse {
offset: offset,
numbytes: numbytes
}
}
)
}
fn parse_sparses_with_limit(i: &[u8], limit: usize) -> IResult<&[u8], Vec<Sparse>> {
take_until_expr_with_limit_consume!(i, parse_one_sparse, |s: &Sparse| s.offset == 0 && s.numbytes == 0, limit)
}
fn add_to_vec<'a, 'b>(sparses: &'a mut Vec<Sparse>, extra: &'b mut Vec<Sparse>) -> &'a mut Vec<Sparse> {
while sparses.len()!= 0 {
extra.pop().map(|s| sparses.push(s));
}
sparses
}
fn parse_extra_sparses<'a,'b>(i: &'a[u8], isextended: bool, sparses: &'b mut Vec<Sparse>) -> IResult< &'a [u8], &'b mut Vec<Sparse>> {
if isextended {
chain!(i,
mut sps: apply!(parse_sparses_with_limit, 21) ~
extended: parse_bool ~
take!(7) /* padding to 512 */ ~
extra_sparses: apply!(parse_extra_sparses, extended, add_to_vec(sparses, &mut sps)),
||{
extra_sparses
}
)
} else {
IResult::Done(i, sparses)
}
}
fn parse_pax_extra_sparses<'a, 'b>(i: &'a [u8], h: &'b mut PaxHeader) -> IResult<&'a [u8], &'b mut Vec<Sparse>> {
parse_extra_sparses(i, h.isextended, &mut h.sparses)
}
/*
* Boolean parsing
*/
fn to_bool(i: &[u8]) -> bool {
i[0]!= 0
}
named!(parse_bool<&[u8], bool>, map!(take!(1), to_bool));
/*
* UStar PAX extended parsing
*/
fn parse_ustar00_extra_pax(i: &[u8]) -> IResult<&[u8], PaxHeader> {
chain!(i,
atime: parse_octal12 ~
ctime: parse_octal12 ~
offset: parse_octal12 ~
longnames: parse_str4 ~
take!(1) ~
sparses: apply!(parse_sparses_with_limit, 4) ~
isextended: parse_bool ~
realsize: parse_octal12 ~
take!(17), /* padding to 512 */
||{
PaxHeader {
atime: atime,
ctime: ctime,
offset: offset,
longnames: longnames,
sparses: sparses,
isextended: isextended,
realsize: realsize,
}
}
)
}
/*
* UStar Posix parsing
*/
fn parse_ustar00_extra_posix(i: &[u8]) -> IResult<&[u8], UStarExtraHeader> {
chain!(i,
prefix: parse_str155 ~
take!(12),
||{
UStarExtraHeader::PosixUStar(PosixUStarHeader {
prefix: prefix
})
}
)
}
fn parse_ustar00_extra<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult< &'a [u8], UStarExtraHeader<'a>>
|
fn parse_ustar00<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult<&'a [u8], ExtraHeader<'a>> {
chain!(i,
tag!("00") ~
uname: parse_str32 ~
gname: parse_str32 ~
devmajor: parse_octal8 ~
devminor: parse_octal8 ~
extra: apply!(parse_ustar00_extra, flag),
||{
ExtraHeader::UStar(UStarHeader {
magic: "ustar\0",
version: "00",
uname: uname,
gname: gname,
devmajor: devmajor,
devminor: devminor,
extra: extra
})
}
)
}
fn parse_ustar<'a, 'b>(i: &'a [u8], flag: &'b TypeFlag) -> IResult<&'a [u8], ExtraHeader<'a>> {
chain!(i,
tag!("ustar\0") ~
ustar: apply!(parse_ustar00, flag),
||{
ustar
}
)
}
/*
* Posix tar archive header parsing
*/
fn parse_posix(i: &[u8]) -> IResult<&[u8], ExtraHeader> {
chain!(i,
take!(255), /* padding to 512 */
||{
ExtraHeader::Padding
}
)
}
fn parse_header(i: &[u8]) -> IResult<&[u8], PosixHeader> {
chain!(i,
name: parse_str100 ~
mode: parse_str8 ~
uid: parse_octal8 ~
gid: parse_octal8 ~
size: parse_octal12 ~
mtime: parse_octal12 ~
chksum: parse_str8 ~
typeflag: parse_type_flag ~
linkname: parse_str100 ~
ustar: alt!(apply!(parse_ustar, &typeflag) | parse_posix),
||{
PosixHeader {
name: name,
mode: mode,
uid: uid,
gid: gid,
size: size,
mtime: mtime,
chksum: chksum,
typeflag: typeflag,
linkname: linkname,
ustar: ustar
}
}
)
}
/*
* Contents parsing
*/
fn parse_contents(i: &[u8], size: u64) -> IResult<&[u8], &[u8]> {
let trailing = size % 512;
let padding = match trailing {
0 => 0,
t => 512 - t
};
chain!(i,
contents: take!(size as usize) ~
take!(padding as usize),
||{
contents
}
)
}
/*
* Tar entry header + contents parsing
*/
fn parse_entry(i: &[u8]) -> IResult<&[u8], TarEntry> {
chain!(i,
header: parse_header ~
contents: apply!(parse_contents, header.size),
||{
TarEntry {
header: header,
contents: contents
}
}
)
}
/*
* Tar archive parsing
*/
fn filter_entries(entries: Vec<TarEntry>) -> Vec<TarEntry> {
/* Filter out empty entries */
entries.into_iter().filter(|e| e.header.name!= "").collect::<Vec<TarEntry>>()
}
pub fn parse_tar(i: &[u8]) -> IResult<&[u8], Vec<TarEntry>> {
chain!(i,
entries: map!(many0!(parse_entry), filter_entries) ~
eof,
||{
entries
}
)
}
/*
* Tests
*/
#[cfg(test)]
mod tests {
use super::*;
use std::str::from_utf8;
use nom::IResult;
#[test]
fn octal_to_u64_ok_test() {
assert_eq!(octal_to_u64("756"), Ok(494));
assert_eq!(octal_to_u64(""), Ok(0));
}
#[test]
fn octal_to_u64_error_test() {
assert_eq!(octal_to_u64("1238"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("a"), Err("invalid octal string received"));
assert_eq!(octal_to_u64("A"), Err("invalid octal string received"));
}
#[test]
fn take_str_eat_garbage_test() {
let s = b"foobar\0\0\0\0baz";
let baz = b"baz";
assert_eq!(take_str_eat_garbage!(&s[..], 10), IResult::Done(&baz[..], "foobar"));
}
}
|
{
match *flag {
TypeFlag::PaxInterexchangeFormat => {
chain!(i,
mut header: parse_ustar00_extra_pax ~
apply!(parse_pax_extra_sparses, &mut header),
||{
UStarExtraHeader::Pax(header)
}
)
},
_ => parse_ustar00_extra_posix(i)
}
}
|
identifier_body
|
main.rs
|
fn main() {
let mut ss = String::from("hello");
ss.push_str(", world!");
println!("{}", ss);
// using the clone method the memory on heap for s1 is copied
// for s2. This operation can be expensive in some cases.
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
// The code below is valid and x is not invalidated because for
// known types/sizes the variable is stored entirely on the stack.
|
println!("x = {}, y = {}", x, y);
// List of types that accept the Copy trait.
// All the integer types, like u32.
// The boolean type, bool, with values true and false.
// All the floating point types, like f64.
// Tuples, but only if they contain types that are also Copy. (i32, i32)
// is Copy, but (i32, String) is not.
let s = String::from("hello"); // s comes into scope.
//
//
// The ownership of a variable follows the same pattern every time:
// assigning a value to another variable moves it. When a variable
// that includes data on the heap goes out of scope, the value will
// be cleaned up by drop unless the data has been moved to be owned
// by another variable.
//
//
takes_ownership(s); // s's value moves into the function...
//... and so is no longer valid here.
//FIXME, this is incorret println!("{}", s);
let x = 5; // x comes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so itβs okay to still
// use x afterward.
println!("{}", x);
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
} // Here, x goes out of scope, then s. But since s's value was moved, nothing
// special happens.
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
fn takes_ownership(some_string: String) {
// some_string comes into scope.
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) {
// some_integer comes into scope.
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
|
// There is no difference between deep and shallow copying here.
let x = 5;
let y = x;
|
random_line_split
|
main.rs
|
fn main() {
let mut ss = String::from("hello");
ss.push_str(", world!");
println!("{}", ss);
// using the clone method the memory on heap for s1 is copied
// for s2. This operation can be expensive in some cases.
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
// The code below is valid and x is not invalidated because for
// known types/sizes the variable is stored entirely on the stack.
// There is no difference between deep and shallow copying here.
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
// List of types that accept the Copy trait.
// All the integer types, like u32.
// The boolean type, bool, with values true and false.
// All the floating point types, like f64.
// Tuples, but only if they contain types that are also Copy. (i32, i32)
// is Copy, but (i32, String) is not.
let s = String::from("hello"); // s comes into scope.
//
//
// The ownership of a variable follows the same pattern every time:
// assigning a value to another variable moves it. When a variable
// that includes data on the heap goes out of scope, the value will
// be cleaned up by drop unless the data has been moved to be owned
// by another variable.
//
//
takes_ownership(s); // s's value moves into the function...
//... and so is no longer valid here.
//FIXME, this is incorret println!("{}", s);
let x = 5; // x comes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so itβs okay to still
// use x afterward.
println!("{}", x);
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
} // Here, x goes out of scope, then s. But since s's value was moved, nothing
// special happens.
fn ca
|
: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
fn takes_ownership(some_string: String) {
// some_string comes into scope.
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) {
// some_integer comes into scope.
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
|
lculate_length(s
|
identifier_name
|
main.rs
|
fn main()
|
// List of types that accept the Copy trait.
// All the integer types, like u32.
// The boolean type, bool, with values true and false.
// All the floating point types, like f64.
// Tuples, but only if they contain types that are also Copy. (i32, i32)
// is Copy, but (i32, String) is not.
let s = String::from("hello"); // s comes into scope.
//
//
// The ownership of a variable follows the same pattern every time:
// assigning a value to another variable moves it. When a variable
// that includes data on the heap goes out of scope, the value will
// be cleaned up by drop unless the data has been moved to be owned
// by another variable.
//
//
takes_ownership(s); // s's value moves into the function...
//... and so is no longer valid here.
//FIXME, this is incorret println!("{}", s);
let x = 5; // x comes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so itβs okay to still
// use x afterward.
println!("{}", x);
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
} /
/ Here, x goes out of scope, then s. But since s's value was moved, nothing
// special happens.
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
fn takes_ownership(some_string: String) {
// some_string comes into scope.
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) {
// some_integer comes into scope.
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
|
{
let mut ss = String::from("hello");
ss.push_str(", world!");
println!("{}", ss);
// using the clone method the memory on heap for s1 is copied
// for s2. This operation can be expensive in some cases.
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
// The code below is valid and x is not invalidated because for
// known types/sizes the variable is stored entirely on the stack.
// There is no difference between deep and shallow copying here.
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
|
identifier_body
|
tests.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use quickcheck::quickcheck;
use crate::Bytes;
use crate::Text;
quickcheck! {
fn test_shallow_clone(v: Vec<u8>) -> bool {
let a: Bytes = v.into();
let b: Bytes = a.clone();
a == b && a.as_ptr() == b.as_ptr()
}
fn test_shallow_slice(v: Vec<u8>) -> bool {
let a: Bytes = v.into();
let b: Bytes = a.slice(..a.len() / 2);
b == &a[..b.len()] && (b.is_empty() || a.as_ptr() == b.as_ptr())
}
fn test_range_of_slice(v: Vec<u8>) -> bool {
let a: Bytes = v.into();
let range1 = a.len() / 3.. a.len() * 2 / 3;
let slice = a.slice(range1.clone());
if slice.is_empty() {
true
} else {
let range2 = a.range_of_slice(&slice).unwrap();
range1 == range2
}
}
fn test_text_shallow_clone(v: String) -> bool {
let a: Text = v.into();
let b: Text = a.clone();
a == b && a.as_ptr() == b.as_ptr()
}
}
static SAMPLE_TEXT: &str = "θΏζ―ζ΅θ―η¨ηζε";
#[test]
fn test_text_slice_
|
Text = SAMPLE_TEXT.into();
let b = a.slice(3..12);
let s: &str = b.as_ref();
let c = a.slice_to_bytes(s);
let d = b.slice_to_bytes(s);
assert_eq!(b.as_ptr(), c.as_ptr());
assert_eq!(b.as_ptr(), d.as_ptr());
}
#[test]
fn test_text_to_string() {
let a: Text = SAMPLE_TEXT.into();
assert_eq!(a.to_string(), SAMPLE_TEXT.to_string());
}
#[test]
#[should_panic]
fn test_text_slice_invalid() {
let a: Text = SAMPLE_TEXT.into();
let _b = a.slice(3..11); // invalid utf-8 boundary
}
#[test]
fn test_downcast_mut() {
let v = b"abcd".to_vec();
let mut b = Bytes::from(v);
assert!(b.downcast_mut::<Vec<u8>>().is_some());
assert!(b.downcast_mut::<String>().is_none());
let mut c = b.clone();
assert!(b.downcast_mut::<Vec<u8>>().is_none());
assert!(c.downcast_mut::<Vec<u8>>().is_none());
}
#[test]
fn test_into_vec() {
let v = b"abcd".to_vec();
let ptr1 = &v[0] as *const u8;
let b = Bytes::from(v);
let v = b.into_vec(); // zero-copy
let ptr2 = &v[0] as *const u8;
assert_eq!(ptr1, ptr2);
let b = Bytes::from(v);
let _c = b.clone();
let v = b.into_vec(); // not zero-copy because refcount > 1
let ptr3 = &v[0] as *const u8;
assert_ne!(ptr1, ptr3);
let b = Bytes::from(v);
let c = b.slice(1..3);
drop(b);
assert_eq!(c.into_vec(), b"bc");
}
#[test]
fn test_bytes_debug_format() {
let v = b"printable\t\r\n\'\"\\\x00\x01\x02printable".to_vec();
let b = Bytes::from(v);
let escaped = format!("{:?}", b);
let expected = r#"b"printable\t\r\n\'\"\\\x00\x01\x02printable""#;
assert_eq!(escaped, expected);
}
|
valid() {
let a:
|
identifier_name
|
tests.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use quickcheck::quickcheck;
use crate::Bytes;
use crate::Text;
quickcheck! {
fn test_shallow_clone(v: Vec<u8>) -> bool {
let a: Bytes = v.into();
let b: Bytes = a.clone();
a == b && a.as_ptr() == b.as_ptr()
}
fn test_shallow_slice(v: Vec<u8>) -> bool {
let a: Bytes = v.into();
let b: Bytes = a.slice(..a.len() / 2);
b == &a[..b.len()] && (b.is_empty() || a.as_ptr() == b.as_ptr())
}
fn test_range_of_slice(v: Vec<u8>) -> bool {
let a: Bytes = v.into();
let range1 = a.len() / 3.. a.len() * 2 / 3;
let slice = a.slice(range1.clone());
if slice.is_empty() {
true
} else {
let range2 = a.range_of_slice(&slice).unwrap();
range1 == range2
}
}
fn test_text_shallow_clone(v: String) -> bool {
let a: Text = v.into();
let b: Text = a.clone();
a == b && a.as_ptr() == b.as_ptr()
}
}
static SAMPLE_TEXT: &str = "θΏζ―ζ΅θ―η¨ηζε";
#[test]
fn test_text_slice_valid() {
let a: Tex
|
t_text_to_string() {
let a: Text = SAMPLE_TEXT.into();
assert_eq!(a.to_string(), SAMPLE_TEXT.to_string());
}
#[test]
#[should_panic]
fn test_text_slice_invalid() {
let a: Text = SAMPLE_TEXT.into();
let _b = a.slice(3..11); // invalid utf-8 boundary
}
#[test]
fn test_downcast_mut() {
let v = b"abcd".to_vec();
let mut b = Bytes::from(v);
assert!(b.downcast_mut::<Vec<u8>>().is_some());
assert!(b.downcast_mut::<String>().is_none());
let mut c = b.clone();
assert!(b.downcast_mut::<Vec<u8>>().is_none());
assert!(c.downcast_mut::<Vec<u8>>().is_none());
}
#[test]
fn test_into_vec() {
let v = b"abcd".to_vec();
let ptr1 = &v[0] as *const u8;
let b = Bytes::from(v);
let v = b.into_vec(); // zero-copy
let ptr2 = &v[0] as *const u8;
assert_eq!(ptr1, ptr2);
let b = Bytes::from(v);
let _c = b.clone();
let v = b.into_vec(); // not zero-copy because refcount > 1
let ptr3 = &v[0] as *const u8;
assert_ne!(ptr1, ptr3);
let b = Bytes::from(v);
let c = b.slice(1..3);
drop(b);
assert_eq!(c.into_vec(), b"bc");
}
#[test]
fn test_bytes_debug_format() {
let v = b"printable\t\r\n\'\"\\\x00\x01\x02printable".to_vec();
let b = Bytes::from(v);
let escaped = format!("{:?}", b);
let expected = r#"b"printable\t\r\n\'\"\\\x00\x01\x02printable""#;
assert_eq!(escaped, expected);
}
|
t = SAMPLE_TEXT.into();
let b = a.slice(3..12);
let s: &str = b.as_ref();
let c = a.slice_to_bytes(s);
let d = b.slice_to_bytes(s);
assert_eq!(b.as_ptr(), c.as_ptr());
assert_eq!(b.as_ptr(), d.as_ptr());
}
#[test]
fn tes
|
identifier_body
|
pass-by-copy.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
extern crate debug;
use std::gc::{GC, Gc};
fn magic(x: A) { println!("{:?}", x); }
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
pub fn main()
|
{
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
}
|
identifier_body
|
|
pass-by-copy.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
extern crate debug;
use std::gc::{GC, Gc};
fn magic(x: A) { println!("{:?}", x); }
|
pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
}
|
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
|
random_line_split
|
pass-by-copy.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
extern crate debug;
use std::gc::{GC, Gc};
fn
|
(x: A) { println!("{:?}", x); }
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
}
|
magic
|
identifier_name
|
regions-early-bound-used-in-bound-method.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
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a isize;
}
#[derive(Copy, Clone)]
struct Box<'a> {
t: &'a isize
}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a isize {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
|
assert_eq!(b1.add(b1), 6);
}
|
random_line_split
|
|
regions-early-bound-used-in-bound-method.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
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a isize;
}
#[derive(Copy, Clone)]
struct Box<'a> {
t: &'a isize
}
impl<'a> GetRef<'a> for Box<'a> {
fn get(&self) -> &'a isize {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize
|
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
|
{
*self.t + *g2.get()
}
|
identifier_body
|
regions-early-bound-used-in-bound-method.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
// Tests that you can use a fn lifetime parameter as part of
// the value for a type parameter in a bound.
trait GetRef<'a> {
fn get(&self) -> &'a isize;
}
#[derive(Copy, Clone)]
struct Box<'a> {
t: &'a isize
}
impl<'a> GetRef<'a> for Box<'a> {
fn
|
(&self) -> &'a isize {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
|
get
|
identifier_name
|
armv7_unknown_linux_musleabihf.rs
|
// Copyright 2016 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 spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult
|
features: "+v7,+vfp3,+d16,+thumb2,-neon".to_string(),
cpu: "generic".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
|
{
let base = super::linux_musl_base::opts();
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
// Most of these settings are copied from the armv7_unknown_linux_gnueabihf
// target.
options: TargetOptions {
|
identifier_body
|
armv7_unknown_linux_musleabihf.rs
|
// Copyright 2016 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 spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn
|
() -> TargetResult {
let base = super::linux_musl_base::opts();
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
// Most of these settings are copied from the armv7_unknown_linux_gnueabihf
// target.
options: TargetOptions {
features: "+v7,+vfp3,+d16,+thumb2,-neon".to_string(),
cpu: "generic".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
|
target
|
identifier_name
|
armv7_unknown_linux_musleabihf.rs
|
// Copyright 2016 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 spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
pub fn target() -> TargetResult {
|
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-unknown-linux-gnueabihf".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "32".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
arch: "arm".to_string(),
target_os: "linux".to_string(),
target_env: "musl".to_string(),
target_vendor: "unknown".to_string(),
linker_flavor: LinkerFlavor::Gcc,
// Most of these settings are copied from the armv7_unknown_linux_gnueabihf
// target.
options: TargetOptions {
features: "+v7,+vfp3,+d16,+thumb2,-neon".to_string(),
cpu: "generic".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
|
let base = super::linux_musl_base::opts();
|
random_line_split
|
metadata.rs
|
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! FFI routines for handling mutable data metadata.
use AppError;
use ffi_utils::{FFI_RESULT_OK, FfiResult, ReprC, catch_unwind_cb};
use maidsafe_utilities::serialisation::serialise;
use safe_core::ffi::ipc::resp::MetadataResponse;
use safe_core::ipc::resp::UserMetadata;
use std::os::raw::c_void;
/// Serialize metadata.
///
/// Callback parameters: user data, error code, encoded metadata vector, vector size
#[no_mangle]
pub unsafe extern "C" fn mdata_encode_metadata(
metadata: *const MetadataResponse,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void,
result: FfiResult,
encoded_ptr: *const u8,
encoded_len: usize),
)
|
#[cfg(test)]
mod tests {
use ffi::mutable_data::metadata::mdata_encode_metadata;
use ffi_utils::test_utils::call_vec_u8;
use maidsafe_utilities::serialisation::deserialise;
use safe_core::ipc::resp::UserMetadata;
// Test serializing and deserializing metadata.
#[test]
fn serialize_metadata() {
let metadata1 = UserMetadata {
name: None,
description: Some(String::from("test")),
};
let metadata_resp = match metadata1.clone().into_md_response(Default::default(), 0) {
Ok(val) => val,
_ => panic!("An error occurred"),
};
let serialised = unsafe {
unwrap!(call_vec_u8(
|ud, cb| mdata_encode_metadata(&metadata_resp, ud, cb),
))
};
let metadata2 = unwrap!(deserialise::<UserMetadata>(&serialised));
assert_eq!(metadata1, metadata2);
}
}
|
{
catch_unwind_cb(user_data, o_cb, || -> Result<_, AppError> {
let metadata = UserMetadata::clone_from_repr_c(metadata)?;
let encoded = serialise(&metadata)?;
o_cb(user_data, FFI_RESULT_OK, encoded.as_ptr(), encoded.len());
Ok(())
})
}
|
identifier_body
|
metadata.rs
|
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! FFI routines for handling mutable data metadata.
use AppError;
use ffi_utils::{FFI_RESULT_OK, FfiResult, ReprC, catch_unwind_cb};
use maidsafe_utilities::serialisation::serialise;
use safe_core::ffi::ipc::resp::MetadataResponse;
use safe_core::ipc::resp::UserMetadata;
use std::os::raw::c_void;
/// Serialize metadata.
///
/// Callback parameters: user data, error code, encoded metadata vector, vector size
#[no_mangle]
pub unsafe extern "C" fn mdata_encode_metadata(
metadata: *const MetadataResponse,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void,
result: FfiResult,
encoded_ptr: *const u8,
encoded_len: usize),
) {
catch_unwind_cb(user_data, o_cb, || -> Result<_, AppError> {
let metadata = UserMetadata::clone_from_repr_c(metadata)?;
let encoded = serialise(&metadata)?;
o_cb(user_data, FFI_RESULT_OK, encoded.as_ptr(), encoded.len());
Ok(())
})
}
#[cfg(test)]
mod tests {
use ffi::mutable_data::metadata::mdata_encode_metadata;
use ffi_utils::test_utils::call_vec_u8;
use maidsafe_utilities::serialisation::deserialise;
use safe_core::ipc::resp::UserMetadata;
// Test serializing and deserializing metadata.
#[test]
fn serialize_metadata() {
let metadata1 = UserMetadata {
name: None,
description: Some(String::from("test")),
};
let metadata_resp = match metadata1.clone().into_md_response(Default::default(), 0) {
Ok(val) => val,
_ => panic!("An error occurred"),
};
let serialised = unsafe {
unwrap!(call_vec_u8(
|ud, cb| mdata_encode_metadata(&metadata_resp, ud, cb),
))
};
let metadata2 = unwrap!(deserialise::<UserMetadata>(&serialised));
assert_eq!(metadata1, metadata2);
|
}
|
}
|
random_line_split
|
metadata.rs
|
// Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! FFI routines for handling mutable data metadata.
use AppError;
use ffi_utils::{FFI_RESULT_OK, FfiResult, ReprC, catch_unwind_cb};
use maidsafe_utilities::serialisation::serialise;
use safe_core::ffi::ipc::resp::MetadataResponse;
use safe_core::ipc::resp::UserMetadata;
use std::os::raw::c_void;
/// Serialize metadata.
///
/// Callback parameters: user data, error code, encoded metadata vector, vector size
#[no_mangle]
pub unsafe extern "C" fn mdata_encode_metadata(
metadata: *const MetadataResponse,
user_data: *mut c_void,
o_cb: extern "C" fn(user_data: *mut c_void,
result: FfiResult,
encoded_ptr: *const u8,
encoded_len: usize),
) {
catch_unwind_cb(user_data, o_cb, || -> Result<_, AppError> {
let metadata = UserMetadata::clone_from_repr_c(metadata)?;
let encoded = serialise(&metadata)?;
o_cb(user_data, FFI_RESULT_OK, encoded.as_ptr(), encoded.len());
Ok(())
})
}
#[cfg(test)]
mod tests {
use ffi::mutable_data::metadata::mdata_encode_metadata;
use ffi_utils::test_utils::call_vec_u8;
use maidsafe_utilities::serialisation::deserialise;
use safe_core::ipc::resp::UserMetadata;
// Test serializing and deserializing metadata.
#[test]
fn
|
() {
let metadata1 = UserMetadata {
name: None,
description: Some(String::from("test")),
};
let metadata_resp = match metadata1.clone().into_md_response(Default::default(), 0) {
Ok(val) => val,
_ => panic!("An error occurred"),
};
let serialised = unsafe {
unwrap!(call_vec_u8(
|ud, cb| mdata_encode_metadata(&metadata_resp, ud, cb),
))
};
let metadata2 = unwrap!(deserialise::<UserMetadata>(&serialised));
assert_eq!(metadata1, metadata2);
}
}
|
serialize_metadata
|
identifier_name
|
step.rs
|
// step.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::fbm::FBM;
use noise::utils::step;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn
|
() {
let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0);
let steps: &[f64] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0];
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let xx = x as f64;
let yy = y as f64;
let nn = ngen.get_value2d(xx, yy);
let n = step(nn, steps);
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("step.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("step.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
}
|
main
|
identifier_name
|
step.rs
|
// step.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::fbm::FBM;
use noise::utils::step;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main()
|
}
let end = precise_time_s();
let fout = File::create(&Path::new("step.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("step.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
}
|
{
let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0);
let steps: &[f64] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0];
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let xx = x as f64;
let yy = y as f64;
let nn = ngen.get_value2d(xx, yy);
let n = step(nn, steps);
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
|
identifier_body
|
step.rs
|
// step.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::fbm::FBM;
use noise::utils::step;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() {
let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0);
let steps: &[f64] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0];
|
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let xx = x as f64;
let yy = y as f64;
let nn = ngen.get_value2d(xx, yy);
let n = step(nn, steps);
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("step.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("step.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
}
|
random_line_split
|
|
sort_an_array_of_composites.rs
|
// http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
#[derive(Debug, PartialEq)]
pub struct Element {
name: String,
value: String,
}
impl Element {
fn new(name: &str, value: &str) -> Element {
Element {
name: name.to_string(),
value: value.to_string(),
}
}
}
pub fn sort_by_name(elements: &mut Vec<Element>) {
elements.sort_by(|a, b| a.name.cmp(&b.name));
}
fn main() {
let mut values = vec![
Element::new("Iron", "Fe"),
Element::new("Cobalt", "Co"),
Element::new("Nickel", "Ni"),
Element::new("Copper", "Cu"),
Element::new("Zinc", "Zn"),
];
sort_by_name(&mut values);
println!("{:?}", values);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_example() {
let mut values = vec![
Element::new("Iron", "Fe"),
Element::new("Cobalt", "Co"),
Element::new("Nickel", "Ni"),
Element::new("Copper", "Cu"),
Element::new("Zinc", "Zn"),
|
Element::new("Cobalt", "Co"),
Element::new("Copper", "Cu"),
Element::new("Iron", "Fe"),
Element::new("Nickel", "Ni"),
Element::new("Zinc", "Zn"),
]);
}
}
|
];
sort_by_name(&mut values);
assert_eq!(values,
vec![
|
random_line_split
|
sort_an_array_of_composites.rs
|
// http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
#[derive(Debug, PartialEq)]
pub struct Element {
name: String,
value: String,
}
impl Element {
fn new(name: &str, value: &str) -> Element {
Element {
name: name.to_string(),
value: value.to_string(),
}
}
}
pub fn sort_by_name(elements: &mut Vec<Element>) {
elements.sort_by(|a, b| a.name.cmp(&b.name));
}
fn
|
() {
let mut values = vec![
Element::new("Iron", "Fe"),
Element::new("Cobalt", "Co"),
Element::new("Nickel", "Ni"),
Element::new("Copper", "Cu"),
Element::new("Zinc", "Zn"),
];
sort_by_name(&mut values);
println!("{:?}", values);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_example() {
let mut values = vec![
Element::new("Iron", "Fe"),
Element::new("Cobalt", "Co"),
Element::new("Nickel", "Ni"),
Element::new("Copper", "Cu"),
Element::new("Zinc", "Zn"),
];
sort_by_name(&mut values);
assert_eq!(values,
vec![
Element::new("Cobalt", "Co"),
Element::new("Copper", "Cu"),
Element::new("Iron", "Fe"),
Element::new("Nickel", "Ni"),
Element::new("Zinc", "Zn"),
]);
}
}
|
main
|
identifier_name
|
adapter.rs
|
extern crate dotalittlehelper;
use dotalittlehelper::*;
#[test]
fn read_json_configuration() {
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"},
"entity_type": "Hero",
"attributes": [{
"identity": {"id": "test_attr", "name": "Test Attr"},
"value": 9001
}]
}]
}"#;
let test_entity = adapter::read_json_configuration(json_str).remove(0);
let real_entity = entity::Entity::new(
entity::Identity::new(
String::from("test"), String::from("Test")
),
entity::EntityType::Hero,
vec!(
entity::Attribute::new(
entity::Identity::new(
String::from("test_attr"), String::from("Test Attr")
),
9001
)
)
);
assert_eq!(real_entity, test_entity);
}
#[test]
#[should_panic]
fn read_json_configuration_fail()
|
{
let json_str = r#"{
"entitties": [{
"what": "is this"
}]
}"#;
let test_entities = adapter::read_json_configuration(json_str);
assert_eq!(0, test_entities.len());
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"}
}]
}"#;
adapter::read_json_configuration(json_str);
}
|
identifier_body
|
|
adapter.rs
|
extern crate dotalittlehelper;
use dotalittlehelper::*;
#[test]
fn read_json_configuration() {
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"},
"entity_type": "Hero",
"attributes": [{
"identity": {"id": "test_attr", "name": "Test Attr"},
"value": 9001
}]
}]
}"#;
let test_entity = adapter::read_json_configuration(json_str).remove(0);
let real_entity = entity::Entity::new(
entity::Identity::new(
String::from("test"), String::from("Test")
),
entity::EntityType::Hero,
vec!(
|
String::from("test_attr"), String::from("Test Attr")
),
9001
)
)
);
assert_eq!(real_entity, test_entity);
}
#[test]
#[should_panic]
fn read_json_configuration_fail() {
let json_str = r#"{
"entitties": [{
"what": "is this"
}]
}"#;
let test_entities = adapter::read_json_configuration(json_str);
assert_eq!(0, test_entities.len());
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"}
}]
}"#;
adapter::read_json_configuration(json_str);
}
|
entity::Attribute::new(
entity::Identity::new(
|
random_line_split
|
adapter.rs
|
extern crate dotalittlehelper;
use dotalittlehelper::*;
#[test]
fn
|
() {
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"},
"entity_type": "Hero",
"attributes": [{
"identity": {"id": "test_attr", "name": "Test Attr"},
"value": 9001
}]
}]
}"#;
let test_entity = adapter::read_json_configuration(json_str).remove(0);
let real_entity = entity::Entity::new(
entity::Identity::new(
String::from("test"), String::from("Test")
),
entity::EntityType::Hero,
vec!(
entity::Attribute::new(
entity::Identity::new(
String::from("test_attr"), String::from("Test Attr")
),
9001
)
)
);
assert_eq!(real_entity, test_entity);
}
#[test]
#[should_panic]
fn read_json_configuration_fail() {
let json_str = r#"{
"entitties": [{
"what": "is this"
}]
}"#;
let test_entities = adapter::read_json_configuration(json_str);
assert_eq!(0, test_entities.len());
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"}
}]
}"#;
adapter::read_json_configuration(json_str);
}
|
read_json_configuration
|
identifier_name
|
attributes.rs
|
use model;
type Attribute = model::Attribute;
type Param = model::Parameter;
|
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_present("param1"));
assert!(!t.is_param_present("param2"));
}
#[test]
fn test_is_param_value_present() {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_value_present("param1", "param1val"));
assert!(!t.is_param_value_present("param1", "param1value"));
assert!(!t.is_param_value_present("param2", "param1val"));
}
|
#[test]
fn test_is_param_present() {
let mut t = Attribute {
name:String::new(),
|
random_line_split
|
attributes.rs
|
use model;
type Attribute = model::Attribute;
type Param = model::Parameter;
#[test]
fn test_is_param_present() {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_present("param1"));
assert!(!t.is_param_present("param2"));
}
#[test]
fn test_is_param_value_present()
|
{
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_value_present("param1", "param1val"));
assert!(!t.is_param_value_present("param1", "param1value"));
assert!(!t.is_param_value_present("param2", "param1val"));
}
|
identifier_body
|
|
attributes.rs
|
use model;
type Attribute = model::Attribute;
type Param = model::Parameter;
#[test]
fn
|
() {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_present("param1"));
assert!(!t.is_param_present("param2"));
}
#[test]
fn test_is_param_value_present() {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_value_present("param1", "param1val"));
assert!(!t.is_param_value_present("param1", "param1value"));
assert!(!t.is_param_value_present("param2", "param1val"));
}
|
test_is_param_present
|
identifier_name
|
closure-in-generic-function.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
|
// except according to those terms.
// xfail-android: FIXME(#10381)
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = 0.5
// debugger:print y
// check:$2 = 10
// debugger:continue
// debugger:finish
// debugger:print *x
// check:$3 = 29
// debugger:print *y
// check:$4 = 110
// debugger:continue
fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1) {
let closure = |x, y| {
zzz();
(y, x)
};
closure(a, b)
}
fn main() {
some_generic_fun(0.5, 10);
some_generic_fun(&29, ~110);
}
fn zzz() {()}
|
//
// 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
|
random_line_split
|
closure-in-generic-function.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-android: FIXME(#10381)
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = 0.5
// debugger:print y
// check:$2 = 10
// debugger:continue
// debugger:finish
// debugger:print *x
// check:$3 = 29
// debugger:print *y
// check:$4 = 110
// debugger:continue
fn
|
<T1, T2>(a: T1, b: T2) -> (T2, T1) {
let closure = |x, y| {
zzz();
(y, x)
};
closure(a, b)
}
fn main() {
some_generic_fun(0.5, 10);
some_generic_fun(&29, ~110);
}
fn zzz() {()}
|
some_generic_fun
|
identifier_name
|
closure-in-generic-function.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-android: FIXME(#10381)
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = 0.5
// debugger:print y
// check:$2 = 10
// debugger:continue
// debugger:finish
// debugger:print *x
// check:$3 = 29
// debugger:print *y
// check:$4 = 110
// debugger:continue
fn some_generic_fun<T1, T2>(a: T1, b: T2) -> (T2, T1)
|
fn main() {
some_generic_fun(0.5, 10);
some_generic_fun(&29, ~110);
}
fn zzz() {()}
|
{
let closure = |x, y| {
zzz();
(y, x)
};
closure(a, b)
}
|
identifier_body
|
token.rs
|
// This program is subject to the terms of the GNU General Public
// License, version 2.0. If a copy of the GPL was not distributed with
// this program, You can obtain one at http://gnu.org.
use std::fmt::{Debug, Write};
use interner::{Interned};
use span::{Spanned};
/// A token with a span.
pub type SToken = Spanned<Token>;
/// A token produced by the lexer.
#[derive(Copy, Eq)]
pub enum Token {
/// A non-terminating part of a string that contains an expression interpolation.
///
/// = Remarks
///
/// This looks like this in the source code:
///
/// "aaaaaaaaaaaa\{e1}bbbbbbbbb\{e2}cccccccc"
/// \____ ____/ \__ __/ \__ __/
/// \ / \ / \ /
/// StringPart StringPart String
///
/// When the parser gets a `StringPart` from the lexer, it parses a single expression
/// (`e1` or `e2` above), eats a `}`, and then tells the lexer to continue parsing the
/// string.
StringPart(Interned),
String(Interned),
Integer(i64),
Ident(Interned),
True,
False,
Null,
Rec,
Let,
In,
Inherit,
If,
Then,
Else,
Or,
LeftBracket,
RightBracket,
LeftBrace,
RightBrace,
LeftParen,
RightParen,
Semicolon,
Dot,
DotDot,
Assign,
Colon,
Comma,
Questionmark,
At,
Equals,
Unequal,
Lt,
Le,
Gt,
Ge,
Concat,
Plus,
Minus,
Times,
Div,
Not,
Mod,
/// `\\`
Overlay,
AndAnd,
OrOr,
/// `->`
Implies,
}
impl Token {
/// Returns whether this token starts an expression.
///
/// = Remarks
///
/// We use this to find out if an expression has just ended. If a token does not start
/// an expression, then it combines a subsequent token with the current expression.
/// E.g., in
///
/// 1 + 1
///
/// the `+` does not start a new expression. However, in
///
/// f x + 1
///
/// the `x` (an identifier) starts a new expressiond and this will be parsed as a
/// function application: `f(x + 1)`.
pub fn
|
(self) -> bool {
match self {
Token::StringPart(..) => true,
Token::String(..) => true,
Token::Integer(..) => true,
Token::Ident(..) => true,
Token::True => true,
Token::False => true,
Token::Null => true,
Token::Rec => true,
Token::Let => true,
Token::If => true,
Token::LeftBracket => true,
Token::LeftBrace => true,
Token::LeftParen => true,
// Unary operators
Token::Minus => true,
Token::Not => true,
Token::In => false,
Token::Inherit => false,
Token::Then => false,
Token::Else => false,
Token::Or => false,
Token::RightBracket => false,
Token::RightBrace => false,
Token::RightParen => false,
Token::Semicolon => false,
Token::Dot => false,
Token::DotDot => false,
Token::Assign => false,
Token::Colon => false,
Token::Comma => false,
Token::Questionmark => false,
Token::At => false,
Token::Equals => false,
Token::Unequal => false,
Token::Lt => false,
Token::Le => false,
Token::Gt => false,
Token::Ge => false,
Token::Concat => false,
Token::Plus => false,
Token::Times => false,
Token::Div => false,
Token::Mod => false,
Token::Overlay => false,
Token::AndAnd => false,
Token::OrOr => false,
Token::Implies => false,
}
}
}
impl Debug for Token {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
let s = match *self {
Token::StringPart(d) => return write!(w, "StringPart({:?})", d),
Token::String(d) => return write!(w, "String({:?})", d),
Token::Integer(d) => return write!(w, "Integer({})", d),
Token::Ident(d) => return write!(w, "Ident({:?})", d),
Token::True => "true",
Token::False => "false",
Token::Null => "null",
Token::Rec => "rec",
Token::Let => "let",
Token::In => "in",
Token::Inherit => "inherit",
Token::If => "if",
Token::Then => "then",
Token::Else => "else",
Token::Or => "or",
Token::LeftBracket => "[",
Token::RightBracket => "]",
Token::LeftBrace => "{",
Token::RightBrace => "}",
Token::LeftParen => "(",
Token::RightParen => ")",
Token::Semicolon => ";",
Token::Dot => ".",
Token::DotDot => "..",
Token::Assign => "=",
Token::Colon => ":",
Token::Comma => ",",
Token::Questionmark => "?",
Token::At => "@",
Token::Equals => "==",
Token::Unequal => "!=",
Token::Lt => "<",
Token::Le => "<=",
Token::Gt => ">",
Token::Ge => ">=",
Token::Concat => "++",
Token::Plus => "+",
Token::Minus => "-",
Token::Times => "*",
Token::Div => "/",
Token::Mod => "%",
Token::Not => "!",
Token::Overlay => "\\\\",
Token::AndAnd => "&&",
Token::OrOr => "||",
Token::Implies => "->",
};
w.write_all(s.as_bytes()).ignore_ok()
}
}
|
starts_expr
|
identifier_name
|
token.rs
|
// This program is subject to the terms of the GNU General Public
// License, version 2.0. If a copy of the GPL was not distributed with
// this program, You can obtain one at http://gnu.org.
use std::fmt::{Debug, Write};
use interner::{Interned};
use span::{Spanned};
/// A token with a span.
pub type SToken = Spanned<Token>;
/// A token produced by the lexer.
#[derive(Copy, Eq)]
pub enum Token {
/// A non-terminating part of a string that contains an expression interpolation.
///
/// = Remarks
///
/// This looks like this in the source code:
///
/// "aaaaaaaaaaaa\{e1}bbbbbbbbb\{e2}cccccccc"
/// \____ ____/ \__ __/ \__ __/
/// \ / \ / \ /
/// StringPart StringPart String
///
/// When the parser gets a `StringPart` from the lexer, it parses a single expression
/// (`e1` or `e2` above), eats a `}`, and then tells the lexer to continue parsing the
/// string.
StringPart(Interned),
String(Interned),
Integer(i64),
Ident(Interned),
True,
False,
Null,
Rec,
Let,
In,
Inherit,
If,
Then,
Else,
Or,
LeftBracket,
RightBracket,
LeftBrace,
RightBrace,
LeftParen,
RightParen,
Semicolon,
Dot,
DotDot,
Assign,
Colon,
Comma,
Questionmark,
At,
Equals,
Unequal,
Lt,
Le,
Gt,
Ge,
Concat,
Plus,
Minus,
Times,
Div,
Not,
Mod,
/// `\\`
Overlay,
AndAnd,
OrOr,
/// `->`
Implies,
}
impl Token {
/// Returns whether this token starts an expression.
///
/// = Remarks
///
/// We use this to find out if an expression has just ended. If a token does not start
/// an expression, then it combines a subsequent token with the current expression.
/// E.g., in
///
/// 1 + 1
///
/// the `+` does not start a new expression. However, in
///
/// f x + 1
///
/// the `x` (an identifier) starts a new expressiond and this will be parsed as a
/// function application: `f(x + 1)`.
pub fn starts_expr(self) -> bool {
match self {
Token::StringPart(..) => true,
Token::String(..) => true,
Token::Integer(..) => true,
Token::Ident(..) => true,
Token::True => true,
Token::False => true,
Token::Null => true,
Token::Rec => true,
Token::Let => true,
Token::If => true,
Token::LeftBracket => true,
Token::LeftBrace => true,
Token::LeftParen => true,
// Unary operators
Token::Minus => true,
Token::Not => true,
Token::In => false,
Token::Inherit => false,
Token::Then => false,
Token::Else => false,
Token::Or => false,
Token::RightBracket => false,
Token::RightBrace => false,
Token::RightParen => false,
Token::Semicolon => false,
Token::Dot => false,
Token::DotDot => false,
Token::Assign => false,
Token::Colon => false,
Token::Comma => false,
Token::Questionmark => false,
Token::At => false,
Token::Equals => false,
|
Token::Concat => false,
Token::Plus => false,
Token::Times => false,
Token::Div => false,
Token::Mod => false,
Token::Overlay => false,
Token::AndAnd => false,
Token::OrOr => false,
Token::Implies => false,
}
}
}
impl Debug for Token {
fn fmt<W: Write>(&self, mut w: &mut W) -> Result {
let s = match *self {
Token::StringPart(d) => return write!(w, "StringPart({:?})", d),
Token::String(d) => return write!(w, "String({:?})", d),
Token::Integer(d) => return write!(w, "Integer({})", d),
Token::Ident(d) => return write!(w, "Ident({:?})", d),
Token::True => "true",
Token::False => "false",
Token::Null => "null",
Token::Rec => "rec",
Token::Let => "let",
Token::In => "in",
Token::Inherit => "inherit",
Token::If => "if",
Token::Then => "then",
Token::Else => "else",
Token::Or => "or",
Token::LeftBracket => "[",
Token::RightBracket => "]",
Token::LeftBrace => "{",
Token::RightBrace => "}",
Token::LeftParen => "(",
Token::RightParen => ")",
Token::Semicolon => ";",
Token::Dot => ".",
Token::DotDot => "..",
Token::Assign => "=",
Token::Colon => ":",
Token::Comma => ",",
Token::Questionmark => "?",
Token::At => "@",
Token::Equals => "==",
Token::Unequal => "!=",
Token::Lt => "<",
Token::Le => "<=",
Token::Gt => ">",
Token::Ge => ">=",
Token::Concat => "++",
Token::Plus => "+",
Token::Minus => "-",
Token::Times => "*",
Token::Div => "/",
Token::Mod => "%",
Token::Not => "!",
Token::Overlay => "\\\\",
Token::AndAnd => "&&",
Token::OrOr => "||",
Token::Implies => "->",
};
w.write_all(s.as_bytes()).ignore_ok()
}
}
|
Token::Unequal => false,
Token::Lt => false,
Token::Le => false,
Token::Gt => false,
Token::Ge => false,
|
random_line_split
|
into_searcher.rs
|
#![feature(core)]
|
mod tests {
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep::{Match, Reject, Done};
use core::str::pattern::StrSearcher;
use core::str::pattern::Pattern;
// #[derive(Copy, Clone, Eq, PartialEq, Debug)]
// pub enum SearchStep {
// /// Expresses that a match of the pattern has been found at
// /// `haystack[a..b]`.
// Match(usize, usize),
// /// Expresses that `haystack[a..b]` has been rejected as a possible match
// /// of the pattern.
// ///
// /// Note that there might be more than one `Reject` between two `Match`es,
// /// there is no requirement for them to be combined into one.
// Reject(usize, usize),
// /// Expresses that every byte of the haystack has been visted, ending
// /// the iteration.
// Done
// }
// #[derive(Clone)]
// pub struct StrSearcher<'a, 'b> {
// haystack: &'a str,
// needle: &'b str,
// start: usize,
// end: usize,
// state: State,
// }
// #[derive(Clone, PartialEq)]
// enum State { Done, NotDone, Reject(usize, usize) }
// impl State {
// #[inline] fn done(&self) -> bool { *self == State::Done }
// #[inline] fn take(&mut self) -> State { ::mem::replace(self, State::NotDone) }
// }
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern
// type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and the `haystack` to search in.
// fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
//
// /// Checks whether the pattern matches anywhere in the haystack
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// self.into_searcher(haystack).next_match().is_some()
// }
//
// /// Checks whether the pattern matches at the front of the haystack
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// match self.into_searcher(haystack).next() {
// SearchStep::Match(0, _) => true,
// _ => false,
// }
// }
//
// /// Checks whether the pattern matches at the back of the haystack
// // #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where Self::Searcher: ReverseSearcher<'a>
// {
// match self.into_searcher(haystack).next_back() {
// SearchStep::Match(_, j) if haystack.len() == j => true,
// _ => false,
// }
// }
// }
// macro_rules! pattern_methods {
// ($t:ty, $pmap:expr, $smap:expr) => {
// type Searcher = $t;
//
// #[inline]
// fn into_searcher(self, haystack: &'a str) -> $t {
// ($smap)(($pmap)(self).into_searcher(haystack))
// }
//
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_contained_in(haystack)
// }
//
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_prefix_of(haystack)
// }
//
// #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where $t: ReverseSearcher<'a>
// {
// ($pmap)(self).is_suffix_of(haystack)
// }
// }
// }
// impl<'a, 'b> Pattern<'a> for &'b &'b str {
// pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
// }
// unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
// #[inline]
// fn haystack(&self) -> &'a str {
// self.haystack
// }
//
// #[inline]
// fn next(&mut self) -> SearchStep {
// str_search_step(self,
// |m: &mut StrSearcher| {
// // Forward step for empty needle
// let current_start = m.start;
// if!m.state.done() {
// m.start = m.haystack.char_range_at(current_start).next;
// m.state = State::Reject(current_start, m.start);
// }
// SearchStep::Match(current_start, current_start)
// },
// |m: &mut StrSearcher| {
// // Forward step for nonempty needle
// let current_start = m.start;
// // Compare byte window because this might break utf8 boundaries
// let possible_match = &m.haystack.as_bytes()[m.start.. m.start + m.needle.len()];
// if possible_match == m.needle.as_bytes() {
// m.start += m.needle.len();
// SearchStep::Match(current_start, m.start)
// } else {
// // Skip a char
// let haystack_suffix = &m.haystack[m.start..];
// m.start += haystack_suffix.chars().next().unwrap().len_utf8();
// SearchStep::Reject(current_start, m.start)
// }
// })
// }
// }
#[test]
fn into_searcher_test1() {
let string: &str = "η»η";
let string_ptr: &&str = &string;
let haystack: &str = "ζθ½εδΈη»ηθδΈε·θΊ«ι«γ";
let mut searcher: StrSearcher = string_ptr.into_searcher(haystack);
assert_eq!(searcher.next(), Reject(0, 3));
assert_eq!(searcher.next(), Reject(3, 6));
assert_eq!(searcher.next(), Reject(6, 9));
assert_eq!(searcher.next(), Reject(9, 12));
assert_eq!(searcher.next(), Match(12, 18));
assert_eq!(searcher.next(), Reject(18, 21));
assert_eq!(searcher.next(), Reject(21, 24));
assert_eq!(searcher.next(), Reject(24, 27));
assert_eq!(searcher.next(), Reject(27, 30));
assert_eq!(searcher.next(), Reject(30, 33));
assert_eq!(searcher.next(), Reject(33, 36));
assert_eq!(searcher.next(), Done);
}
}
|
extern crate core;
#[cfg(test)]
|
random_line_split
|
into_searcher.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep::{Match, Reject, Done};
use core::str::pattern::StrSearcher;
use core::str::pattern::Pattern;
// #[derive(Copy, Clone, Eq, PartialEq, Debug)]
// pub enum SearchStep {
// /// Expresses that a match of the pattern has been found at
// /// `haystack[a..b]`.
// Match(usize, usize),
// /// Expresses that `haystack[a..b]` has been rejected as a possible match
// /// of the pattern.
// ///
// /// Note that there might be more than one `Reject` between two `Match`es,
// /// there is no requirement for them to be combined into one.
// Reject(usize, usize),
// /// Expresses that every byte of the haystack has been visted, ending
// /// the iteration.
// Done
// }
// #[derive(Clone)]
// pub struct StrSearcher<'a, 'b> {
// haystack: &'a str,
// needle: &'b str,
// start: usize,
// end: usize,
// state: State,
// }
// #[derive(Clone, PartialEq)]
// enum State { Done, NotDone, Reject(usize, usize) }
// impl State {
// #[inline] fn done(&self) -> bool { *self == State::Done }
// #[inline] fn take(&mut self) -> State { ::mem::replace(self, State::NotDone) }
// }
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern
// type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and the `haystack` to search in.
// fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
//
// /// Checks whether the pattern matches anywhere in the haystack
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// self.into_searcher(haystack).next_match().is_some()
// }
//
// /// Checks whether the pattern matches at the front of the haystack
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// match self.into_searcher(haystack).next() {
// SearchStep::Match(0, _) => true,
// _ => false,
// }
// }
//
// /// Checks whether the pattern matches at the back of the haystack
// // #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where Self::Searcher: ReverseSearcher<'a>
// {
// match self.into_searcher(haystack).next_back() {
// SearchStep::Match(_, j) if haystack.len() == j => true,
// _ => false,
// }
// }
// }
// macro_rules! pattern_methods {
// ($t:ty, $pmap:expr, $smap:expr) => {
// type Searcher = $t;
//
// #[inline]
// fn into_searcher(self, haystack: &'a str) -> $t {
// ($smap)(($pmap)(self).into_searcher(haystack))
// }
//
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_contained_in(haystack)
// }
//
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_prefix_of(haystack)
// }
//
// #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where $t: ReverseSearcher<'a>
// {
// ($pmap)(self).is_suffix_of(haystack)
// }
// }
// }
// impl<'a, 'b> Pattern<'a> for &'b &'b str {
// pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
// }
// unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
// #[inline]
// fn haystack(&self) -> &'a str {
// self.haystack
// }
//
// #[inline]
// fn next(&mut self) -> SearchStep {
// str_search_step(self,
// |m: &mut StrSearcher| {
// // Forward step for empty needle
// let current_start = m.start;
// if!m.state.done() {
// m.start = m.haystack.char_range_at(current_start).next;
// m.state = State::Reject(current_start, m.start);
// }
// SearchStep::Match(current_start, current_start)
// },
// |m: &mut StrSearcher| {
// // Forward step for nonempty needle
// let current_start = m.start;
// // Compare byte window because this might break utf8 boundaries
// let possible_match = &m.haystack.as_bytes()[m.start.. m.start + m.needle.len()];
// if possible_match == m.needle.as_bytes() {
// m.start += m.needle.len();
// SearchStep::Match(current_start, m.start)
// } else {
// // Skip a char
// let haystack_suffix = &m.haystack[m.start..];
// m.start += haystack_suffix.chars().next().unwrap().len_utf8();
// SearchStep::Reject(current_start, m.start)
// }
// })
// }
// }
#[test]
fn into_searcher_test1()
|
{
let string: &str = "η»η";
let string_ptr: &&str = &string;
let haystack: &str = "ζθ½εδΈη»ηθδΈε·θΊ«ι«γ";
let mut searcher: StrSearcher = string_ptr.into_searcher(haystack);
assert_eq!(searcher.next(), Reject(0, 3));
assert_eq!(searcher.next(), Reject(3, 6));
assert_eq!(searcher.next(), Reject(6, 9));
assert_eq!(searcher.next(), Reject(9, 12));
assert_eq!(searcher.next(), Match(12, 18));
assert_eq!(searcher.next(), Reject(18, 21));
assert_eq!(searcher.next(), Reject(21, 24));
assert_eq!(searcher.next(), Reject(24, 27));
assert_eq!(searcher.next(), Reject(27, 30));
assert_eq!(searcher.next(), Reject(30, 33));
assert_eq!(searcher.next(), Reject(33, 36));
assert_eq!(searcher.next(), Done);
}
}
|
identifier_body
|
|
into_searcher.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep::{Match, Reject, Done};
use core::str::pattern::StrSearcher;
use core::str::pattern::Pattern;
// #[derive(Copy, Clone, Eq, PartialEq, Debug)]
// pub enum SearchStep {
// /// Expresses that a match of the pattern has been found at
// /// `haystack[a..b]`.
// Match(usize, usize),
// /// Expresses that `haystack[a..b]` has been rejected as a possible match
// /// of the pattern.
// ///
// /// Note that there might be more than one `Reject` between two `Match`es,
// /// there is no requirement for them to be combined into one.
// Reject(usize, usize),
// /// Expresses that every byte of the haystack has been visted, ending
// /// the iteration.
// Done
// }
// #[derive(Clone)]
// pub struct StrSearcher<'a, 'b> {
// haystack: &'a str,
// needle: &'b str,
// start: usize,
// end: usize,
// state: State,
// }
// #[derive(Clone, PartialEq)]
// enum State { Done, NotDone, Reject(usize, usize) }
// impl State {
// #[inline] fn done(&self) -> bool { *self == State::Done }
// #[inline] fn take(&mut self) -> State { ::mem::replace(self, State::NotDone) }
// }
// pub trait Pattern<'a>: Sized {
// /// Associated searcher for this pattern
// type Searcher: Searcher<'a>;
//
// /// Constructs the associated searcher from
// /// `self` and the `haystack` to search in.
// fn into_searcher(self, haystack: &'a str) -> Self::Searcher;
//
// /// Checks whether the pattern matches anywhere in the haystack
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// self.into_searcher(haystack).next_match().is_some()
// }
//
// /// Checks whether the pattern matches at the front of the haystack
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// match self.into_searcher(haystack).next() {
// SearchStep::Match(0, _) => true,
// _ => false,
// }
// }
//
// /// Checks whether the pattern matches at the back of the haystack
// // #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where Self::Searcher: ReverseSearcher<'a>
// {
// match self.into_searcher(haystack).next_back() {
// SearchStep::Match(_, j) if haystack.len() == j => true,
// _ => false,
// }
// }
// }
// macro_rules! pattern_methods {
// ($t:ty, $pmap:expr, $smap:expr) => {
// type Searcher = $t;
//
// #[inline]
// fn into_searcher(self, haystack: &'a str) -> $t {
// ($smap)(($pmap)(self).into_searcher(haystack))
// }
//
// #[inline]
// fn is_contained_in(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_contained_in(haystack)
// }
//
// #[inline]
// fn is_prefix_of(self, haystack: &'a str) -> bool {
// ($pmap)(self).is_prefix_of(haystack)
// }
//
// #[inline]
// fn is_suffix_of(self, haystack: &'a str) -> bool
// where $t: ReverseSearcher<'a>
// {
// ($pmap)(self).is_suffix_of(haystack)
// }
// }
// }
// impl<'a, 'b> Pattern<'a> for &'b &'b str {
// pattern_methods!(StrSearcher<'a, 'b>, |&s| s, |s| s);
// }
// unsafe impl<'a, 'b> Searcher<'a> for StrSearcher<'a, 'b> {
// #[inline]
// fn haystack(&self) -> &'a str {
// self.haystack
// }
//
// #[inline]
// fn next(&mut self) -> SearchStep {
// str_search_step(self,
// |m: &mut StrSearcher| {
// // Forward step for empty needle
// let current_start = m.start;
// if!m.state.done() {
// m.start = m.haystack.char_range_at(current_start).next;
// m.state = State::Reject(current_start, m.start);
// }
// SearchStep::Match(current_start, current_start)
// },
// |m: &mut StrSearcher| {
// // Forward step for nonempty needle
// let current_start = m.start;
// // Compare byte window because this might break utf8 boundaries
// let possible_match = &m.haystack.as_bytes()[m.start.. m.start + m.needle.len()];
// if possible_match == m.needle.as_bytes() {
// m.start += m.needle.len();
// SearchStep::Match(current_start, m.start)
// } else {
// // Skip a char
// let haystack_suffix = &m.haystack[m.start..];
// m.start += haystack_suffix.chars().next().unwrap().len_utf8();
// SearchStep::Reject(current_start, m.start)
// }
// })
// }
// }
#[test]
fn
|
() {
let string: &str = "η»η";
let string_ptr: &&str = &string;
let haystack: &str = "ζθ½εδΈη»ηθδΈε·θΊ«ι«γ";
let mut searcher: StrSearcher = string_ptr.into_searcher(haystack);
assert_eq!(searcher.next(), Reject(0, 3));
assert_eq!(searcher.next(), Reject(3, 6));
assert_eq!(searcher.next(), Reject(6, 9));
assert_eq!(searcher.next(), Reject(9, 12));
assert_eq!(searcher.next(), Match(12, 18));
assert_eq!(searcher.next(), Reject(18, 21));
assert_eq!(searcher.next(), Reject(21, 24));
assert_eq!(searcher.next(), Reject(24, 27));
assert_eq!(searcher.next(), Reject(27, 30));
assert_eq!(searcher.next(), Reject(30, 33));
assert_eq!(searcher.next(), Reject(33, 36));
assert_eq!(searcher.next(), Done);
}
}
|
into_searcher_test1
|
identifier_name
|
hard-tabs.rs
|
// rustfmt-wrap_comments: true
// rustfmt-hard_tabs: true
fn main() {
let x = Bar;
let y = Foo { a: x };
Foo {
a: foo(), // comment
// comment
b: bar(),
..something
};
fn foo(a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32) {
}
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
if let (some_very_large,
tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple) = 1 + 2 + 3 {
}
if cond() {
something();
} else if different_cond() {
something_else();
} else {
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
* comment */ {
}
unsafe /* So this is a very long comment.
* Multi-line, too.
* Will it still format correctly? */ {
}
let chain = funktion_kall()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab();
let z = [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
yyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzzzzzzzzzzzzzzzzz,
q];
fn generic<T>(arg: T) -> &SomeType
where T: Fn(// First arg
A,
// Second argument
B,
C,
D,
// pre comment
E /* last comment */)
-> &SomeType
{
arg(a, b, c, d, e)
}
loong_func().quux(move || {
if true {
1
} else {
2
}
});
fffffffffffffffffffffffffffffffffff(a, {
SCRIPT_TASK_ROOT.with(|root| {
*root.borrow_mut() = Some(&script_task);
});
});
a.b
.c
.d();
x().y(|| {
match cond() {
true => (),
false => (),
}
});
}
|
}
unsafe /* very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
|
random_line_split
|
hard-tabs.rs
|
// rustfmt-wrap_comments: true
// rustfmt-hard_tabs: true
fn main()
|
a: i32,
a: i32,
a: i32) {
}
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
if let (some_very_large,
tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple) = 1 + 2 + 3 {
}
if cond() {
something();
} else if different_cond() {
something_else();
} else {
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
}
unsafe /* very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
* comment */ {
}
unsafe /* So this is a very long comment.
* Multi-line, too.
* Will it still format correctly? */ {
}
let chain = funktion_kall()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab();
let z = [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
yyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzzzzzzzzzzzzzzzzz,
q];
fn generic<T>(arg: T) -> &SomeType
where T: Fn(// First arg
A,
// Second argument
B,
C,
D,
// pre comment
E /* last comment */)
-> &SomeType
{
arg(a, b, c, d, e)
}
loong_func().quux(move || {
if true {
1
} else {
2
}
});
fffffffffffffffffffffffffffffffffff(a, {
SCRIPT_TASK_ROOT.with(|root| {
*root.borrow_mut() = Some(&script_task);
});
});
a.b
.c
.d();
x().y(|| {
match cond() {
true => (),
false => (),
}
});
}
|
{
let x = Bar;
let y = Foo { a: x };
Foo {
a: foo(), // comment
// comment
b: bar(),
..something
};
fn foo(a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
|
identifier_body
|
hard-tabs.rs
|
// rustfmt-wrap_comments: true
// rustfmt-hard_tabs: true
fn
|
() {
let x = Bar;
let y = Foo { a: x };
Foo {
a: foo(), // comment
// comment
b: bar(),
..something
};
fn foo(a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32) {
}
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
if let (some_very_large,
tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple) = 1 + 2 + 3 {
}
if cond() {
something();
} else if different_cond() {
something_else();
} else {
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
}
unsafe /* very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
* comment */ {
}
unsafe /* So this is a very long comment.
* Multi-line, too.
* Will it still format correctly? */ {
}
let chain = funktion_kall()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab();
let z = [xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
yyyyyyyyyyyyyyyyyyyyyyyyyyy,
zzzzzzzzzzzzzzzzzz,
q];
fn generic<T>(arg: T) -> &SomeType
where T: Fn(// First arg
A,
// Second argument
B,
C,
D,
// pre comment
E /* last comment */)
-> &SomeType
{
arg(a, b, c, d, e)
}
loong_func().quux(move || {
if true {
1
} else {
2
}
});
fffffffffffffffffffffffffffffffffff(a, {
SCRIPT_TASK_ROOT.with(|root| {
*root.borrow_mut() = Some(&script_task);
});
});
a.b
.c
.d();
x().y(|| {
match cond() {
true => (),
false => (),
}
});
}
|
main
|
identifier_name
|
build.rs
|
fn
|
() {
println!("cargo:rerun-if-changed=build.rs");
#[cfg(feature = "ispc")]
{
if std::env::var("CARGO_FEATURE_ISPC").is_ok() {
let mut cfg = ispc::Config::new();
if cfg!(windows) {
cfg.debug(false);
}
let ispc_files = vec!["volta/mandelbrot.ispc"];
for s in &ispc_files[..] {
cfg.file(*s);
}
cfg.target_isas(vec![
ispc::opt::TargetISA::SSE2i32x4,
ispc::opt::TargetISA::SSE4i32x4,
ispc::opt::TargetISA::AVX1i32x8,
ispc::opt::TargetISA::AVX2i32x8,
ispc::opt::TargetISA::AVX512KNLi32x16,
]);
cfg.compile("mandelbrot");
}
}
}
|
main
|
identifier_name
|
build.rs
|
fn main()
|
ispc::opt::TargetISA::SSE4i32x4,
ispc::opt::TargetISA::AVX1i32x8,
ispc::opt::TargetISA::AVX2i32x8,
ispc::opt::TargetISA::AVX512KNLi32x16,
]);
cfg.compile("mandelbrot");
}
}
}
|
{
println!("cargo:rerun-if-changed=build.rs");
#[cfg(feature = "ispc")]
{
if std::env::var("CARGO_FEATURE_ISPC").is_ok() {
let mut cfg = ispc::Config::new();
if cfg!(windows) {
cfg.debug(false);
}
let ispc_files = vec!["volta/mandelbrot.ispc"];
for s in &ispc_files[..] {
cfg.file(*s);
}
cfg.target_isas(vec![
ispc::opt::TargetISA::SSE2i32x4,
|
identifier_body
|
build.rs
|
fn main() {
println!("cargo:rerun-if-changed=build.rs");
#[cfg(feature = "ispc")]
{
if std::env::var("CARGO_FEATURE_ISPC").is_ok()
|
cfg.compile("mandelbrot");
}
}
}
|
{
let mut cfg = ispc::Config::new();
if cfg!(windows) {
cfg.debug(false);
}
let ispc_files = vec!["volta/mandelbrot.ispc"];
for s in &ispc_files[..] {
cfg.file(*s);
}
cfg.target_isas(vec![
ispc::opt::TargetISA::SSE2i32x4,
ispc::opt::TargetISA::SSE4i32x4,
ispc::opt::TargetISA::AVX1i32x8,
ispc::opt::TargetISA::AVX2i32x8,
ispc::opt::TargetISA::AVX512KNLi32x16,
]);
|
conditional_block
|
build.rs
|
fn main() {
println!("cargo:rerun-if-changed=build.rs");
#[cfg(feature = "ispc")]
{
if std::env::var("CARGO_FEATURE_ISPC").is_ok() {
let mut cfg = ispc::Config::new();
if cfg!(windows) {
cfg.debug(false);
}
let ispc_files = vec!["volta/mandelbrot.ispc"];
for s in &ispc_files[..] {
cfg.file(*s);
}
cfg.target_isas(vec![
ispc::opt::TargetISA::SSE2i32x4,
ispc::opt::TargetISA::SSE4i32x4,
ispc::opt::TargetISA::AVX1i32x8,
ispc::opt::TargetISA::AVX2i32x8,
|
cfg.compile("mandelbrot");
}
}
}
|
ispc::opt::TargetISA::AVX512KNLi32x16,
]);
|
random_line_split
|
dom.rs
|
pub fn id(&self) -> usize {
self.0
}
}
/// Simple trait to provide basic information about the type of an element.
///
/// We avoid exposing the full type id, since computing it in the general case
/// would be difficult for Gecko nodes.
pub trait NodeInfo {
/// Whether this node is an element.
fn is_element(&self) -> bool;
/// Whether this node is a text node.
fn is_text_node(&self) -> bool;
}
/// A node iterator that only returns node that don't need layout.
pub struct LayoutIterator<T>(pub T);
impl<T, N> Iterator for LayoutIterator<T>
where
T: Iterator<Item = N>,
N: NodeInfo,
{
type Item = N;
fn next(&mut self) -> Option<N> {
loop {
match self.0.next() {
Some(n) => {
// Filter out nodes that layout should ignore.
if n.is_text_node() || n.is_element()
|
}
None => return None,
}
}
}
}
/// An iterator over the DOM children of a node.
pub struct DomChildren<N>(Option<N>);
impl<N> Iterator for DomChildren<N>
where
N: TNode
{
type Item = N;
fn next(&mut self) -> Option<N> {
match self.0.take() {
Some(n) => {
self.0 = n.next_sibling();
Some(n)
}
None => None,
}
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's first child.
fn first_child(&self) -> Option<Self>;
/// Get this node's first child.
fn last_child(&self) -> Option<Self>;
/// Get this node's previous sibling.
fn prev_sibling(&self) -> Option<Self>;
/// Get this node's next sibling.
fn next_sibling(&self) -> Option<Self>;
/// Iterate over the DOM children of an element.
fn dom_children(&self) -> DomChildren<Self> {
DomChildren(self.first_child())
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
}
/// Wrapper to output the ElementData along with the node when formatting for
/// Debug.
pub struct ShowData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data(f, self.0)
}
}
/// Wrapper to output the primary computed values along with the node when
/// formatting for Debug. This is very verbose.
pub struct ShowDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
+ PresentationalHintsSynthesizer
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(traversal_flags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.hint.has_animation_hint()
}
/// Returns the anonymous content for the current element's XBL binding,
/// given if any.
///
/// This is used in Gecko for XBL and shadow DOM.
fn xbl_binding_anonymous_content(&self) -> Option<Self::ConcreteNode> {
None
}
/// Returns the rule hash target given an element.
fn rule_hash_target(&self) -> Self {
let is_implemented_pseudo =
self.implemented_pseudo_element().is_some();
// NB: This causes use to rule has pseudo selectors based on the
// properties of the originating element (which is fine, given the
// find_first_from_right usage).
if is_implemented_pseudo {
self.closest_non_native_anonymous_ancestor().unwrap()
} else {
|
{
return Some(n)
}
|
conditional_block
|
dom.rs
|
) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
+ PresentationalHintsSynthesizer
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(traversal_flags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.hint.has_animation_hint()
}
/// Returns the anonymous content for the current element's XBL binding,
/// given if any.
///
/// This is used in Gecko for XBL and shadow DOM.
fn xbl_binding_anonymous_content(&self) -> Option<Self::ConcreteNode> {
None
}
/// Returns the rule hash target given an element.
fn rule_hash_target(&self) -> Self {
let is_implemented_pseudo =
self.implemented_pseudo_element().is_some();
// NB: This causes use to rule has pseudo selectors based on the
// properties of the originating element (which is fine, given the
// find_first_from_right usage).
if is_implemented_pseudo {
self.closest_non_native_anonymous_ancestor().unwrap()
} else {
*self
}
}
/// Implements Gecko's `nsBindingManager::WalkRules`.
///
/// Returns whether to cut off the inheritance.
fn each_xbl_stylist<F>(&self, _: F) -> bool
where
F: FnMut(&Stylist),
{
false
}
/// Gets the current existing CSS transitions, by |property, end value| pairs in a FnvHashMap.
#[cfg(feature = "gecko")]
fn get_css_transitions_info(&self)
-> FnvHashMap<LonghandId, Arc<AnimationValue>>;
/// Does a rough (and cheap) check for whether or not transitions might need to be updated that
/// will quickly return false for the common case of no transitions specified or running. If
/// this returns false, we definitely don't need to update transitions but if it returns true
/// we can perform the more thoroughgoing check, needs_transitions_update, to further
/// reduce the possibility of false positives.
#[cfg(feature = "gecko")]
fn might_need_transitions_update(
&self,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues
) -> bool;
/// Returns true if one of the transitions needs to be updated on this element. We check all
/// the transition properties to make sure that updating transitions is necessary.
/// This method should only be called if might_needs_transitions_update returns true when
/// passed the same parameters.
#[cfg(feature = "gecko")]
fn needs_transitions_update(
&self,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues
) -> bool;
/// Returns true if we need to update transitions for the specified property on this element.
#[cfg(feature = "gecko")]
fn needs_transitions_update_per_property(
&self,
property: &LonghandId,
combined_duration: f32,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues,
existing_transitions: &FnvHashMap<LonghandId, Arc<AnimationValue>>
) -> bool;
/// Returns the value of the `xml:lang=""` attribute (or, if appropriate,
/// the `lang=""` attribute) on this element.
fn lang_attr(&self) -> Option<AttrValue>;
/// Returns whether this element's language matches the language tag
/// `value`. If `override_lang` is not `None`, it specifies the value
/// of the `xml:lang=""` or `lang=""` attribute to use in place of
/// looking at the element and its ancestors. (This argument is used
/// to implement matching of `:lang()` against snapshots.)
fn match_element_lang(
&self,
override_lang: Option<Option<AttrValue>>,
value: &PseudoClassStringArg
) -> bool;
/// Returns whether this element is the main body element of the HTML
/// document it is on.
fn is_html_document_body_element(&self) -> bool;
}
/// TNode and TElement aren't Send because we want to be careful and explicit
/// about our parallel traversal. However, there are certain situations
/// (including but not limited to the traversal) where we need to send DOM
/// objects to other threads.
///
/// That's the reason why `SendNode` exists.
#[derive(Clone, Debug, PartialEq)]
pub struct SendNode<N: TNode>(N);
unsafe impl<N: TNode> Send for SendNode<N> {}
impl<N: TNode> SendNode<N> {
/// Unsafely construct a SendNode.
pub unsafe fn new(node: N) -> Self {
SendNode(node)
}
}
impl<N: TNode> Deref for SendNode<N> {
type Target = N;
fn deref(&self) -> &N {
&self.0
}
}
/// Same reason as for the existence of SendNode, SendElement does the proper
/// things for a given `TElement`.
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct SendElement<E: TElement>(E);
unsafe impl<E: TElement> Send for SendElement<E> {}
impl<E: TElement> SendElement<E> {
/// Unsafely construct a SendElement.
pub unsafe fn new(el: E) -> Self {
SendElement(el)
}
}
impl<E: TElement> Deref for SendElement<E> {
type Target = E;
fn deref(&self) -> &E
|
{
&self.0
}
|
identifier_body
|
|
dom.rs
|
)
}
}
/// Wrapper to output the primary computed values along with the node when
/// formatting for Debug. This is very verbose.
pub struct ShowDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
+ PresentationalHintsSynthesizer
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(traversal_flags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.hint.has_animation_hint()
}
/// Returns the anonymous content for the current element's XBL binding,
/// given if any.
///
/// This is used in Gecko for XBL and shadow DOM.
fn xbl_binding_anonymous_content(&self) -> Option<Self::ConcreteNode> {
None
}
/// Returns the rule hash target given an element.
fn rule_hash_target(&self) -> Self {
let is_implemented_pseudo =
self.implemented_pseudo_element().is_some();
// NB: This causes use to rule has pseudo selectors based on the
// properties of the originating element (which is fine, given the
// find_first_from_right usage).
if is_implemented_pseudo {
self.closest_non_native_anonymous_ancestor().unwrap()
} else {
*self
}
}
/// Implements Gecko's `nsBindingManager::WalkRules`.
///
/// Returns whether to cut off the inheritance.
fn each_xbl_stylist<F>(&self, _: F) -> bool
where
F: FnMut(&Stylist),
{
false
}
/// Gets the current existing CSS transitions, by |property, end value| pairs in a FnvHashMap.
#[cfg(feature = "gecko")]
fn get_css_transitions_info(&self)
-> FnvHashMap<LonghandId, Arc<AnimationValue>>;
/// Does a rough (and cheap) check for whether or not transitions might need to be updated that
/// will quickly return false for the common case of no transitions specified or running. If
/// this returns false, we definitely don't need to update transitions but if it returns true
/// we can perform the more thoroughgoing check, needs_transitions_update, to further
/// reduce the possibility of false positives.
#[cfg(feature = "gecko")]
fn might_need_transitions_update(
&self,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues
) -> bool;
/// Returns true if one of the transitions needs to be updated on this element. We check all
/// the transition properties to make sure that updating transitions is necessary.
/// This method should only be called if might_needs_transitions_update returns true when
/// passed the same parameters.
#[cfg(feature = "gecko")]
fn needs_transitions_update(
&self,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues
) -> bool;
/// Returns true if we need to update transitions for the specified property on this element.
#[cfg(feature = "gecko")]
fn needs_transitions_update_per_property(
&self,
property: &LonghandId,
combined_duration: f32,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues,
existing_transitions: &FnvHashMap<LonghandId, Arc<AnimationValue>>
) -> bool;
/// Returns the value of the `xml:lang=""` attribute (or, if appropriate,
/// the `lang=""` attribute) on this element.
fn lang_attr(&self) -> Option<AttrValue>;
/// Returns whether this element's language matches the language tag
/// `value`. If `override_lang` is not `None`, it specifies the value
/// of the `xml:lang=""` or `lang=""` attribute to use in place of
/// looking at the element and its ancestors. (This argument is used
/// to implement matching of `:lang()` against snapshots.)
fn match_element_lang(
&self,
override_lang: Option<Option<AttrValue>>,
value: &PseudoClassStringArg
) -> bool;
/// Returns whether this element is the main body element of the HTML
/// document it is on.
fn is_html_document_body_element(&self) -> bool;
}
/// TNode and TElement aren't Send because we want to be careful and explicit
/// about our parallel traversal. However, there are certain situations
/// (including but not limited to the traversal) where we need to send DOM
/// objects to other threads.
///
/// That's the reason why `SendNode` exists.
#[derive(Clone, Debug, PartialEq)]
pub struct SendNode<N: TNode>(N);
unsafe impl<N: TNode> Send for SendNode<N> {}
impl<N: TNode> SendNode<N> {
/// Unsafely construct a SendNode.
pub unsafe fn new(node: N) -> Self {
SendNode(node)
}
}
impl<N: TNode> Deref for SendNode<N> {
type Target = N;
fn deref(&self) -> &N {
&self.0
}
}
/// Same reason as for the existence of SendNode, SendElement does the proper
/// things for a given `TElement`.
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct SendElement<E: TElement>(E);
unsafe impl<E: TElement> Send for SendElement<E> {}
impl<E: TElement> SendElement<E> {
/// Unsafely construct a SendElement.
pub unsafe fn
|
new
|
identifier_name
|
|
dom.rs
|
set_can_be_fragmented(&self, value: bool);
}
/// Wrapper to output the ElementData along with the node when formatting for
/// Debug.
pub struct ShowData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data(f, self.0)
}
}
/// Wrapper to output the primary computed values along with the node when
/// formatting for Debug. This is very verbose.
pub struct ShowDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "DOM Subtree:")?;
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(
f, "{:?} dd={} aodd={} data={:?}",
el,
el.has_dirty_descendants(),
el.has_animation_only_dirty_descendants(),
el.borrow_data(),
)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let aodd = el.has_animation_only_dirty_descendants();
let data = el.borrow_data();
let values = data.as_ref().and_then(|d| d.styles.get_primary());
write!(f, "{:?} dd={} aodd={} data={:?} values={:?}", el, dd, aodd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
write!(f, " ")?;
}
stringify(f, n)?;
if let Some(e) = n.as_element() {
for kid in e.traversal_children() {
writeln!(f, "")?;
fmt_subtree(f, stringify, kid, indent + 1)?;
}
}
Ok(())
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement
: Eq
+ PartialEq
+ Debug
+ Hash
+ Sized
+ Copy
+ Clone
+ SelectorsElement<Impl = SelectorImpl>
+ PresentationalHintsSynthesizer
{
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type TraversalChildrenIterator: Iterator<Item = Self::ConcreteNode>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider + Send;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// A debug-only check that the device's owner doc matches the actual doc
/// we're the root of.
///
/// Otherwise we may set document-level state incorrectly, like the root
/// font-size used for rem units.
fn owner_doc_matches_for_testing(&self, _: &Device) -> bool { true }
/// Whether this element should match user and author rules.
///
/// We use this for Native Anonymous Content in Gecko.
fn matches_user_and_author_rules(&self) -> bool { true }
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::TraversalChildrenIterator>;
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// The ::before pseudo-element of this element, if it exists.
fn before_pseudo_element(&self) -> Option<Self> {
None
}
/// The ::after pseudo-element of this element, if it exists.
fn after_pseudo_element(&self) -> Option<Self> {
None
}
/// Execute `f` for each anonymous content child (apart from ::before and
/// ::after) whose originating element is `self`.
fn each_anonymous_content_child<F>(&self, _f: F)
where
F: FnMut(Self),
{}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<ArcBorrow<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get the combined animation and transition rules.
fn get_animation_rules(&self) -> AnimationRules {
if!self.may_have_animations() {
return AnimationRules(None, None)
}
AnimationRules(
self.get_animation_rule(),
self.get_transition_rule(),
)
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// The ID for this element.
fn get_id(&self) -> Option<Atom>;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
// ::before/::after are always supported for now, though we could try to
// optimize out leaf elements.
// ::first-letter and ::first-line are only supported for block-inside
// things, and only in Gecko, not Servo. Unfortunately, Gecko has
// block-inside things that might have any computed display value due to
// things like fieldsets, legends, etc. Need to figure out how this
// should work.
debug_assert!(pseudo.is_eager(),
"Someone called may_generate_pseudo with a non-eager pseudo.");
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date for |traversal_flags|.
fn has_current_styles_for_traversal(
&self,
data: &ElementData,
traversal_flags: TraversalFlags,
) -> bool {
if traversal_flags.for_animation_only() {
// In animation-only restyle we never touch snapshots and don't
// care about them. But we can't assert '!self.handled_snapshot()'
// here since there are some cases that a second animation-only
// restyle which is a result of normal restyle (e.g. setting
// animation-name in normal restyle and creating a new CSS
// animation in a SequentialTask) is processed after the normal
// traversal in that we had elements that handled snapshot.
return data.has_styles() &&
!data.hint.has_animation_hint_or_recascade();
}
if traversal_flags.contains(traversal_flags::UnstyledOnly) {
// We don't process invalidations in UnstyledOnly mode.
return data.has_styles();
}
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.hint.has_non_animation_invalidations()
}
/// Returns whether the element's styles are up-to-date after traversal
/// (i.e. in post traversal).
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&
// TODO(hiro): When an animating element moved into subtree of
// contenteditable element, there remains animation restyle hints in
// post traversal. It's generally harmless since the hints will be
// processed in a next styling but ideally it should be processed soon.
//
// Without this, we get failures in:
// layout/style/crashtests/1383319.html
// layout/style/crashtests/1383001.html
//
// https://bugzilla.mozilla.org/show_bug.cgi?id=1389675 tracks fixing
// this.
!data.hint.has_non_animation_invalidations()
}
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Clear all bits related describing the dirtiness of descendants.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, and the lazy frame construction
/// descendants bit.
unsafe fn clear_descendant_bits(&self) { self.unset_dirty_descendants(); }
/// Clear all element flags related to dirtiness.
///
/// In Gecko, this corresponds to the regular dirty descendants bit, the
/// animation-only dirty descendants bit, the lazy frame construction bit,
/// and the lazy frame construction descendants bit.
unsafe fn clear_dirty_bits(&self) { self.unset_dirty_descendants(); }
/// Returns true if this element is a visited link.
///
/// Servo doesn't support visited styles yet.
fn is_visited_link(&self) -> bool { false }
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container, or creates one.
///
/// Unsafe because it can race to allocate and leak if not used with
/// exclusive access to the element.
unsafe fn ensure_data(&self) -> AtomicRefMut<ElementData>;
/// Clears the element data reference, if any.
///
/// Unsafe following the same reasoning as ensure_data.
unsafe fn clear_data(&self);
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Creates a task to process post animation on a given element.
#[cfg(feature = "gecko")]
fn process_post_animation(&self, tasks: PostAnimationTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.hint.has_animation_hint()
}
/// Returns the anonymous content for the current element's XBL binding,
/// given if any.
///
/// This is used in Gecko for XBL and shadow DOM.
fn xbl_binding_anonymous_content(&self) -> Option<Self::ConcreteNode> {
None
}
/// Returns the rule hash target given an element.
fn rule_hash_target(&self) -> Self {
let is_implemented_pseudo =
self.implemented_pseudo_element().is_some();
// NB: This causes use to rule has pseudo selectors based on the
// properties of the originating element (which is fine, given the
// find_first_from_right usage).
if is_implemented_pseudo {
self.closest_non_native_anonymous_ancestor().unwrap()
} else {
*self
}
}
/// Implements Gecko's `nsBindingManager::WalkRules`.
///
/// Returns whether to cut off the inheritance.
fn each_xbl_stylist<F>(&self, _: F) -> bool
where
F: FnMut(&Stylist),
{
false
}
/// Gets the current existing CSS transitions, by |property, end value| pairs in a FnvHashMap.
#[cfg(feature = "gecko")]
fn get_css_transitions_info(&self)
-> FnvHashMap<LonghandId, Arc<AnimationValue>>;
/// Does a rough (and cheap) check for whether or not transitions might need to be updated that
/// will quickly return false for the common case of no transitions specified or running. If
/// this returns false, we definitely don't need to update transitions but if it returns true
/// we can perform the more thoroughgoing check, needs_transitions_update, to further
/// reduce the possibility of false positives.
#[cfg(feature = "gecko")]
fn might_need_transitions_update(
&self,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues
) -> bool;
/// Returns true if one of the transitions needs to be updated on this element. We check all
/// the transition properties to make sure that updating transitions is necessary.
/// This method should only be called if might_needs_transitions_update returns true when
/// passed the same parameters.
#[cfg(feature = "gecko")]
fn needs_transitions_update(
&self,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues
) -> bool;
/// Returns true if we need to update transitions for the specified property on this element.
#[cfg(feature = "gecko")]
fn needs_transitions_update_per_property(
&self,
property: &LonghandId,
combined_duration: f32,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues,
existing_transitions: &FnvHashMap<LonghandId, Arc<AnimationValue>>
) -> bool;
/// Returns the value of the `xml:lang=""` attribute (or, if appropriate,
/// the `lang=""` attribute) on this element.
fn lang_attr(&self) -> Option<AttrValue>;
/// Returns whether this element's language matches the language tag
/// `value`. If `override_lang` is not `None`, it specifies the value
/// of the `xml:lang=""` or `lang=""` attribute to use in place of
/// looking at the element and its ancestors. (This argument is used
/// to implement matching of `:lang()` against snapshots.)
fn match_element_lang(
&self,
override_lang: Option<Option<AttrValue>>,
value: &PseudoClassStringArg
) -> bool;
/// Returns whether this element is the main body element of the HTML
/// document it is on.
fn is_html_document_body_element(&self) -> bool;
}
/// TNode and TElement aren't Send because we want to be careful and explicit
/// about our parallel traversal. However, there are certain situations
/// (including but not limited to the traversal) where we need to send DOM
/// objects to other threads.
///
/// That's the reason why `SendNode` exists.
#[derive(Clone, Debug, PartialEq)]
pub struct SendNode<N: TNode>(N);
unsafe impl<N: TNode> Send for SendNode<N> {}
impl<N: TNode> SendNode<N> {
/// Unsafely construct a SendNode.
pub unsafe fn new(node: N) -> Self {
SendNode(node)
}
}
impl<N: TNode> Deref for SendNode<N> {
type Target = N;
fn deref(&self) -> &N {
&self.0
}
|
}
|
random_line_split
|
|
mod.rs
|
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 161)]
pub struct CharacterCreationResultMessage<'a> {
pub result: u8,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 5544)]
pub struct CharacterNameSuggestionSuccessMessage<'a> {
pub suggestion: &'a str,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 160)]
pub struct CharacterCreationRequestMessage<'a> {
pub name: &'a str,
pub breed: i8,
pub sex: bool,
pub colors: std::borrow::Cow<'a, [i32]>,
#[protocol(var)]
pub cosmetic_id: u16,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 162)]
pub struct
|
<'a> {
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 164)]
pub struct CharacterNameSuggestionFailureMessage<'a> {
pub reason: u8,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6733)]
pub struct CharacterCanBeCreatedResultMessage<'a> {
pub yes_you_can: bool,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6732)]
pub struct CharacterCanBeCreatedRequestMessage<'a> {
pub _phantom: std::marker::PhantomData<&'a ()>,
}
|
CharacterNameSuggestionRequestMessage
|
identifier_name
|
mod.rs
|
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 161)]
pub struct CharacterCreationResultMessage<'a> {
pub result: u8,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 5544)]
pub struct CharacterNameSuggestionSuccessMessage<'a> {
pub suggestion: &'a str,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 160)]
pub struct CharacterCreationRequestMessage<'a> {
pub name: &'a str,
pub breed: i8,
pub sex: bool,
pub colors: std::borrow::Cow<'a, [i32]>,
#[protocol(var)]
pub cosmetic_id: u16,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 162)]
pub struct CharacterNameSuggestionRequestMessage<'a> {
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 164)]
pub struct CharacterNameSuggestionFailureMessage<'a> {
|
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6733)]
pub struct CharacterCanBeCreatedResultMessage<'a> {
pub yes_you_can: bool,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6732)]
pub struct CharacterCanBeCreatedRequestMessage<'a> {
pub _phantom: std::marker::PhantomData<&'a ()>,
}
|
pub reason: u8,
pub _phantom: std::marker::PhantomData<&'a ()>,
}
|
random_line_split
|
dep-graph-struct-signature.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.
// Test cases where a changing struct appears in the signature of fns
// and methods.
// compile-flags: -Z query-dep-graph
#![feature(rustc_attrs)]
|
fn main() { }
#[rustc_if_this_changed]
struct WillChange {
x: u32,
y: u32
}
struct WontChange {
x: u32,
y: u32
}
// these are valid dependencies
mod signatures {
use WillChange;
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
#[rustc_then_this_would_need(AssociatedItems)] //~ ERROR no path
#[rustc_then_this_would_need(TraitDefOfItem)] //~ ERROR no path
trait Bar {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
fn do_something(x: WillChange);
}
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn some_fn(x: WillChange) { }
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn new_foo(x: u32, y: u32) -> WillChange {
WillChange { x: x, y: y }
}
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
impl WillChange {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn new(x: u32, y: u32) -> WillChange { loop { } }
}
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
impl WillChange {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn method(&self, x: u32) { }
}
struct WillChanges {
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
x: WillChange,
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
y: WillChange
}
// The fields change, not the type itself.
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
fn indirect(x: WillChanges) { }
}
mod invalid_signatures {
use WontChange;
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
trait A {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path
fn do_something_else_twice(x: WontChange);
}
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path
fn b(x: WontChange) { }
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path from `WillChange`
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path from `WillChange`
fn c(x: u32) { }
}
|
#![allow(dead_code)]
#![allow(unused_variables)]
|
random_line_split
|
dep-graph-struct-signature.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.
// Test cases where a changing struct appears in the signature of fns
// and methods.
// compile-flags: -Z query-dep-graph
#![feature(rustc_attrs)]
#![allow(dead_code)]
#![allow(unused_variables)]
fn main() { }
#[rustc_if_this_changed]
struct WillChange {
x: u32,
y: u32
}
struct WontChange {
x: u32,
y: u32
}
// these are valid dependencies
mod signatures {
use WillChange;
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
#[rustc_then_this_would_need(AssociatedItems)] //~ ERROR no path
#[rustc_then_this_would_need(TraitDefOfItem)] //~ ERROR no path
trait Bar {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
fn do_something(x: WillChange);
}
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn some_fn(x: WillChange) { }
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn new_foo(x: u32, y: u32) -> WillChange {
WillChange { x: x, y: y }
}
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
impl WillChange {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn new(x: u32, y: u32) -> WillChange { loop { } }
}
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
impl WillChange {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn method(&self, x: u32)
|
}
struct WillChanges {
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
x: WillChange,
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
y: WillChange
}
// The fields change, not the type itself.
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
fn indirect(x: WillChanges) { }
}
mod invalid_signatures {
use WontChange;
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
trait A {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path
fn do_something_else_twice(x: WontChange);
}
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path
fn b(x: WontChange) { }
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path from `WillChange`
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path from `WillChange`
fn c(x: u32) { }
}
|
{ }
|
identifier_body
|
dep-graph-struct-signature.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.
// Test cases where a changing struct appears in the signature of fns
// and methods.
// compile-flags: -Z query-dep-graph
#![feature(rustc_attrs)]
#![allow(dead_code)]
#![allow(unused_variables)]
fn main() { }
#[rustc_if_this_changed]
struct
|
{
x: u32,
y: u32
}
struct WontChange {
x: u32,
y: u32
}
// these are valid dependencies
mod signatures {
use WillChange;
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
#[rustc_then_this_would_need(AssociatedItems)] //~ ERROR no path
#[rustc_then_this_would_need(TraitDefOfItem)] //~ ERROR no path
trait Bar {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
fn do_something(x: WillChange);
}
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn some_fn(x: WillChange) { }
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn new_foo(x: u32, y: u32) -> WillChange {
WillChange { x: x, y: y }
}
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
impl WillChange {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn new(x: u32, y: u32) -> WillChange { loop { } }
}
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
impl WillChange {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR OK
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR OK
fn method(&self, x: u32) { }
}
struct WillChanges {
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
x: WillChange,
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR OK
y: WillChange
}
// The fields change, not the type itself.
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
fn indirect(x: WillChanges) { }
}
mod invalid_signatures {
use WontChange;
#[rustc_then_this_would_need(TypeOfItem)] //~ ERROR no path
trait A {
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path
fn do_something_else_twice(x: WontChange);
}
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path
fn b(x: WontChange) { }
#[rustc_then_this_would_need(FnSignature)] //~ ERROR no path from `WillChange`
#[rustc_then_this_would_need(TypeckTables)] //~ ERROR no path from `WillChange`
fn c(x: u32) { }
}
|
WillChange
|
identifier_name
|
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:[email protected]"}], {"String": "hello world"}]]' http://localhost:3000/api/v1/channels/set
///
use foxbox_taxonomy::adapter::*;
use foxbox_taxonomy::manager::AdapterManager;
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::services::{ AdapterId, Channel, ChannelKind, Id, Service, ServiceId };
use foxbox_taxonomy::values::{ Type, Value };
use std::collections::HashMap;
use std::sync::Arc;
pub mod engine;
pub use self::engine::TtsEngine;
// eSpeak is the only engine supported for now.
mod espeak;
use self::espeak::EspeakEngine;
static ADAPTER_ID: &'static str = "[email protected]";
static ADAPTER_NAME: &'static str = "eSpeak adapter";
static ADAPTER_VENDOR: &'static str = "[email protected]";
static ADAPTER_VERSION: [u32;4] = [0, 0, 0, 0];
pub struct
|
<T> {
talk_setter_id: Id<Channel>,
engine: T
}
impl<T: TtsEngine> Adapter for TtsAdapter<T> {
fn id(&self) -> Id<AdapterId> {
adapter_id!(ADAPTER_ID)
}
fn name(&self) -> &str {
ADAPTER_NAME
}
fn vendor(&self) -> &str {
ADAPTER_VENDOR
}
fn version(&self) -> &[u32;4] {
&ADAPTER_VERSION
}
fn fetch_values(&self, mut set: Vec<Id<Channel>>, _: User) -> ResultMap<Id<Channel>, Option<Value>, Error> {
set.drain(..).map(|id| {
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
fn send_values(&self, mut values: HashMap<Id<Channel>, Value>, _: User) -> ResultMap<Id<Channel>, (), Error> {
use core::ops::Deref;
values.drain().map(|(id, value)| {
if id == self.talk_setter_id {
if let Value::String(text) = value {
self.engine.say(text.deref());
return (id, Ok(()));
}
}
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
}
pub fn init(adapt: &Arc<AdapterManager>) -> Result<(), Error> {
let engine = EspeakEngine { };
if!engine.init() {
warn!("eSpeak initialization failed!");
return Err(Error::InternalError(InternalError::GenericError("eSpeak initialization failed!".to_owned())));
}
let talk_setter_id = Id::new("setter:[email protected]");
try!(adapt.add_adapter(Arc::new(TtsAdapter {
talk_setter_id: talk_setter_id.clone(),
engine: engine
})));
let service_id = service_id!("[email protected]");
let adapter_id = adapter_id!(ADAPTER_ID);
try!(adapt.add_service(Service::empty(&service_id, &adapter_id)));
try!(adapt.add_channel(Channel {
kind: ChannelKind::Extension {
vendor: Id::new(ADAPTER_VENDOR),
adapter: Id::new(ADAPTER_NAME),
kind: Id::new("Sentence"),
typ: Type::String,
},
supports_send: true,
.. Channel::empty(&talk_setter_id, &service_id, &adapter_id)
}));
Ok(())
}
|
TtsAdapter
|
identifier_name
|
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:[email protected]"}], {"String": "hello world"}]]' http://localhost:3000/api/v1/channels/set
///
use foxbox_taxonomy::adapter::*;
use foxbox_taxonomy::manager::AdapterManager;
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::services::{ AdapterId, Channel, ChannelKind, Id, Service, ServiceId };
use foxbox_taxonomy::values::{ Type, Value };
use std::collections::HashMap;
use std::sync::Arc;
pub mod engine;
pub use self::engine::TtsEngine;
// eSpeak is the only engine supported for now.
mod espeak;
use self::espeak::EspeakEngine;
static ADAPTER_ID: &'static str = "[email protected]";
static ADAPTER_NAME: &'static str = "eSpeak adapter";
static ADAPTER_VENDOR: &'static str = "[email protected]";
static ADAPTER_VERSION: [u32;4] = [0, 0, 0, 0];
pub struct TtsAdapter<T> {
talk_setter_id: Id<Channel>,
engine: T
}
impl<T: TtsEngine> Adapter for TtsAdapter<T> {
fn id(&self) -> Id<AdapterId> {
adapter_id!(ADAPTER_ID)
}
fn name(&self) -> &str {
ADAPTER_NAME
}
fn vendor(&self) -> &str {
ADAPTER_VENDOR
}
fn version(&self) -> &[u32;4] {
&ADAPTER_VERSION
}
fn fetch_values(&self, mut set: Vec<Id<Channel>>, _: User) -> ResultMap<Id<Channel>, Option<Value>, Error> {
set.drain(..).map(|id| {
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
fn send_values(&self, mut values: HashMap<Id<Channel>, Value>, _: User) -> ResultMap<Id<Channel>, (), Error> {
use core::ops::Deref;
values.drain().map(|(id, value)| {
if id == self.talk_setter_id {
if let Value::String(text) = value {
self.engine.say(text.deref());
return (id, Ok(()));
}
}
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
}
pub fn init(adapt: &Arc<AdapterManager>) -> Result<(), Error> {
let engine = EspeakEngine { };
if!engine.init()
|
let talk_setter_id = Id::new("setter:[email protected]");
try!(adapt.add_adapter(Arc::new(TtsAdapter {
talk_setter_id: talk_setter_id.clone(),
engine: engine
})));
let service_id = service_id!("[email protected]");
let adapter_id = adapter_id!(ADAPTER_ID);
try!(adapt.add_service(Service::empty(&service_id, &adapter_id)));
try!(adapt.add_channel(Channel {
kind: ChannelKind::Extension {
vendor: Id::new(ADAPTER_VENDOR),
adapter: Id::new(ADAPTER_NAME),
kind: Id::new("Sentence"),
typ: Type::String,
},
supports_send: true,
.. Channel::empty(&talk_setter_id, &service_id, &adapter_id)
}));
Ok(())
}
|
{
warn!("eSpeak initialization failed!");
return Err(Error::InternalError(InternalError::GenericError("eSpeak initialization failed!".to_owned())));
}
|
conditional_block
|
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:[email protected]"}], {"String": "hello world"}]]' http://localhost:3000/api/v1/channels/set
///
use foxbox_taxonomy::adapter::*;
use foxbox_taxonomy::manager::AdapterManager;
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::services::{ AdapterId, Channel, ChannelKind, Id, Service, ServiceId };
use foxbox_taxonomy::values::{ Type, Value };
use std::collections::HashMap;
use std::sync::Arc;
pub mod engine;
pub use self::engine::TtsEngine;
// eSpeak is the only engine supported for now.
mod espeak;
use self::espeak::EspeakEngine;
static ADAPTER_ID: &'static str = "[email protected]";
static ADAPTER_NAME: &'static str = "eSpeak adapter";
static ADAPTER_VENDOR: &'static str = "[email protected]";
static ADAPTER_VERSION: [u32;4] = [0, 0, 0, 0];
pub struct TtsAdapter<T> {
talk_setter_id: Id<Channel>,
engine: T
}
impl<T: TtsEngine> Adapter for TtsAdapter<T> {
fn id(&self) -> Id<AdapterId> {
adapter_id!(ADAPTER_ID)
}
fn name(&self) -> &str {
ADAPTER_NAME
}
fn vendor(&self) -> &str {
ADAPTER_VENDOR
}
fn version(&self) -> &[u32;4] {
&ADAPTER_VERSION
}
fn fetch_values(&self, mut set: Vec<Id<Channel>>, _: User) -> ResultMap<Id<Channel>, Option<Value>, Error> {
set.drain(..).map(|id| {
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
fn send_values(&self, mut values: HashMap<Id<Channel>, Value>, _: User) -> ResultMap<Id<Channel>, (), Error> {
use core::ops::Deref;
values.drain().map(|(id, value)| {
if id == self.talk_setter_id {
if let Value::String(text) = value {
self.engine.say(text.deref());
return (id, Ok(()));
}
}
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
}
pub fn init(adapt: &Arc<AdapterManager>) -> Result<(), Error> {
let engine = EspeakEngine { };
if!engine.init() {
warn!("eSpeak initialization failed!");
return Err(Error::InternalError(InternalError::GenericError("eSpeak initialization failed!".to_owned())));
}
let talk_setter_id = Id::new("setter:[email protected]");
try!(adapt.add_adapter(Arc::new(TtsAdapter {
talk_setter_id: talk_setter_id.clone(),
engine: engine
})));
let service_id = service_id!("[email protected]");
let adapter_id = adapter_id!(ADAPTER_ID);
try!(adapt.add_service(Service::empty(&service_id, &adapter_id)));
try!(adapt.add_channel(Channel {
kind: ChannelKind::Extension {
vendor: Id::new(ADAPTER_VENDOR),
adapter: Id::new(ADAPTER_NAME),
kind: Id::new("Sentence"),
typ: Type::String,
},
supports_send: true,
.. Channel::empty(&talk_setter_id, &service_id, &adapter_id)
}));
Ok(())
|
}
|
random_line_split
|
|
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:[email protected]"}], {"String": "hello world"}]]' http://localhost:3000/api/v1/channels/set
///
use foxbox_taxonomy::adapter::*;
use foxbox_taxonomy::manager::AdapterManager;
use foxbox_taxonomy::api::{ Error, InternalError, User };
use foxbox_taxonomy::services::{ AdapterId, Channel, ChannelKind, Id, Service, ServiceId };
use foxbox_taxonomy::values::{ Type, Value };
use std::collections::HashMap;
use std::sync::Arc;
pub mod engine;
pub use self::engine::TtsEngine;
// eSpeak is the only engine supported for now.
mod espeak;
use self::espeak::EspeakEngine;
static ADAPTER_ID: &'static str = "[email protected]";
static ADAPTER_NAME: &'static str = "eSpeak adapter";
static ADAPTER_VENDOR: &'static str = "[email protected]";
static ADAPTER_VERSION: [u32;4] = [0, 0, 0, 0];
pub struct TtsAdapter<T> {
talk_setter_id: Id<Channel>,
engine: T
}
impl<T: TtsEngine> Adapter for TtsAdapter<T> {
fn id(&self) -> Id<AdapterId> {
adapter_id!(ADAPTER_ID)
}
fn name(&self) -> &str
|
fn vendor(&self) -> &str {
ADAPTER_VENDOR
}
fn version(&self) -> &[u32;4] {
&ADAPTER_VERSION
}
fn fetch_values(&self, mut set: Vec<Id<Channel>>, _: User) -> ResultMap<Id<Channel>, Option<Value>, Error> {
set.drain(..).map(|id| {
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
fn send_values(&self, mut values: HashMap<Id<Channel>, Value>, _: User) -> ResultMap<Id<Channel>, (), Error> {
use core::ops::Deref;
values.drain().map(|(id, value)| {
if id == self.talk_setter_id {
if let Value::String(text) = value {
self.engine.say(text.deref());
return (id, Ok(()));
}
}
(id.clone(), Err(Error::InternalError(InternalError::NoSuchChannel(id))))
}).collect()
}
}
pub fn init(adapt: &Arc<AdapterManager>) -> Result<(), Error> {
let engine = EspeakEngine { };
if!engine.init() {
warn!("eSpeak initialization failed!");
return Err(Error::InternalError(InternalError::GenericError("eSpeak initialization failed!".to_owned())));
}
let talk_setter_id = Id::new("setter:[email protected]");
try!(adapt.add_adapter(Arc::new(TtsAdapter {
talk_setter_id: talk_setter_id.clone(),
engine: engine
})));
let service_id = service_id!("[email protected]");
let adapter_id = adapter_id!(ADAPTER_ID);
try!(adapt.add_service(Service::empty(&service_id, &adapter_id)));
try!(adapt.add_channel(Channel {
kind: ChannelKind::Extension {
vendor: Id::new(ADAPTER_VENDOR),
adapter: Id::new(ADAPTER_NAME),
kind: Id::new("Sentence"),
typ: Type::String,
},
supports_send: true,
.. Channel::empty(&talk_setter_id, &service_id, &adapter_id)
}));
Ok(())
}
|
{
ADAPTER_NAME
}
|
identifier_body
|
lib.rs
|
#[macro_use] extern crate winreg;
#[macro_use] extern crate rustler;
#[macro_use] extern crate rustler_codegen;
#[macro_use] extern crate lazy_static;
use rustler::{NifEnv, NifTerm, NifResult, NifEncoder};
use winreg::RegKey;
use winreg::enums::*;
mod atoms {
rustler_atoms! {
atom ok;
//atom error;
// atom __true__ = "true";
// atom __false__ = "false";
atom ntfs_create_short_names = "ntfs_create_short_names";
atom ntfs_never_create_short_names = "ntfs_never_create_short_names";
atom ntfs_create_short_per_volume = "ntfs_create_short_per_volume";
atom ntfs_create_short_only_on_system_volume = "ntfs_create_short_only_on_system_volume";
atom e_cannot_determine_ntfs_setting="e_cannot_determine_ntfs_setting";
atom error;
}
}
rustler_export_nifs! {
"Elixir.Pragmatic.Windows",
[("add", 2, add),("check_short_names",2,check_short_names)],
None
}
fn add<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let num1: i64 = try!(args[0].decode());
let num2: i64 = try!(args[1].decode());
Ok((atoms::ok(), num1 + num2).encode(env))
}
fn
|
<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let file_system_key = hklm.open_subkey_with_flags("SYSTEM\\CurrentControlSet\\Control\\FileSystem", KEY_READ).unwrap();
let eight_dot_three_disabled: u32 = file_system_key.get_value("NtfsDisable8dot3NameCreation").unwrap();
match eight_dot_three_disabled {
0 => Ok((atoms::ok(), atoms::ntfs_create_short_names()).encode(env)),
1 => Ok((atoms::ok(), atoms::ntfs_never_create_short_names()).encode(env)),
2 => Ok((atoms::ok(), atoms::ntfs_create_short_per_volume()).encode(env)),
3 => Ok((atoms::ok(), atoms::ntfs_create_short_only_on_system_volume ()).encode(env)),
_ => Ok((atoms::error(),atoms::e_cannot_determine_ntfs_setting()).encode(env))
}
}
|
check_short_names
|
identifier_name
|
lib.rs
|
#[macro_use] extern crate winreg;
#[macro_use] extern crate rustler;
#[macro_use] extern crate rustler_codegen;
#[macro_use] extern crate lazy_static;
use rustler::{NifEnv, NifTerm, NifResult, NifEncoder};
use winreg::RegKey;
use winreg::enums::*;
mod atoms {
rustler_atoms! {
atom ok;
//atom error;
// atom __true__ = "true";
// atom __false__ = "false";
atom ntfs_create_short_names = "ntfs_create_short_names";
atom ntfs_never_create_short_names = "ntfs_never_create_short_names";
atom ntfs_create_short_per_volume = "ntfs_create_short_per_volume";
atom ntfs_create_short_only_on_system_volume = "ntfs_create_short_only_on_system_volume";
atom e_cannot_determine_ntfs_setting="e_cannot_determine_ntfs_setting";
atom error;
}
}
rustler_export_nifs! {
"Elixir.Pragmatic.Windows",
[("add", 2, add),("check_short_names",2,check_short_names)],
None
}
fn add<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>>
|
fn check_short_names<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let file_system_key = hklm.open_subkey_with_flags("SYSTEM\\CurrentControlSet\\Control\\FileSystem", KEY_READ).unwrap();
let eight_dot_three_disabled: u32 = file_system_key.get_value("NtfsDisable8dot3NameCreation").unwrap();
match eight_dot_three_disabled {
0 => Ok((atoms::ok(), atoms::ntfs_create_short_names()).encode(env)),
1 => Ok((atoms::ok(), atoms::ntfs_never_create_short_names()).encode(env)),
2 => Ok((atoms::ok(), atoms::ntfs_create_short_per_volume()).encode(env)),
3 => Ok((atoms::ok(), atoms::ntfs_create_short_only_on_system_volume ()).encode(env)),
_ => Ok((atoms::error(),atoms::e_cannot_determine_ntfs_setting()).encode(env))
}
}
|
{
let num1: i64 = try!(args[0].decode());
let num2: i64 = try!(args[1].decode());
Ok((atoms::ok(), num1 + num2).encode(env))
}
|
identifier_body
|
lib.rs
|
#[macro_use] extern crate winreg;
#[macro_use] extern crate rustler;
#[macro_use] extern crate rustler_codegen;
#[macro_use] extern crate lazy_static;
use rustler::{NifEnv, NifTerm, NifResult, NifEncoder};
use winreg::RegKey;
use winreg::enums::*;
mod atoms {
rustler_atoms! {
atom ok;
//atom error;
// atom __true__ = "true";
|
atom ntfs_create_short_names = "ntfs_create_short_names";
atom ntfs_never_create_short_names = "ntfs_never_create_short_names";
atom ntfs_create_short_per_volume = "ntfs_create_short_per_volume";
atom ntfs_create_short_only_on_system_volume = "ntfs_create_short_only_on_system_volume";
atom e_cannot_determine_ntfs_setting="e_cannot_determine_ntfs_setting";
atom error;
}
}
rustler_export_nifs! {
"Elixir.Pragmatic.Windows",
[("add", 2, add),("check_short_names",2,check_short_names)],
None
}
fn add<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let num1: i64 = try!(args[0].decode());
let num2: i64 = try!(args[1].decode());
Ok((atoms::ok(), num1 + num2).encode(env))
}
fn check_short_names<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let file_system_key = hklm.open_subkey_with_flags("SYSTEM\\CurrentControlSet\\Control\\FileSystem", KEY_READ).unwrap();
let eight_dot_three_disabled: u32 = file_system_key.get_value("NtfsDisable8dot3NameCreation").unwrap();
match eight_dot_three_disabled {
0 => Ok((atoms::ok(), atoms::ntfs_create_short_names()).encode(env)),
1 => Ok((atoms::ok(), atoms::ntfs_never_create_short_names()).encode(env)),
2 => Ok((atoms::ok(), atoms::ntfs_create_short_per_volume()).encode(env)),
3 => Ok((atoms::ok(), atoms::ntfs_create_short_only_on_system_volume ()).encode(env)),
_ => Ok((atoms::error(),atoms::e_cannot_determine_ntfs_setting()).encode(env))
}
}
|
// atom __false__ = "false";
|
random_line_split
|
lib.rs
|
//! # The rusty-machine crate.
//!
//! A crate built for machine learning that works out-of-the-box.
//!
//! ---
//!
//! ## Structure
//!
//! The crate is made up of two primary modules: learning and linalg.
//!
//! ### learning
//!
//! The learning module contains all of the machine learning modules.
//! This means the algorithms, models and related tools.
//!
//! The currently supported techniques are:
//!
//! - Linear Regression
//! - Logistic Regression
//! - Generalized Linear Models
//! - K-Means Clustering
//! - Neural Networks
//! - Gaussian Process Regression
//! - Support Vector Machines
//! - Gaussian Mixture Models
//! - Naive Bayes Classifiers
//! - DBSCAN
//!
|
//!
//! The linalg module reexports some structs and traits from the
//! [rulinalg](https://crates.io/crates/rulinalg) crate. This is to provide
//! easy access to common linear algebra tools within this library.
//!
//! ---
//!
//! ## Usage
//!
//! Specific usage of modules is described within the modules themselves. This section
//! will focus on the general workflow for this library.
//!
//! The models contained within the learning module should implement either
//! `SupModel` or `UnSupModel`. These both provide a `train` and a `predict`
//! function which provide an interface to the model.
//!
//! You should instantiate the model, with your chosen options and then train using
//! the training data. Followed by predicting with your test data. *For now*
//! cross-validation, data handling, and many other things are left explicitly
//! to the user.
//!
//! Here is an example usage for Gaussian Process Regression:
//!
//! ```
//! use rusty_machine::linalg::Matrix;
//! use rusty_machine::linalg::Vector;
//! use rusty_machine::learning::gp::GaussianProcess;
//! use rusty_machine::learning::gp::ConstMean;
//! use rusty_machine::learning::toolkit::kernel;
//! use rusty_machine::learning::SupModel;
//!
//! // First we'll get some data.
//!
//! // Some example training data.
//! let inputs = Matrix::new(3,3,vec![1.,1.,1.,2.,2.,2.,3.,3.,3.]);
//! let targets = Vector::new(vec![0.,1.,0.]);
//!
//! // Some example test data.
//! let test_inputs = Matrix::new(2,3, vec![1.5,1.5,1.5,2.5,2.5,2.5]);
//!
//! // Now we'll set up our model.
//! // This is close to the most complicated a model in rusty-machine gets!
//!
//! // A squared exponential kernel with lengthscale 2, and amplitude 1.
//! let ker = kernel::SquaredExp::new(2., 1.);
//!
//! // The zero function
//! let zero_mean = ConstMean::default();
//!
//! // Construct a GP with the specified kernel, mean, and a noise of 0.5.
//! let mut gp = GaussianProcess::new(ker, zero_mean, 0.5);
//!
//!
//! // Now we can train and predict from the model.
//!
//! // Train the model!
//! gp.train(&inputs, &targets);
//!
//! // Predict output from test datae]
//! let outputs = gp.predict(&test_inputs);
//! ```
//!
//! This code could have been a lot simpler if we had simply adopted
//! `let mut gp = GaussianProcess::default();`. Conversely, you could also implement
//! your own kernels and mean functions by using the appropriate traits.
//!
//! Additionally you'll notice there's quite a few `use` statements at the top of this code.
//! We can remove some of these by utilizing the `prelude`:
//!
//! ```
//! use rusty_machine::prelude::*;
//!
//! let _ = Matrix::new(2,2,vec![2.0;4]);
//! ```
#![deny(missing_docs)]
#![warn(missing_debug_implementations)]
extern crate rulinalg;
extern crate num as libnum;
extern crate rand;
pub mod prelude;
/// The linear algebra module
///
/// This module contains reexports of common tools from the rulinalg crate.
pub mod linalg {
pub use rulinalg::matrix::{Axes, Matrix, MatrixSlice, MatrixSliceMut};
pub use rulinalg::matrix::slice::BaseSlice;
pub use rulinalg::vector::Vector;
pub use rulinalg::Metric;
}
/// Module for data handling
pub mod data {
pub mod transforms;
}
/// Module for machine learning.
pub mod learning {
pub mod dbscan;
pub mod glm;
pub mod gmm;
pub mod lin_reg;
pub mod logistic_reg;
pub mod k_means;
pub mod nnet;
pub mod gp;
pub mod svm;
pub mod naive_bayes;
pub mod error;
/// Trait for supervised model.
pub trait SupModel<T, U> {
/// Predict output from inputs.
fn predict(&self, inputs: &T) -> U;
/// Train the model using inputs and targets.
fn train(&mut self, inputs: &T, targets: &U);
}
/// Trait for unsupervised model.
pub trait UnSupModel<T, U> {
/// Predict output from inputs.
fn predict(&self, inputs: &T) -> U;
/// Train the model using inputs.
fn train(&mut self, inputs: &T);
}
/// Module for optimization in machine learning setting.
pub mod optim {
/// Trait for models which can be gradient-optimized.
pub trait Optimizable {
/// The input data type to the model.
type Inputs;
/// The target data type to the model.
type Targets;
/// Compute the gradient for the model.
fn compute_grad(&self,
params: &[f64],
inputs: &Self::Inputs,
targets: &Self::Targets)
-> (f64, Vec<f64>);
}
/// Trait for optimization algorithms.
pub trait OptimAlgorithm<M: Optimizable> {
/// Return the optimized parameter using gradient optimization.
///
/// Takes in a set of starting parameters and related model data.
fn optimize(&self,
model: &M,
start: &[f64],
inputs: &M::Inputs,
targets: &M::Targets)
-> Vec<f64>;
}
pub mod grad_desc;
pub mod fmincg;
}
/// Module for learning tools.
pub mod toolkit {
pub mod activ_fn;
pub mod kernel;
pub mod cost_fn;
pub mod rand_utils;
pub mod regularization;
}
}
#[cfg(feature = "stats")]
/// Module for computational statistics
pub mod stats {
/// Module for statistical distributions.
pub mod dist;
}
|
//! ### linalg
|
random_line_split
|
util.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use container::Container;
use fmt;
use from_str::FromStr;
use io::IoResult;
use io;
use iter::Iterator;
use libc;
use option::{Some, None, Option};
use os;
use result::Ok;
use str::StrSlice;
use unstable::running_on_valgrind;
use slice::ImmutableVector;
// Indicates whether we should perform expensive sanity checks, including rtassert!
// FIXME: Once the runtime matures remove the `true` below to turn off rtassert, etc.
pub static ENFORCE_SANITY: bool = true ||!cfg!(rtopt) || cfg!(rtdebug) || cfg!(rtassert);
/// Get the number of cores available
pub fn num_cpus() -> uint {
unsafe {
return rust_get_num_cpus();
}
extern {
fn rust_get_num_cpus() -> libc::uintptr_t;
}
}
/// Valgrind has a fixed-sized array (size around 2000) of segment descriptors
/// wired into it; this is a hard limit and requires rebuilding valgrind if you
/// want to go beyond it. Normally this is not a problem, but in some tests, we
/// produce a lot of threads casually. Making lots of threads alone might not
/// be a problem _either_, except on OSX, the segments produced for new threads
/// _take a while_ to get reclaimed by the OS. Combined with the fact that libuv
/// schedulers fork off a separate thread for polling fsevents on OSX, we get a
/// perfect storm of creating "too many mappings" for valgrind to handle when
/// running certain stress tests in the runtime.
pub fn limit_thread_creation_due_to_osx_and_valgrind() -> bool {
(cfg!(target_os="macos")) && running_on_valgrind()
}
/// Get's the number of scheduler threads requested by the environment
/// either `RUST_THREADS` or `num_cpus`.
pub fn default_sched_threads() -> uint
|
pub struct Stderr;
impl io::Writer for Stderr {
fn write(&mut self, data: &[u8]) -> IoResult<()> {
unsafe {
libc::write(libc::STDERR_FILENO,
data.as_ptr() as *libc::c_void,
data.len() as libc::size_t);
}
Ok(()) // yes, we're lying
}
}
pub fn dumb_println(args: &fmt::Arguments) {
let mut w = Stderr;
let _ = fmt::writeln(&mut w as &mut io::Writer, args);
}
pub fn abort(msg: &str) ->! {
let msg = if!msg.is_empty() { msg } else { "aborted" };
let hash = msg.chars().fold(0, |accum, val| accum + (val as uint) );
let quote = match hash % 10 {
0 => "
It was from the artists and poets that the pertinent answers came, and I
know that panic would have broken loose had they been able to compare notes.
As it was, lacking their original letters, I half suspected the compiler of
having asked leading questions, or of having edited the correspondence in
corroboration of what he had latently resolved to see.",
1 => "
There are not many persons who know what wonders are opened to them in the
stories and visions of their youth; for when as children we listen and dream,
we think but half-formed thoughts, and when as men we try to remember, we are
dulled and prosaic with the poison of life. But some of us awake in the night
with strange phantasms of enchanted hills and gardens, of fountains that sing
in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch
down to sleeping cities of bronze and stone, and of shadowy companies of heroes
that ride caparisoned white horses along the edges of thick forests; and then
we know that we have looked back through the ivory gates into that world of
wonder which was ours before we were wise and unhappy.",
2 => "
Instead of the poems I had hoped for, there came only a shuddering blackness
and ineffable loneliness; and I saw at last a fearful truth which no one had
ever dared to breathe before β the unwhisperable secret of secrets β The fact
that this city of stone and stridor is not a sentient perpetuation of Old New
York as London is of Old London and Paris of Old Paris, but that it is in fact
quite dead, its sprawling body imperfectly embalmed and infested with queer
animate things which have nothing to do with it as it was in life.",
3 => "
The ocean ate the last of the land and poured into the smoking gulf, thereby
giving up all it had ever conquered. From the new-flooded lands it flowed
again, uncovering death and decay; and from its ancient and immemorial bed it
trickled loathsomely, uncovering nighted secrets of the years when Time was
young and the gods unborn. Above the waves rose weedy remembered spires. The
moon laid pale lilies of light on dead London, and Paris stood up from its damp
grave to be sanctified with star-dust. Then rose spires and monoliths that were
weedy but not remembered; terrible spires and monoliths of lands that men never
knew were lands...",
4 => "
There was a night when winds from unknown spaces whirled us irresistibly into
limitless vacuum beyond all thought and entity. Perceptions of the most
maddeningly untransmissible sort thronged upon us; perceptions of infinity
which at the time convulsed us with joy, yet which are now partly lost to my
memory and partly incapable of presentation to others.",
_ => "You've met with a terrible fate, haven't you?"
};
rterrln!("{}", "");
rterrln!("{}", quote);
rterrln!("{}", "");
rterrln!("fatal runtime error: {}", msg);
{
let mut err = Stderr;
let _err = ::rt::backtrace::write(&mut err);
}
abort();
fn abort() ->! {
use intrinsics;
unsafe { intrinsics::abort() }
}
}
|
{
match os::getenv("RUST_THREADS") {
Some(nstr) => {
let opt_n: Option<uint> = FromStr::from_str(nstr);
match opt_n {
Some(n) if n > 0 => n,
_ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
}
}
None => {
if limit_thread_creation_due_to_osx_and_valgrind() {
1
} else {
num_cpus()
}
}
}
}
|
identifier_body
|
util.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use container::Container;
use fmt;
use from_str::FromStr;
use io::IoResult;
use io;
use iter::Iterator;
use libc;
use option::{Some, None, Option};
use os;
use result::Ok;
use str::StrSlice;
use unstable::running_on_valgrind;
use slice::ImmutableVector;
// Indicates whether we should perform expensive sanity checks, including rtassert!
// FIXME: Once the runtime matures remove the `true` below to turn off rtassert, etc.
pub static ENFORCE_SANITY: bool = true ||!cfg!(rtopt) || cfg!(rtdebug) || cfg!(rtassert);
/// Get the number of cores available
pub fn num_cpus() -> uint {
unsafe {
return rust_get_num_cpus();
}
extern {
fn rust_get_num_cpus() -> libc::uintptr_t;
}
}
/// Valgrind has a fixed-sized array (size around 2000) of segment descriptors
/// wired into it; this is a hard limit and requires rebuilding valgrind if you
/// want to go beyond it. Normally this is not a problem, but in some tests, we
/// produce a lot of threads casually. Making lots of threads alone might not
/// be a problem _either_, except on OSX, the segments produced for new threads
/// _take a while_ to get reclaimed by the OS. Combined with the fact that libuv
/// schedulers fork off a separate thread for polling fsevents on OSX, we get a
/// perfect storm of creating "too many mappings" for valgrind to handle when
/// running certain stress tests in the runtime.
pub fn
|
() -> bool {
(cfg!(target_os="macos")) && running_on_valgrind()
}
/// Get's the number of scheduler threads requested by the environment
/// either `RUST_THREADS` or `num_cpus`.
pub fn default_sched_threads() -> uint {
match os::getenv("RUST_THREADS") {
Some(nstr) => {
let opt_n: Option<uint> = FromStr::from_str(nstr);
match opt_n {
Some(n) if n > 0 => n,
_ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
}
}
None => {
if limit_thread_creation_due_to_osx_and_valgrind() {
1
} else {
num_cpus()
}
}
}
}
pub struct Stderr;
impl io::Writer for Stderr {
fn write(&mut self, data: &[u8]) -> IoResult<()> {
unsafe {
libc::write(libc::STDERR_FILENO,
data.as_ptr() as *libc::c_void,
data.len() as libc::size_t);
}
Ok(()) // yes, we're lying
}
}
pub fn dumb_println(args: &fmt::Arguments) {
let mut w = Stderr;
let _ = fmt::writeln(&mut w as &mut io::Writer, args);
}
pub fn abort(msg: &str) ->! {
let msg = if!msg.is_empty() { msg } else { "aborted" };
let hash = msg.chars().fold(0, |accum, val| accum + (val as uint) );
let quote = match hash % 10 {
0 => "
It was from the artists and poets that the pertinent answers came, and I
know that panic would have broken loose had they been able to compare notes.
As it was, lacking their original letters, I half suspected the compiler of
having asked leading questions, or of having edited the correspondence in
corroboration of what he had latently resolved to see.",
1 => "
There are not many persons who know what wonders are opened to them in the
stories and visions of their youth; for when as children we listen and dream,
we think but half-formed thoughts, and when as men we try to remember, we are
dulled and prosaic with the poison of life. But some of us awake in the night
with strange phantasms of enchanted hills and gardens, of fountains that sing
in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch
down to sleeping cities of bronze and stone, and of shadowy companies of heroes
that ride caparisoned white horses along the edges of thick forests; and then
we know that we have looked back through the ivory gates into that world of
wonder which was ours before we were wise and unhappy.",
2 => "
Instead of the poems I had hoped for, there came only a shuddering blackness
and ineffable loneliness; and I saw at last a fearful truth which no one had
ever dared to breathe before β the unwhisperable secret of secrets β The fact
that this city of stone and stridor is not a sentient perpetuation of Old New
York as London is of Old London and Paris of Old Paris, but that it is in fact
quite dead, its sprawling body imperfectly embalmed and infested with queer
animate things which have nothing to do with it as it was in life.",
3 => "
The ocean ate the last of the land and poured into the smoking gulf, thereby
giving up all it had ever conquered. From the new-flooded lands it flowed
again, uncovering death and decay; and from its ancient and immemorial bed it
trickled loathsomely, uncovering nighted secrets of the years when Time was
young and the gods unborn. Above the waves rose weedy remembered spires. The
moon laid pale lilies of light on dead London, and Paris stood up from its damp
grave to be sanctified with star-dust. Then rose spires and monoliths that were
weedy but not remembered; terrible spires and monoliths of lands that men never
knew were lands...",
4 => "
There was a night when winds from unknown spaces whirled us irresistibly into
limitless vacuum beyond all thought and entity. Perceptions of the most
maddeningly untransmissible sort thronged upon us; perceptions of infinity
which at the time convulsed us with joy, yet which are now partly lost to my
memory and partly incapable of presentation to others.",
_ => "You've met with a terrible fate, haven't you?"
};
rterrln!("{}", "");
rterrln!("{}", quote);
rterrln!("{}", "");
rterrln!("fatal runtime error: {}", msg);
{
let mut err = Stderr;
let _err = ::rt::backtrace::write(&mut err);
}
abort();
fn abort() ->! {
use intrinsics;
unsafe { intrinsics::abort() }
}
}
|
limit_thread_creation_due_to_osx_and_valgrind
|
identifier_name
|
util.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use container::Container;
use fmt;
use from_str::FromStr;
use io::IoResult;
use io;
use iter::Iterator;
use libc;
use option::{Some, None, Option};
use os;
use result::Ok;
use str::StrSlice;
use unstable::running_on_valgrind;
use slice::ImmutableVector;
// Indicates whether we should perform expensive sanity checks, including rtassert!
// FIXME: Once the runtime matures remove the `true` below to turn off rtassert, etc.
pub static ENFORCE_SANITY: bool = true ||!cfg!(rtopt) || cfg!(rtdebug) || cfg!(rtassert);
/// Get the number of cores available
pub fn num_cpus() -> uint {
unsafe {
return rust_get_num_cpus();
}
extern {
fn rust_get_num_cpus() -> libc::uintptr_t;
}
}
/// Valgrind has a fixed-sized array (size around 2000) of segment descriptors
/// wired into it; this is a hard limit and requires rebuilding valgrind if you
/// want to go beyond it. Normally this is not a problem, but in some tests, we
/// produce a lot of threads casually. Making lots of threads alone might not
/// be a problem _either_, except on OSX, the segments produced for new threads
/// _take a while_ to get reclaimed by the OS. Combined with the fact that libuv
/// schedulers fork off a separate thread for polling fsevents on OSX, we get a
/// perfect storm of creating "too many mappings" for valgrind to handle when
/// running certain stress tests in the runtime.
pub fn limit_thread_creation_due_to_osx_and_valgrind() -> bool {
(cfg!(target_os="macos")) && running_on_valgrind()
}
/// Get's the number of scheduler threads requested by the environment
/// either `RUST_THREADS` or `num_cpus`.
pub fn default_sched_threads() -> uint {
match os::getenv("RUST_THREADS") {
Some(nstr) => {
let opt_n: Option<uint> = FromStr::from_str(nstr);
match opt_n {
Some(n) if n > 0 => n,
_ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
}
}
None => {
if limit_thread_creation_due_to_osx_and_valgrind() {
1
} else {
num_cpus()
}
}
}
}
pub struct Stderr;
impl io::Writer for Stderr {
fn write(&mut self, data: &[u8]) -> IoResult<()> {
unsafe {
libc::write(libc::STDERR_FILENO,
data.as_ptr() as *libc::c_void,
data.len() as libc::size_t);
}
Ok(()) // yes, we're lying
}
}
pub fn dumb_println(args: &fmt::Arguments) {
let mut w = Stderr;
let _ = fmt::writeln(&mut w as &mut io::Writer, args);
}
pub fn abort(msg: &str) ->! {
let msg = if!msg.is_empty() { msg } else { "aborted" };
let hash = msg.chars().fold(0, |accum, val| accum + (val as uint) );
let quote = match hash % 10 {
0 => "
It was from the artists and poets that the pertinent answers came, and I
know that panic would have broken loose had they been able to compare notes.
As it was, lacking their original letters, I half suspected the compiler of
having asked leading questions, or of having edited the correspondence in
corroboration of what he had latently resolved to see.",
1 => "
There are not many persons who know what wonders are opened to them in the
stories and visions of their youth; for when as children we listen and dream,
we think but half-formed thoughts, and when as men we try to remember, we are
dulled and prosaic with the poison of life. But some of us awake in the night
with strange phantasms of enchanted hills and gardens, of fountains that sing
in the sun, of golden cliffs overhanging murmuring seas, of plains that stretch
down to sleeping cities of bronze and stone, and of shadowy companies of heroes
that ride caparisoned white horses along the edges of thick forests; and then
we know that we have looked back through the ivory gates into that world of
wonder which was ours before we were wise and unhappy.",
2 => "
Instead of the poems I had hoped for, there came only a shuddering blackness
and ineffable loneliness; and I saw at last a fearful truth which no one had
ever dared to breathe before β the unwhisperable secret of secrets β The fact
that this city of stone and stridor is not a sentient perpetuation of Old New
York as London is of Old London and Paris of Old Paris, but that it is in fact
quite dead, its sprawling body imperfectly embalmed and infested with queer
animate things which have nothing to do with it as it was in life.",
3 => "
The ocean ate the last of the land and poured into the smoking gulf, thereby
giving up all it had ever conquered. From the new-flooded lands it flowed
again, uncovering death and decay; and from its ancient and immemorial bed it
trickled loathsomely, uncovering nighted secrets of the years when Time was
young and the gods unborn. Above the waves rose weedy remembered spires. The
moon laid pale lilies of light on dead London, and Paris stood up from its damp
grave to be sanctified with star-dust. Then rose spires and monoliths that were
weedy but not remembered; terrible spires and monoliths of lands that men never
knew were lands...",
4 => "
|
limitless vacuum beyond all thought and entity. Perceptions of the most
maddeningly untransmissible sort thronged upon us; perceptions of infinity
which at the time convulsed us with joy, yet which are now partly lost to my
memory and partly incapable of presentation to others.",
_ => "You've met with a terrible fate, haven't you?"
};
rterrln!("{}", "");
rterrln!("{}", quote);
rterrln!("{}", "");
rterrln!("fatal runtime error: {}", msg);
{
let mut err = Stderr;
let _err = ::rt::backtrace::write(&mut err);
}
abort();
fn abort() ->! {
use intrinsics;
unsafe { intrinsics::abort() }
}
}
|
There was a night when winds from unknown spaces whirled us irresistibly into
|
random_line_split
|
moves-based-on-type-exprs.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.
// Tests that references to move-by-default values trigger moves when
// they occur as part of various kinds of expressions.
struct Foo<A> { f: A }
fn guard(_s: String) -> bool {fail!()}
fn touch<A>(_a: &A) {}
fn f10() {
let x = "hi".to_string();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
let x = "hi".to_string();
let _y = (x, 3i);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f21() {
let x = vec!(1i, 2, 3);
let _y = (*x.get(0), 3i);
touch(&x);
}
fn f30(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = if cond {
x
} else {
y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn
|
(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f50(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
_ if guard(x) => 10i,
true => 10i,
false => 20i,
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y);
}
fn f70() {
let x = "hi".to_string();
let _y = [x];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f80() {
let x = "hi".to_string();
let _y = vec!(x);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f100() {
let x = vec!("hi".to_string());
let _y = x.into_iter().next().unwrap();
touch(&x); //~ ERROR use of moved value: `x`
}
fn f110() {
let x = vec!("hi".to_string());
let _y = [x.into_iter().next().unwrap(),..1];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f120() {
let mut x = vec!("hi".to_string(), "ho".to_string());
x.as_mut_slice().swap(0, 1);
touch(x.get(0));
touch(x.get(1));
}
fn main() {}
|
f40
|
identifier_name
|
moves-based-on-type-exprs.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.
// Tests that references to move-by-default values trigger moves when
// they occur as part of various kinds of expressions.
struct Foo<A> { f: A }
fn guard(_s: String) -> bool {fail!()}
fn touch<A>(_a: &A) {}
fn f10() {
let x = "hi".to_string();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
let x = "hi".to_string();
let _y = (x, 3i);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f21() {
let x = vec!(1i, 2, 3);
let _y = (*x.get(0), 3i);
touch(&x);
}
fn f30(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = if cond
|
else {
y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f40(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f50(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
_ if guard(x) => 10i,
true => 10i,
false => 20i,
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y);
}
fn f70() {
let x = "hi".to_string();
let _y = [x];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f80() {
let x = "hi".to_string();
let _y = vec!(x);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f100() {
let x = vec!("hi".to_string());
let _y = x.into_iter().next().unwrap();
touch(&x); //~ ERROR use of moved value: `x`
}
fn f110() {
let x = vec!("hi".to_string());
let _y = [x.into_iter().next().unwrap(),..1];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f120() {
let mut x = vec!("hi".to_string(), "ho".to_string());
x.as_mut_slice().swap(0, 1);
touch(x.get(0));
touch(x.get(1));
}
fn main() {}
|
{
x
}
|
conditional_block
|
moves-based-on-type-exprs.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.
// Tests that references to move-by-default values trigger moves when
// they occur as part of various kinds of expressions.
struct Foo<A> { f: A }
fn guard(_s: String) -> bool {fail!()}
fn touch<A>(_a: &A)
|
fn f10() {
let x = "hi".to_string();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
let x = "hi".to_string();
let _y = (x, 3i);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f21() {
let x = vec!(1i, 2, 3);
let _y = (*x.get(0), 3i);
touch(&x);
}
fn f30(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = if cond {
x
} else {
y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f40(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f50(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
_ if guard(x) => 10i,
true => 10i,
false => 20i,
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y);
}
fn f70() {
let x = "hi".to_string();
let _y = [x];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f80() {
let x = "hi".to_string();
let _y = vec!(x);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f100() {
let x = vec!("hi".to_string());
let _y = x.into_iter().next().unwrap();
touch(&x); //~ ERROR use of moved value: `x`
}
fn f110() {
let x = vec!("hi".to_string());
let _y = [x.into_iter().next().unwrap(),..1];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f120() {
let mut x = vec!("hi".to_string(), "ho".to_string());
x.as_mut_slice().swap(0, 1);
touch(x.get(0));
touch(x.get(1));
}
fn main() {}
|
{}
|
identifier_body
|
moves-based-on-type-exprs.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.
// Tests that references to move-by-default values trigger moves when
// they occur as part of various kinds of expressions.
struct Foo<A> { f: A }
fn guard(_s: String) -> bool {fail!()}
fn touch<A>(_a: &A) {}
fn f10() {
let x = "hi".to_string();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
let x = "hi".to_string();
let _y = (x, 3i);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f21() {
let x = vec!(1i, 2, 3);
let _y = (*x.get(0), 3i);
touch(&x);
}
fn f30(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = if cond {
x
} else {
y
};
|
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f40(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f50(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
_ if guard(x) => 10i,
true => 10i,
false => 20i,
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y);
}
fn f70() {
let x = "hi".to_string();
let _y = [x];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f80() {
let x = "hi".to_string();
let _y = vec!(x);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f100() {
let x = vec!("hi".to_string());
let _y = x.into_iter().next().unwrap();
touch(&x); //~ ERROR use of moved value: `x`
}
fn f110() {
let x = vec!("hi".to_string());
let _y = [x.into_iter().next().unwrap(),..1];
touch(&x); //~ ERROR use of moved value: `x`
}
fn f120() {
let mut x = vec!("hi".to_string(), "ho".to_string());
x.as_mut_slice().swap(0, 1);
touch(x.get(0));
touch(x.get(1));
}
fn main() {}
|
random_line_split
|
|
cache_aligned.rs
|
use alloc::heap::{allocate, deallocate};
use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
allocate(size, CACHE_LINE_SIZE)
}
pub struct CacheAligned<T: Sized> {
ptr: Unique<T>,
}
impl<T: Sized> Drop for CacheAligned<T> {
fn drop(&mut self) {
unsafe {
deallocate(*self.ptr as *mut u8, size_of::<T>(), 64);
}
}
}
impl<T: Sized> Deref for CacheAligned<T> {
type Target = T;
fn
|
(&self) -> &T {
unsafe { self.ptr.get() }
}
}
impl<T: Sized> DerefMut for CacheAligned<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.ptr.get_mut() }
}
}
impl<T: Sized> CacheAligned<T> {
pub fn allocate(src: T) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::write(alloc, src);
CacheAligned { ptr: Unique::new(alloc) }
}
}
}
impl<T: Sized> Clone for CacheAligned<T>
where T: Clone
{
fn clone(&self) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::copy(self.ptr.get() as *const T, alloc, 1);
CacheAligned { ptr: Unique::new(alloc) }
}
}
}
impl<T: Sized> fmt::Display for CacheAligned<T>
where T: fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
T::fmt(&*self, f)
}
}
|
deref
|
identifier_name
|
cache_aligned.rs
|
use alloc::heap::{allocate, deallocate};
use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
allocate(size, CACHE_LINE_SIZE)
}
pub struct CacheAligned<T: Sized> {
ptr: Unique<T>,
}
impl<T: Sized> Drop for CacheAligned<T> {
fn drop(&mut self) {
unsafe {
deallocate(*self.ptr as *mut u8, size_of::<T>(), 64);
}
}
}
impl<T: Sized> Deref for CacheAligned<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.get() }
}
}
impl<T: Sized> DerefMut for CacheAligned<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.ptr.get_mut() }
}
}
impl<T: Sized> CacheAligned<T> {
pub fn allocate(src: T) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::write(alloc, src);
CacheAligned { ptr: Unique::new(alloc) }
}
}
}
impl<T: Sized> Clone for CacheAligned<T>
where T: Clone
{
fn clone(&self) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::copy(self.ptr.get() as *const T, alloc, 1);
CacheAligned { ptr: Unique::new(alloc) }
}
}
}
impl<T: Sized> fmt::Display for CacheAligned<T>
where T: fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
|
{
T::fmt(&*self, f)
}
|
identifier_body
|
cache_aligned.rs
|
use alloc::heap::{allocate, deallocate};
|
use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
allocate(size, CACHE_LINE_SIZE)
}
pub struct CacheAligned<T: Sized> {
ptr: Unique<T>,
}
impl<T: Sized> Drop for CacheAligned<T> {
fn drop(&mut self) {
unsafe {
deallocate(*self.ptr as *mut u8, size_of::<T>(), 64);
}
}
}
impl<T: Sized> Deref for CacheAligned<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.ptr.get() }
}
}
impl<T: Sized> DerefMut for CacheAligned<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.ptr.get_mut() }
}
}
impl<T: Sized> CacheAligned<T> {
pub fn allocate(src: T) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::write(alloc, src);
CacheAligned { ptr: Unique::new(alloc) }
}
}
}
impl<T: Sized> Clone for CacheAligned<T>
where T: Clone
{
fn clone(&self) -> CacheAligned<T> {
unsafe {
let alloc = allocate_cache_line(size_of::<T>()) as *mut T;
ptr::copy(self.ptr.get() as *const T, alloc, 1);
CacheAligned { ptr: Unique::new(alloc) }
}
}
}
impl<T: Sized> fmt::Display for CacheAligned<T>
where T: fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
T::fmt(&*self, f)
}
}
|
random_line_split
|
|
issue-16272.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::process::Command;
use std::env;
fn main() {
let len = env::args().len();
if len == 1 {
test();
} else {
assert_eq!(len, 3);
}
}
fn
|
() {
let status = Command::new(&env::current_exe().unwrap())
.arg("foo").arg("")
.status().unwrap();
assert!(status.success());
}
|
test
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.