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 |
---|---|---|---|---|
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or directory content of two paths.
//! When possible, this is done in an atomic fashion, so that only the full changes are observable.
//!
//! Currently, atomic exchange is only supported on Windows and Linux.
use std::path;
pub use error::Error;
mod platform;
mod non_atomic;
mod error;
/// Exchange the content of the objects pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation is atomic**, meaning if the content at one path changed, the other path will
/// also have changed. If the operation can't be done atomically, it will fail.
pub fn xch<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> { |
/// Exchange the content of the object pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation may not be atomic**. If available, it will try to use the platform specific,
/// atomic operations. If they are not implemented, this will fallback to a non-atomic exchange.
pub fn xch_non_atomic<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
let res = platform::xch(&path1, &path2);
if let Err(error::Error::NotImplemented) = res {
non_atomic::xch(&path1, &path2)
} else {
res
}
}
|
platform::xch(path1, path2)
}
| identifier_body |
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
// | // Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or directory content of two paths.
//! When possible, this is done in an atomic fashion, so that only the full changes are observable.
//!
//! Currently, atomic exchange is only supported on Windows and Linux.
use std::path;
pub use error::Error;
mod platform;
mod non_atomic;
mod error;
/// Exchange the content of the objects pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation is atomic**, meaning if the content at one path changed, the other path will
/// also have changed. If the operation can't be done atomically, it will fail.
pub fn xch<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
platform::xch(path1, path2)
}
/// Exchange the content of the object pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation may not be atomic**. If available, it will try to use the platform specific,
/// atomic operations. If they are not implemented, this will fallback to a non-atomic exchange.
pub fn xch_non_atomic<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
let res = platform::xch(&path1, &path2);
if let Err(error::Error::NotImplemented) = res {
non_atomic::xch(&path1, &path2)
} else {
res
}
} | random_line_split |
|
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or directory content of two paths.
//! When possible, this is done in an atomic fashion, so that only the full changes are observable.
//!
//! Currently, atomic exchange is only supported on Windows and Linux.
use std::path;
pub use error::Error;
mod platform;
mod non_atomic;
mod error;
/// Exchange the content of the objects pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation is atomic**, meaning if the content at one path changed, the other path will
/// also have changed. If the operation can't be done atomically, it will fail.
pub fn xch<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
platform::xch(path1, path2)
}
/// Exchange the content of the object pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation may not be atomic**. If available, it will try to use the platform specific,
/// atomic operations. If they are not implemented, this will fallback to a non-atomic exchange.
pub fn x | A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
let res = platform::xch(&path1, &path2);
if let Err(error::Error::NotImplemented) = res {
non_atomic::xch(&path1, &path2)
} else {
res
}
}
| ch_non_atomic< | identifier_name |
lib.rs | // Copyright 2017-2019 Moritz Wanzenböck.
//
// Licensed under the MIT License <LICENSE or http://opensource.org/licenses/MIT>.
// This file may not be copied, modified, or distributed except according to those terms.
//! A library for exchanging paths
//!
//! This library provides a simple utility to swap files and/or directory content of two paths.
//! When possible, this is done in an atomic fashion, so that only the full changes are observable.
//!
//! Currently, atomic exchange is only supported on Windows and Linux.
use std::path;
pub use error::Error;
mod platform;
mod non_atomic;
mod error;
/// Exchange the content of the objects pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation is atomic**, meaning if the content at one path changed, the other path will
/// also have changed. If the operation can't be done atomically, it will fail.
pub fn xch<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
platform::xch(path1, path2)
}
/// Exchange the content of the object pointed to by the two paths.
///
/// This can be used to swap the content of two files, but it also works with directories.
/// **This operation may not be atomic**. If available, it will try to use the platform specific,
/// atomic operations. If they are not implemented, this will fallback to a non-atomic exchange.
pub fn xch_non_atomic<A: AsRef<path::Path>, B: AsRef<path::Path>>(path1: A, path2: B) -> error::Result<()> {
let res = platform::xch(&path1, &path2);
if let Err(error::Error::NotImplemented) = res {
non_atomic::xch(&path1, &path2)
} else { | }
|
res
}
| conditional_block |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct | {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn parse_from(
file: &Path,
config: &Config,
debugger_prefixes: &[&str],
) -> Result<Self, String> {
let directives = debugger_prefixes
.iter()
.map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
.collect::<Vec<_>>();
let mut breakpoint_lines = vec![];
let mut commands = vec![];
let mut check_lines = vec![];
let mut counter = 1;
let reader = BufReader::new(File::open(file).unwrap());
for line in reader.lines() {
match line {
Ok(line) => {
let line =
if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
if line.contains("#break") {
breakpoint_lines.push(counter);
}
for &(ref command_directive, ref check_directive) in &directives {
config
.parse_name_value_directive(&line, command_directive)
.map(|cmd| commands.push(cmd));
config
.parse_name_value_directive(&line, check_directive)
.map(|cmd| check_lines.push(cmd));
}
}
Err(e) => return Err(format!("Error while parsing debugger commands: {}", e)),
}
counter += 1;
}
Ok(Self { commands, check_lines, breakpoint_lines })
}
}
pub(super) fn check_debugger_output(
debugger_run_result: &ProcRes,
check_lines: &[String],
) -> Result<(), String> {
let num_check_lines = check_lines.len();
let mut check_line_index = 0;
for line in debugger_run_result.stdout.lines() {
if check_line_index >= num_check_lines {
break;
}
if check_single_line(line, &(check_lines[check_line_index])[..]) {
check_line_index += 1;
}
}
if check_line_index!= num_check_lines && num_check_lines > 0 {
Err(format!("line not found in debugger output: {}", check_lines[check_line_index]))
} else {
Ok(())
}
}
fn check_single_line(line: &str, check_line: &str) -> bool {
// Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim();
let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_with("[...]");
let check_fragments: Vec<&str> =
check_line.split("[...]").filter(|frag|!frag.is_empty()).collect();
if check_fragments.is_empty() {
return true;
}
let (mut rest, first_fragment) = if can_start_anywhere {
match line.find(check_fragments[0]) {
Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
None => return false,
}
} else {
(line, 0)
};
for current_fragment in &check_fragments[first_fragment..] {
match rest.find(current_fragment) {
Some(pos) => {
rest = &rest[pos + current_fragment.len()..];
}
None => return false,
}
}
if!can_end_anywhere &&!rest.is_empty() { false } else { true }
}
| DebuggerCommands | identifier_name |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct DebuggerCommands {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn parse_from(
file: &Path,
config: &Config,
debugger_prefixes: &[&str],
) -> Result<Self, String> {
let directives = debugger_prefixes
.iter()
.map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
.collect::<Vec<_>>();
let mut breakpoint_lines = vec![];
let mut commands = vec![];
let mut check_lines = vec![];
let mut counter = 1;
let reader = BufReader::new(File::open(file).unwrap());
for line in reader.lines() {
match line {
Ok(line) => {
let line =
if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
if line.contains("#break") {
breakpoint_lines.push(counter);
}
for &(ref command_directive, ref check_directive) in &directives {
config
.parse_name_value_directive(&line, command_directive)
.map(|cmd| commands.push(cmd));
config
.parse_name_value_directive(&line, check_directive)
.map(|cmd| check_lines.push(cmd));
}
}
Err(e) => return Err(format!("Error while parsing debugger commands: {}", e)),
}
counter += 1;
}
Ok(Self { commands, check_lines, breakpoint_lines })
}
}
pub(super) fn check_debugger_output(
debugger_run_result: &ProcRes,
check_lines: &[String],
) -> Result<(), String> {
let num_check_lines = check_lines.len();
let mut check_line_index = 0;
for line in debugger_run_result.stdout.lines() {
if check_line_index >= num_check_lines {
break;
}
if check_single_line(line, &(check_lines[check_line_index])[..]) {
check_line_index += 1;
}
}
if check_line_index!= num_check_lines && num_check_lines > 0 {
Err(format!("line not found in debugger output: {}", check_lines[check_line_index]))
} else {
Ok(())
}
}
fn check_single_line(line: &str, check_line: &str) -> bool {
// Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim();
let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_with("[...]");
let check_fragments: Vec<&str> =
check_line.split("[...]").filter(|frag|!frag.is_empty()).collect();
if check_fragments.is_empty() {
return true;
}
let (mut rest, first_fragment) = if can_start_anywhere {
match line.find(check_fragments[0]) {
Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
None => return false,
}
} else {
(line, 0)
};
for current_fragment in &check_fragments[first_fragment..] {
match rest.find(current_fragment) {
Some(pos) => {
rest = &rest[pos + current_fragment.len()..];
}
None => return false,
}
}
if!can_end_anywhere &&!rest.is_empty() { false } else |
}
| { true } | conditional_block |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct DebuggerCommands {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn parse_from(
file: &Path,
config: &Config,
debugger_prefixes: &[&str],
) -> Result<Self, String> {
let directives = debugger_prefixes
.iter()
.map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
.collect::<Vec<_>>();
let mut breakpoint_lines = vec![];
let mut commands = vec![];
let mut check_lines = vec![];
let mut counter = 1;
let reader = BufReader::new(File::open(file).unwrap());
for line in reader.lines() {
match line {
Ok(line) => {
let line =
if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
if line.contains("#break") {
breakpoint_lines.push(counter);
}
for &(ref command_directive, ref check_directive) in &directives {
config
.parse_name_value_directive(&line, command_directive)
.map(|cmd| commands.push(cmd));
config
.parse_name_value_directive(&line, check_directive)
.map(|cmd| check_lines.push(cmd));
}
}
Err(e) => return Err(format!("Error while parsing debugger commands: {}", e)),
}
counter += 1;
}
Ok(Self { commands, check_lines, breakpoint_lines })
}
}
pub(super) fn check_debugger_output(
debugger_run_result: &ProcRes,
check_lines: &[String],
) -> Result<(), String> {
let num_check_lines = check_lines.len();
let mut check_line_index = 0;
for line in debugger_run_result.stdout.lines() {
if check_line_index >= num_check_lines {
break;
}
if check_single_line(line, &(check_lines[check_line_index])[..]) {
check_line_index += 1;
}
}
if check_line_index!= num_check_lines && num_check_lines > 0 {
Err(format!("line not found in debugger output: {}", check_lines[check_line_index]))
} else {
Ok(())
}
}
fn check_single_line(line: &str, check_line: &str) -> bool | (line, 0)
};
for current_fragment in &check_fragments[first_fragment..] {
match rest.find(current_fragment) {
Some(pos) => {
rest = &rest[pos + current_fragment.len()..];
}
None => return false,
}
}
if!can_end_anywhere &&!rest.is_empty() { false } else { true }
}
| {
// Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim();
let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_with("[...]");
let check_fragments: Vec<&str> =
check_line.split("[...]").filter(|frag| !frag.is_empty()).collect();
if check_fragments.is_empty() {
return true;
}
let (mut rest, first_fragment) = if can_start_anywhere {
match line.find(check_fragments[0]) {
Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
None => return false,
}
} else { | identifier_body |
debugger.rs | use crate::common::Config;
use crate::runtest::ProcRes;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
pub(super) struct DebuggerCommands {
pub commands: Vec<String>,
pub check_lines: Vec<String>,
pub breakpoint_lines: Vec<usize>,
}
impl DebuggerCommands {
pub(super) fn parse_from(
file: &Path,
config: &Config,
debugger_prefixes: &[&str],
) -> Result<Self, String> {
let directives = debugger_prefixes
.iter()
.map(|prefix| (format!("{}-command", prefix), format!("{}-check", prefix)))
.collect::<Vec<_>>();
let mut breakpoint_lines = vec![];
let mut commands = vec![];
let mut check_lines = vec![];
let mut counter = 1;
let reader = BufReader::new(File::open(file).unwrap());
for line in reader.lines() {
match line {
Ok(line) => {
let line =
if line.starts_with("//") { line[2..].trim_start() } else { line.as_str() };
if line.contains("#break") {
breakpoint_lines.push(counter);
}
for &(ref command_directive, ref check_directive) in &directives {
config
.parse_name_value_directive(&line, command_directive)
.map(|cmd| commands.push(cmd));
config
.parse_name_value_directive(&line, check_directive)
.map(|cmd| check_lines.push(cmd));
}
}
Err(e) => return Err(format!("Error while parsing debugger commands: {}", e)),
}
counter += 1;
}
Ok(Self { commands, check_lines, breakpoint_lines })
}
}
pub(super) fn check_debugger_output(
debugger_run_result: &ProcRes,
check_lines: &[String],
) -> Result<(), String> {
let num_check_lines = check_lines.len();
let mut check_line_index = 0;
for line in debugger_run_result.stdout.lines() {
if check_line_index >= num_check_lines {
break;
}
if check_single_line(line, &(check_lines[check_line_index])[..]) {
check_line_index += 1;
}
}
if check_line_index!= num_check_lines && num_check_lines > 0 {
Err(format!("line not found in debugger output: {}", check_lines[check_line_index]))
} else {
Ok(())
}
}
fn check_single_line(line: &str, check_line: &str) -> bool { | let can_start_anywhere = check_line.starts_with("[...]");
let can_end_anywhere = check_line.ends_with("[...]");
let check_fragments: Vec<&str> =
check_line.split("[...]").filter(|frag|!frag.is_empty()).collect();
if check_fragments.is_empty() {
return true;
}
let (mut rest, first_fragment) = if can_start_anywhere {
match line.find(check_fragments[0]) {
Some(pos) => (&line[pos + check_fragments[0].len()..], 1),
None => return false,
}
} else {
(line, 0)
};
for current_fragment in &check_fragments[first_fragment..] {
match rest.find(current_fragment) {
Some(pos) => {
rest = &rest[pos + current_fragment.len()..];
}
None => return false,
}
}
if!can_end_anywhere &&!rest.is_empty() { false } else { true }
} | // Allow check lines to leave parts unspecified (e.g., uninitialized
// bits in the wrong case of an enum) with the notation "[...]".
let line = line.trim();
let check_line = check_line.trim(); | random_line_split |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use attr::{AttrSelectorOperation, NamespaceConstraint};
use matching::{ElementSelectorFlags, MatchingContext, RelevantLinkStatus};
use parser::SelectorImpl; |
fn parent_element(&self) -> Option<Self>;
/// The parent of a given pseudo-element, after matching a pseudo-element
/// selector.
///
/// This is guaranteed to be called in a pseudo-element.
fn pseudo_element_originating_element(&self) -> Option<Self> {
self.parent_element()
}
/// Skips non-element nodes
fn first_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn last_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn next_sibling_element(&self) -> Option<Self>;
fn is_html_element_in_html_document(&self) -> bool;
fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName;
/// Empty string for no namespace
fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl;
fn attr_matches(&self,
ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>,
local_name: &<Self::Impl as SelectorImpl>::LocalName,
operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>)
-> bool;
fn match_non_ts_pseudo_class<F>(&self,
pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass,
context: &mut MatchingContext,
relevant_link: &RelevantLinkStatus,
flags_setter: &mut F) -> bool
where F: FnMut(&Self, ElementSelectorFlags);
fn match_pseudo_element(&self,
pe: &<Self::Impl as SelectorImpl>::PseudoElement,
context: &mut MatchingContext)
-> bool;
/// Whether this element is a `link`.
fn is_link(&self) -> bool;
fn get_id(&self) -> Option<<Self::Impl as SelectorImpl>::Identifier>;
fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName) -> bool;
/// Returns whether this element matches `:empty`.
///
/// That is, whether it does not contain any child element or any non-zero-length text node.
/// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo
fn is_empty(&self) -> bool;
/// Returns whether this element matches `:root`,
/// i.e. whether it is the root element of a document.
///
/// Note: this can be false even if `.parent_element()` is `None`
/// if the parent node is a `DocumentFragment`.
fn is_root(&self) -> bool;
} |
pub trait Element: Sized {
type Impl: SelectorImpl; | random_line_split |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use attr::{AttrSelectorOperation, NamespaceConstraint};
use matching::{ElementSelectorFlags, MatchingContext, RelevantLinkStatus};
use parser::SelectorImpl;
pub trait Element: Sized {
type Impl: SelectorImpl;
fn parent_element(&self) -> Option<Self>;
/// The parent of a given pseudo-element, after matching a pseudo-element
/// selector.
///
/// This is guaranteed to be called in a pseudo-element.
fn pseudo_element_originating_element(&self) -> Option<Self> |
/// Skips non-element nodes
fn first_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn last_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn next_sibling_element(&self) -> Option<Self>;
fn is_html_element_in_html_document(&self) -> bool;
fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName;
/// Empty string for no namespace
fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl;
fn attr_matches(&self,
ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>,
local_name: &<Self::Impl as SelectorImpl>::LocalName,
operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>)
-> bool;
fn match_non_ts_pseudo_class<F>(&self,
pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass,
context: &mut MatchingContext,
relevant_link: &RelevantLinkStatus,
flags_setter: &mut F) -> bool
where F: FnMut(&Self, ElementSelectorFlags);
fn match_pseudo_element(&self,
pe: &<Self::Impl as SelectorImpl>::PseudoElement,
context: &mut MatchingContext)
-> bool;
/// Whether this element is a `link`.
fn is_link(&self) -> bool;
fn get_id(&self) -> Option<<Self::Impl as SelectorImpl>::Identifier>;
fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName) -> bool;
/// Returns whether this element matches `:empty`.
///
/// That is, whether it does not contain any child element or any non-zero-length text node.
/// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo
fn is_empty(&self) -> bool;
/// Returns whether this element matches `:root`,
/// i.e. whether it is the root element of a document.
///
/// Note: this can be false even if `.parent_element()` is `None`
/// if the parent node is a `DocumentFragment`.
fn is_root(&self) -> bool;
}
| {
self.parent_element()
} | identifier_body |
tree.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/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use attr::{AttrSelectorOperation, NamespaceConstraint};
use matching::{ElementSelectorFlags, MatchingContext, RelevantLinkStatus};
use parser::SelectorImpl;
pub trait Element: Sized {
type Impl: SelectorImpl;
fn parent_element(&self) -> Option<Self>;
/// The parent of a given pseudo-element, after matching a pseudo-element
/// selector.
///
/// This is guaranteed to be called in a pseudo-element.
fn | (&self) -> Option<Self> {
self.parent_element()
}
/// Skips non-element nodes
fn first_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn last_child_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn prev_sibling_element(&self) -> Option<Self>;
/// Skips non-element nodes
fn next_sibling_element(&self) -> Option<Self>;
fn is_html_element_in_html_document(&self) -> bool;
fn get_local_name(&self) -> &<Self::Impl as SelectorImpl>::BorrowedLocalName;
/// Empty string for no namespace
fn get_namespace(&self) -> &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl;
fn attr_matches(&self,
ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>,
local_name: &<Self::Impl as SelectorImpl>::LocalName,
operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>)
-> bool;
fn match_non_ts_pseudo_class<F>(&self,
pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass,
context: &mut MatchingContext,
relevant_link: &RelevantLinkStatus,
flags_setter: &mut F) -> bool
where F: FnMut(&Self, ElementSelectorFlags);
fn match_pseudo_element(&self,
pe: &<Self::Impl as SelectorImpl>::PseudoElement,
context: &mut MatchingContext)
-> bool;
/// Whether this element is a `link`.
fn is_link(&self) -> bool;
fn get_id(&self) -> Option<<Self::Impl as SelectorImpl>::Identifier>;
fn has_class(&self, name: &<Self::Impl as SelectorImpl>::ClassName) -> bool;
/// Returns whether this element matches `:empty`.
///
/// That is, whether it does not contain any child element or any non-zero-length text node.
/// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo
fn is_empty(&self) -> bool;
/// Returns whether this element matches `:root`,
/// i.e. whether it is the root element of a document.
///
/// Note: this can be false even if `.parent_element()` is `None`
/// if the parent node is a `DocumentFragment`.
fn is_root(&self) -> bool;
}
| pseudo_element_originating_element | identifier_name |
websocket.rs |
use script_thread::Runnable;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::sync::Arc;
use std::thread;
use websocket::client::request::Url;
use websocket::header::{Headers, WebSocketProtocol};
use websocket::ws::util::url::parse_url;
#[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// list of bad ports according to
// https://fetch.spec.whatwg.org/#port-blocking
const BLOCKED_PORTS_LIST: &'static [u16] = &[
1, // tcpmux
7, // echo
9, // discard
11, // systat
13, // daytime
15, // netstat
17, // qotd
19, // chargen
20, // ftp-data
21, // ftp
22, // ssh
23, // telnet
25, // smtp
37, // time
42, // name
43, // nicname
53, // domain
77, // priv-rjs
79, // finger
87, // ttylink
95, // supdup
101, // hostriame
102, // iso-tsap
103, // gppitnp
104, // acr-nema
109, // pop2
110, // pop3
111, // sunrpc
113, // auth
115, // sftp
117, // uucp-path
119, // nntp
123, // ntp
135, // loc-srv / epmap
139, // netbios
143, // imap2
179, // bgp
389, // ldap
465, // smtp+ssl
512, // print / exec
513, // login
514, // shell
515, // printer
526, // tempo
530, // courier
531, // chat
532, // netnews
540, // uucp
556, // remotefs
563, // nntp+ssl
587, // smtp
601, // syslog-conn
636, // ldap+ssl
993, // imap+ssl
995, // pop3+ssl
2049, // nfs
3659, // apple-sasl
4045, // lockd
6000, // x11
6665, // irc (alternate)
6666, // irc (alternate)
6667, // irc (default)
6668, // irc (alternate)
6669, // irc (alternate)
];
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(address: Trusted<WebSocket>,
sender: Box<ScriptChan>,
code: Option<u16>,
reason: String) {
let close_task = box CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap();
}
pub fn fail_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>) {
let close_task = box CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_heap_size_of = "Defined in std"]
sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DOMRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: Url) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DOMRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DOMRefCell::new("".to_owned()),
}
}
fn new(global: GlobalRef, url: Url) -> Root<WebSocket> {
reflect_dom_object(box WebSocket::new_inherited(url),
global, WebSocketBinding::Wrap)
}
pub fn Constructor(global: GlobalRef,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<Root<WebSocket>> {
// Step 1.
let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax));
// Although we do this replace and parse operation again in the resource thread,
// we try here to be able to immediately throw a syntax error on failure.
let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax));
// Step 2: Disallow https -> ws connections.
// Step 3: Potentially block access to some ports.
let port: u16 = resource_url.port_or_known_default().unwrap(); | // Step 4.
let protocols = match protocols {
Some(StringOrStringSequence::String(string)) => vec![String::from(string)],
Some(StringOrStringSequence::StringSequence(sequence)) => {
sequence.into_iter().map(String::from).collect()
},
_ => Vec::new(),
};
// Step 5.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
// Step 6: Origin.
let origin = UrlHelper::Origin(&global.get_url()).0;
// Step 7.
let ws = WebSocket::new(global, resource_url.clone());
let address = Trusted::new(ws.r());
let connect_data = WebSocketConnectData {
resource_url: resource_url.clone(),
origin: origin,
protocols: protocols,
};
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
let connect = WebSocketCommunicate {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let moved_address = address.clone();
let sender = global.networking_task_source();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished(headers, protocols) => {
let open_thread = box ConnectionEstablishedTask {
address: moved_address.clone(),
headers: headers,
protocols: protocols,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = box MessageReceivedTask {
address: moved_address.clone(),
message: message,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_thread)).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(moved_address.clone(), sender.clone());
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(moved_address.clone(), sender.clone(), code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = box BufferedAmountTask {
address: address,
};
let global = self.global();
global.r().script_chan().send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_data().get_bytes().to_vec();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let sender = self.global().r().networking_task_source();
fail_the_websocket_connection(address, sender);
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocols: Vec<String>,
headers: Headers,
}
impl Runnable for ConnectionEstablishedTask {
fn handler(self: Box<Self>) {
let ws = self.address.root();
let global = ws.r().global();
// Step 1: Protocols.
if!self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() {
let sender = global.r().networking_task_source();
fail_the_websocket_connection(self.address, sender);
return;
}
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
//TODO: Set extensions to extensions in use
// Step 4: Protocols.
let protocol_in_use = unwrap_websocket_protocol(self.headers.get::<WebSocketProtocol>());
if let Some(protocol_name) = protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name.to_owned();
};
// Step 5: Cookies.
if let Some(cookies) = self.headers.get_raw("set-cookie") {
for cookie in cookies.iter() {
if let Ok(cookie_value) = String::from_utf8(cookie.clone()) {
let _ = ws.global().r().core_resource_thread().send(SetCookiesForUrl(ws.url.clone(),
cookie_value,
HTTP));
}
}
}
// Step 6.
ws.upcast().fire_simple_event("open");
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl Runnable for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn handler(self: Box<Self>) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl Runnable for CloseTask {
fn handler(self: Box<Self>) {
let ws = self.address.root();
let ws = ws.r();
let global = ws.global();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_simple_event("error");
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(global.r(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
|
if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) {
return Err(Error::Security);
}
| random_line_split |
websocket.rs | script_thread::Runnable;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::sync::Arc;
use std::thread;
use websocket::client::request::Url;
use websocket::header::{Headers, WebSocketProtocol};
use websocket::ws::util::url::parse_url;
#[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)]
enum | {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// list of bad ports according to
// https://fetch.spec.whatwg.org/#port-blocking
const BLOCKED_PORTS_LIST: &'static [u16] = &[
1, // tcpmux
7, // echo
9, // discard
11, // systat
13, // daytime
15, // netstat
17, // qotd
19, // chargen
20, // ftp-data
21, // ftp
22, // ssh
23, // telnet
25, // smtp
37, // time
42, // name
43, // nicname
53, // domain
77, // priv-rjs
79, // finger
87, // ttylink
95, // supdup
101, // hostriame
102, // iso-tsap
103, // gppitnp
104, // acr-nema
109, // pop2
110, // pop3
111, // sunrpc
113, // auth
115, // sftp
117, // uucp-path
119, // nntp
123, // ntp
135, // loc-srv / epmap
139, // netbios
143, // imap2
179, // bgp
389, // ldap
465, // smtp+ssl
512, // print / exec
513, // login
514, // shell
515, // printer
526, // tempo
530, // courier
531, // chat
532, // netnews
540, // uucp
556, // remotefs
563, // nntp+ssl
587, // smtp
601, // syslog-conn
636, // ldap+ssl
993, // imap+ssl
995, // pop3+ssl
2049, // nfs
3659, // apple-sasl
4045, // lockd
6000, // x11
6665, // irc (alternate)
6666, // irc (alternate)
6667, // irc (default)
6668, // irc (alternate)
6669, // irc (alternate)
];
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(address: Trusted<WebSocket>,
sender: Box<ScriptChan>,
code: Option<u16>,
reason: String) {
let close_task = box CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap();
}
pub fn fail_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>) {
let close_task = box CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_heap_size_of = "Defined in std"]
sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DOMRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: Url) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DOMRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DOMRefCell::new("".to_owned()),
}
}
fn new(global: GlobalRef, url: Url) -> Root<WebSocket> {
reflect_dom_object(box WebSocket::new_inherited(url),
global, WebSocketBinding::Wrap)
}
pub fn Constructor(global: GlobalRef,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<Root<WebSocket>> {
// Step 1.
let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax));
// Although we do this replace and parse operation again in the resource thread,
// we try here to be able to immediately throw a syntax error on failure.
let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax));
// Step 2: Disallow https -> ws connections.
// Step 3: Potentially block access to some ports.
let port: u16 = resource_url.port_or_known_default().unwrap();
if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) {
return Err(Error::Security);
}
// Step 4.
let protocols = match protocols {
Some(StringOrStringSequence::String(string)) => vec![String::from(string)],
Some(StringOrStringSequence::StringSequence(sequence)) => {
sequence.into_iter().map(String::from).collect()
},
_ => Vec::new(),
};
// Step 5.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
// Step 6: Origin.
let origin = UrlHelper::Origin(&global.get_url()).0;
// Step 7.
let ws = WebSocket::new(global, resource_url.clone());
let address = Trusted::new(ws.r());
let connect_data = WebSocketConnectData {
resource_url: resource_url.clone(),
origin: origin,
protocols: protocols,
};
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
let connect = WebSocketCommunicate {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let moved_address = address.clone();
let sender = global.networking_task_source();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished(headers, protocols) => {
let open_thread = box ConnectionEstablishedTask {
address: moved_address.clone(),
headers: headers,
protocols: protocols,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = box MessageReceivedTask {
address: moved_address.clone(),
message: message,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_thread)).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(moved_address.clone(), sender.clone());
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(moved_address.clone(), sender.clone(), code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = box BufferedAmountTask {
address: address,
};
let global = self.global();
global.r().script_chan().send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_data().get_bytes().to_vec();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let sender = self.global().r().networking_task_source();
fail_the_websocket_connection(address, sender);
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocols: Vec<String>,
headers: Headers,
}
impl Runnable for ConnectionEstablishedTask {
fn handler(self: Box<Self>) {
let ws = self.address.root();
let global = ws.r().global();
// Step 1: Protocols.
if!self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() {
let sender = global.r().networking_task_source();
fail_the_websocket_connection(self.address, sender);
return;
}
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
//TODO: Set extensions to extensions in use
// Step 4: Protocols.
let protocol_in_use = unwrap_websocket_protocol(self.headers.get::<WebSocketProtocol>());
if let Some(protocol_name) = protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name.to_owned();
};
// Step 5: Cookies.
if let Some(cookies) = self.headers.get_raw("set-cookie") {
for cookie in cookies.iter() {
if let Ok(cookie_value) = String::from_utf8(cookie.clone()) {
let _ = ws.global().r().core_resource_thread().send(SetCookiesForUrl(ws.url.clone(),
cookie_value,
HTTP));
}
}
}
// Step 6.
ws.upcast().fire_simple_event("open");
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl Runnable for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn handler(self: Box<Self>) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl Runnable for CloseTask {
fn handler(self: Box<Self>) {
let ws = self.address.root();
let ws = ws.r();
let global = ws.global();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_simple_event("error");
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(global.r(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
| WebSocketRequestState | identifier_name |
websocket.rs | script_thread::Runnable;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::ptr;
use std::sync::Arc;
use std::thread;
use websocket::client::request::Url;
use websocket::header::{Headers, WebSocketProtocol};
use websocket::ws::util::url::parse_url;
#[derive(JSTraceable, PartialEq, Copy, Clone, Debug, HeapSizeOf)]
enum WebSocketRequestState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
// list of bad ports according to
// https://fetch.spec.whatwg.org/#port-blocking
const BLOCKED_PORTS_LIST: &'static [u16] = &[
1, // tcpmux
7, // echo
9, // discard
11, // systat
13, // daytime
15, // netstat
17, // qotd
19, // chargen
20, // ftp-data
21, // ftp
22, // ssh
23, // telnet
25, // smtp
37, // time
42, // name
43, // nicname
53, // domain
77, // priv-rjs
79, // finger
87, // ttylink
95, // supdup
101, // hostriame
102, // iso-tsap
103, // gppitnp
104, // acr-nema
109, // pop2
110, // pop3
111, // sunrpc
113, // auth
115, // sftp
117, // uucp-path
119, // nntp
123, // ntp
135, // loc-srv / epmap
139, // netbios
143, // imap2
179, // bgp
389, // ldap
465, // smtp+ssl
512, // print / exec
513, // login
514, // shell
515, // printer
526, // tempo
530, // courier
531, // chat
532, // netnews
540, // uucp
556, // remotefs
563, // nntp+ssl
587, // smtp
601, // syslog-conn
636, // ldap+ssl
993, // imap+ssl
995, // pop3+ssl
2049, // nfs
3659, // apple-sasl
4045, // lockd
6000, // x11
6665, // irc (alternate)
6666, // irc (alternate)
6667, // irc (default)
6668, // irc (alternate)
6669, // irc (alternate)
];
// Close codes defined in https://tools.ietf.org/html/rfc6455#section-7.4.1
// Names are from https://github.com/mozilla/gecko-dev/blob/master/netwerk/protocol/websocket/nsIWebSocketChannel.idl
#[allow(dead_code)]
mod close_code {
pub const NORMAL: u16 = 1000;
pub const GOING_AWAY: u16 = 1001;
pub const PROTOCOL_ERROR: u16 = 1002;
pub const UNSUPPORTED_DATATYPE: u16 = 1003;
pub const NO_STATUS: u16 = 1005;
pub const ABNORMAL: u16 = 1006;
pub const INVALID_PAYLOAD: u16 = 1007;
pub const POLICY_VIOLATION: u16 = 1008;
pub const TOO_LARGE: u16 = 1009;
pub const EXTENSION_MISSING: u16 = 1010;
pub const INTERNAL_ERROR: u16 = 1011;
pub const TLS_FAILED: u16 = 1015;
}
pub fn close_the_websocket_connection(address: Trusted<WebSocket>,
sender: Box<ScriptChan>,
code: Option<u16>,
reason: String) {
let close_task = box CloseTask {
address: address,
failed: false,
code: code,
reason: Some(reason),
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap();
}
pub fn fail_the_websocket_connection(address: Trusted<WebSocket>, sender: Box<ScriptChan>) {
let close_task = box CloseTask {
address: address,
failed: true,
code: Some(close_code::ABNORMAL),
reason: None,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, close_task)).unwrap();
}
#[dom_struct]
pub struct WebSocket {
eventtarget: EventTarget,
url: Url,
ready_state: Cell<WebSocketRequestState>,
buffered_amount: Cell<u64>,
clearing_buffer: Cell<bool>, //Flag to tell if there is a running thread to clear buffered_amount
#[ignore_heap_size_of = "Defined in std"]
sender: DOMRefCell<Option<IpcSender<WebSocketDomAction>>>,
binary_type: Cell<BinaryType>,
protocol: DOMRefCell<String>, //Subprotocol selected by server
}
impl WebSocket {
fn new_inherited(url: Url) -> WebSocket {
WebSocket {
eventtarget: EventTarget::new_inherited(),
url: url,
ready_state: Cell::new(WebSocketRequestState::Connecting),
buffered_amount: Cell::new(0),
clearing_buffer: Cell::new(false),
sender: DOMRefCell::new(None),
binary_type: Cell::new(BinaryType::Blob),
protocol: DOMRefCell::new("".to_owned()),
}
}
fn new(global: GlobalRef, url: Url) -> Root<WebSocket> {
reflect_dom_object(box WebSocket::new_inherited(url),
global, WebSocketBinding::Wrap)
}
pub fn Constructor(global: GlobalRef,
url: DOMString,
protocols: Option<StringOrStringSequence>)
-> Fallible<Root<WebSocket>> {
// Step 1.
let resource_url = try!(Url::parse(&url).map_err(|_| Error::Syntax));
// Although we do this replace and parse operation again in the resource thread,
// we try here to be able to immediately throw a syntax error on failure.
let _ = try!(parse_url(&replace_hosts(&resource_url)).map_err(|_| Error::Syntax));
// Step 2: Disallow https -> ws connections.
// Step 3: Potentially block access to some ports.
let port: u16 = resource_url.port_or_known_default().unwrap();
if BLOCKED_PORTS_LIST.iter().any(|&p| p == port) {
return Err(Error::Security);
}
// Step 4.
let protocols = match protocols {
Some(StringOrStringSequence::String(string)) => vec![String::from(string)],
Some(StringOrStringSequence::StringSequence(sequence)) => {
sequence.into_iter().map(String::from).collect()
},
_ => Vec::new(),
};
// Step 5.
for (i, protocol) in protocols.iter().enumerate() {
// https://tools.ietf.org/html/rfc6455#section-4.1
// Handshake requirements, step 10
if protocols[i + 1..].iter().any(|p| p.eq_ignore_ascii_case(protocol)) {
return Err(Error::Syntax);
}
// https://tools.ietf.org/html/rfc6455#section-4.1
if!is_token(protocol.as_bytes()) {
return Err(Error::Syntax);
}
}
// Step 6: Origin.
let origin = UrlHelper::Origin(&global.get_url()).0;
// Step 7.
let ws = WebSocket::new(global, resource_url.clone());
let address = Trusted::new(ws.r());
let connect_data = WebSocketConnectData {
resource_url: resource_url.clone(),
origin: origin,
protocols: protocols,
};
// Create the interface for communication with the resource thread
let (dom_action_sender, resource_action_receiver):
(IpcSender<WebSocketDomAction>,
IpcReceiver<WebSocketDomAction>) = ipc::channel().unwrap();
let (resource_event_sender, dom_event_receiver):
(IpcSender<WebSocketNetworkEvent>,
IpcReceiver<WebSocketNetworkEvent>) = ipc::channel().unwrap();
let connect = WebSocketCommunicate {
event_sender: resource_event_sender,
action_receiver: resource_action_receiver,
};
let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data));
*ws.sender.borrow_mut() = Some(dom_action_sender);
let moved_address = address.clone();
let sender = global.networking_task_source();
thread::spawn(move || {
while let Ok(event) = dom_event_receiver.recv() {
match event {
WebSocketNetworkEvent::ConnectionEstablished(headers, protocols) => {
let open_thread = box ConnectionEstablishedTask {
address: moved_address.clone(),
headers: headers,
protocols: protocols,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = box MessageReceivedTask {
address: moved_address.clone(),
message: message,
};
sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, message_thread)).unwrap();
},
WebSocketNetworkEvent::Fail => {
fail_the_websocket_connection(moved_address.clone(), sender.clone());
},
WebSocketNetworkEvent::Close(code, reason) => {
close_the_websocket_connection(moved_address.clone(), sender.clone(), code, reason);
},
}
}
});
// Step 7.
Ok(ws)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn send_impl(&self, data_byte_len: u64) -> Fallible<bool> {
let return_after_buffer = match self.ready_state.get() {
WebSocketRequestState::Connecting => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.get()) {
None => panic!(),
Some(new_amount) => self.buffered_amount.set(new_amount)
};
if return_after_buffer {
return Ok(false);
}
if!self.clearing_buffer.get() && self.ready_state.get() == WebSocketRequestState::Open {
self.clearing_buffer.set(true);
let task = box BufferedAmountTask {
address: address,
};
let global = self.global();
global.r().script_chan().send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap();
}
Ok(true)
}
}
impl WebSocketMethods for WebSocket {
// https://html.spec.whatwg.org/multipage/#handler-websocket-onopen
event_handler!(open, GetOnopen, SetOnopen);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onclose
event_handler!(close, GetOnclose, SetOnclose);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onerror
event_handler!(error, GetOnerror, SetOnerror);
// https://html.spec.whatwg.org/multipage/#handler-websocket-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
// https://html.spec.whatwg.org/multipage/#dom-websocket-url
fn Url(&self) -> DOMString {
DOMString::from(self.url.as_str())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-readystate
fn ReadyState(&self) -> u16 {
self.ready_state.get() as u16
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
fn BufferedAmount(&self) -> u64 {
self.buffered_amount.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn BinaryType(&self) -> BinaryType {
self.binary_type.get()
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-binarytype
fn SetBinaryType(&self, btype: BinaryType) {
self.binary_type.set(btype)
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-protocol
fn Protocol(&self) -> DOMString {
DOMString::from(self.protocol.borrow().clone())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send(&self, data: USVString) -> ErrorResult |
// https://html.spec.whatwg.org/multipage/#dom-websocket-send
fn Send_(&self, blob: &Blob) -> ErrorResult {
/* As per https://html.spec.whatwg.org/multipage/#websocket
the buffered amount needs to be clamped to u32, even though Blob.Size() is u64
If the buffer limit is reached in the first place, there are likely other major problems
*/
let data_byte_len = blob.Size();
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let bytes = blob.get_data().get_bytes().to_vec();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Binary(bytes)));
}
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-websocket-close
fn Close(&self, code: Option<u16>, reason: Option<USVString>) -> ErrorResult {
if let Some(code) = code {
//Fail if the supplied code isn't normal and isn't reserved for libraries, frameworks, and applications
if code!= close_code::NORMAL && (code < 3000 || code > 4999) {
return Err(Error::InvalidAccess);
}
}
if let Some(ref reason) = reason {
if reason.0.as_bytes().len() > 123 { //reason cannot be larger than 123 bytes
return Err(Error::Syntax);
}
}
match self.ready_state.get() {
WebSocketRequestState::Closing | WebSocketRequestState::Closed => {} //Do nothing
WebSocketRequestState::Connecting => { //Connection is not yet established
/*By setting the state to closing, the open function
will abort connecting the websocket*/
self.ready_state.set(WebSocketRequestState::Closing);
let address = Trusted::new(self);
let sender = self.global().r().networking_task_source();
fail_the_websocket_connection(address, sender);
}
WebSocketRequestState::Open => {
self.ready_state.set(WebSocketRequestState::Closing);
// Kick off _Start the WebSocket Closing Handshake_
// https://tools.ietf.org/html/rfc6455#section-7.1.2
let reason = reason.map(|reason| reason.0);
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::Close(code, reason));
}
}
Ok(()) //Return Ok
}
}
/// Task queued when *the WebSocket connection is established*.
struct ConnectionEstablishedTask {
address: Trusted<WebSocket>,
protocols: Vec<String>,
headers: Headers,
}
impl Runnable for ConnectionEstablishedTask {
fn handler(self: Box<Self>) {
let ws = self.address.root();
let global = ws.r().global();
// Step 1: Protocols.
if!self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() {
let sender = global.r().networking_task_source();
fail_the_websocket_connection(self.address, sender);
return;
}
// Step 2.
ws.ready_state.set(WebSocketRequestState::Open);
// Step 3: Extensions.
//TODO: Set extensions to extensions in use
// Step 4: Protocols.
let protocol_in_use = unwrap_websocket_protocol(self.headers.get::<WebSocketProtocol>());
if let Some(protocol_name) = protocol_in_use {
*ws.protocol.borrow_mut() = protocol_name.to_owned();
};
// Step 5: Cookies.
if let Some(cookies) = self.headers.get_raw("set-cookie") {
for cookie in cookies.iter() {
if let Ok(cookie_value) = String::from_utf8(cookie.clone()) {
let _ = ws.global().r().core_resource_thread().send(SetCookiesForUrl(ws.url.clone(),
cookie_value,
HTTP));
}
}
}
// Step 6.
ws.upcast().fire_simple_event("open");
}
}
struct BufferedAmountTask {
address: Trusted<WebSocket>,
}
impl Runnable for BufferedAmountTask {
// See https://html.spec.whatwg.org/multipage/#dom-websocket-bufferedamount
//
// To be compliant with standards, we need to reset bufferedAmount only when the event loop
// reaches step 1. In our implementation, the bytes will already have been sent on a background
// thread.
fn handler(self: Box<Self>) {
let ws = self.address.root();
ws.buffered_amount.set(0);
ws.clearing_buffer.set(false);
}
}
struct CloseTask {
address: Trusted<WebSocket>,
failed: bool,
code: Option<u16>,
reason: Option<String>,
}
impl Runnable for CloseTask {
fn handler(self: Box<Self>) {
let ws = self.address.root();
let ws = ws.r();
let global = ws.global();
if ws.ready_state.get() == WebSocketRequestState::Closed {
// Do nothing if already closed.
return;
}
// Perform _the WebSocket connection is closed_ steps.
// https://html.spec.whatwg.org/multipage/#closeWebSocket
// Step 1.
ws.ready_state.set(WebSocketRequestState::Closed);
// Step 2.
if self.failed {
ws.upcast().fire_simple_event("error");
}
// Step 3.
let clean_close =!self.failed;
let code = self.code.unwrap_or(close_code::NO_STATUS);
let reason = DOMString::from(self.reason.unwrap_or("".to_owned()));
let close_event = CloseEvent::new(global.r(),
atom!("close"),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable,
clean_close,
| {
let data_byte_len = data.0.as_bytes().len() as u64;
let send_data = try!(self.send_impl(data_byte_len));
if send_data {
let mut other_sender = self.sender.borrow_mut();
let my_sender = other_sender.as_mut().unwrap();
let _ = my_sender.send(WebSocketDomAction::SendMessage(MessageData::Text(data.0)));
}
Ok(())
} | identifier_body |
else-if.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.
pub fn | () {
if 1i == 2 {
assert!((false));
} else if 2i == 3 {
assert!((false));
} else if 3i == 4 { assert!((false)); } else { assert!((true)); }
if 1i == 2 { assert!((false)); } else if 2i == 2 { assert!((true)); }
if 1i == 2 {
assert!((false));
} else if 2i == 2 {
if 1i == 1 {
assert!((true));
} else { if 2i == 1 { assert!((false)); } else { assert!((false)); } }
}
if 1i == 2 {
assert!((false));
} else { if 1i == 2 { assert!((false)); } else { assert!((true)); } }
}
| main | identifier_name |
else-if.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.
pub fn main() | {
if 1i == 2 {
assert!((false));
} else if 2i == 3 {
assert!((false));
} else if 3i == 4 { assert!((false)); } else { assert!((true)); }
if 1i == 2 { assert!((false)); } else if 2i == 2 { assert!((true)); }
if 1i == 2 {
assert!((false));
} else if 2i == 2 {
if 1i == 1 {
assert!((true));
} else { if 2i == 1 { assert!((false)); } else { assert!((false)); } }
}
if 1i == 2 {
assert!((false));
} else { if 1i == 2 { assert!((false)); } else { assert!((true)); } }
} | identifier_body |
|
else-if.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.
pub fn main() {
if 1i == 2 {
assert!((false));
} else if 2i == 3 {
assert!((false));
} else if 3i == 4 | else { assert!((true)); }
if 1i == 2 { assert!((false)); } else if 2i == 2 { assert!((true)); }
if 1i == 2 {
assert!((false));
} else if 2i == 2 {
if 1i == 1 {
assert!((true));
} else { if 2i == 1 { assert!((false)); } else { assert!((false)); } }
}
if 1i == 2 {
assert!((false));
} else { if 1i == 2 { assert!((false)); } else { assert!((true)); } }
}
| { assert!((false)); } | conditional_block |
else-if.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.
pub fn main() {
if 1i == 2 {
assert!((false));
} else if 2i == 3 {
assert!((false));
} else if 3i == 4 { assert!((false)); } else { assert!((true)); }
if 1i == 2 { assert!((false)); } else if 2i == 2 { assert!((true)); }
if 1i == 2 {
assert!((false));
} else if 2i == 2 {
if 1i == 1 {
assert!((true));
} else { if 2i == 1 { assert!((false)); } else { assert!((false)); } }
}
if 1i == 2 { | } else { if 1i == 2 { assert!((false)); } else { assert!((true)); } }
} | assert!((false)); | random_line_split |
time.rs | //! A module for time
use system::syscall::{sys_clock_gettime, CLOCK_REALTIME, CLOCK_MONOTONIC, TimeSpec};
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ops::{Add, Sub, Mul, Div};
const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// A duration type to represent a span of time, typically used for system
/// timeouts.
///
/// Each duration is composed of a number of seconds and nanosecond precision.
/// APIs binding a system timeout will typically round up the nanosecond
/// precision if the underlying system does not support that level of precision.
///
/// Durations implement many common traits, including `Add`, `Sub`, and other
/// ops traits. Currently a duration may only be inspected for its number of
/// seconds and its nanosecond precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
///
/// let ten_millis = Duration::from_millis(10);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct Duration {
secs: u64,
nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
}
impl Duration {
/// Creates a new `Duration` from the specified number of seconds and
/// additional nanosecond precision.
///
/// If the nanoseconds is greater than 1 billion (the number of nanoseconds
/// in a second), then it will carry over into the seconds provided.
pub fn new(secs: u64, nanos: u32) -> Duration {
let secs = secs + (nanos / NANOS_PER_SEC) as u64;
let nanos = nanos % NANOS_PER_SEC;
Duration { secs: secs, nanos: nanos }
}
/// Creates a new `Duration` from the specified number of seconds.
pub fn from_secs(secs: u64) -> Duration {
Duration { secs: secs, nanos: 0 }
}
/// Creates a new `Duration` from the specified number of milliseconds.
pub fn from_millis(millis: u64) -> Duration {
let secs = millis / MILLIS_PER_SEC;
let nanos = ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI;
Duration { secs: secs, nanos: nanos }
}
/// Returns the number of whole seconds represented by this duration.
///
/// The extra precision represented by this duration is ignored (e.g. extra
/// nanoseconds are not represented in the returned value).
pub fn as_secs(&self) -> u64 { self.secs }
/// Returns the nanosecond precision represented by this duration.
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
/// fractional portion of a second (e.g. it is less than one billion).
pub fn subsec_nanos(&self) -> u32 { self.nanos }
}
impl Add for Duration {
type Output = Duration;
fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_add(rhs.secs)
.expect("overflow when adding durations");
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs = secs.checked_add(1).expect("overflow when adding durations");
}
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Sub for Duration {
type Output = Duration;
fn sub(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_sub(rhs.secs)
.expect("overflow when subtracting durations");
let nanos = if self.nanos >= rhs.nanos | else {
secs = secs.checked_sub(1)
.expect("overflow when subtracting durations");
self.nanos + NANOS_PER_SEC - rhs.nanos
};
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Mul<u32> for Duration {
type Output = Duration;
fn mul(self, rhs: u32) -> Duration {
// Multiply nanoseconds as u64, because it cannot overflow that way.
let total_nanos = self.nanos as u64 * rhs as u64;
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
let secs = self.secs.checked_mul(rhs as u64)
.and_then(|s| s.checked_add(extra_secs))
.expect("overflow when multiplying duration");
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Div<u32> for Duration {
type Output = Duration;
fn div(self, rhs: u32) -> Duration {
let secs = self.secs / (rhs as u64);
let carry = self.secs - secs * (rhs as u64);
let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
let nanos = self.nanos / rhs + (extra_nanos as u32);
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
#[derive(Copy, Clone)]
pub struct Instant(Duration);
impl Instant {
/// Returns an instant corresponding to "now".
pub fn now() -> Instant {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_MONOTONIC, &mut tp).unwrap();
Instant(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
/// Returns the amount of time between two instants
pub fn duration_since(&self, earlier: Instant) -> Duration {
self.0 - earlier.0
}
/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
///
/// This function may panic if the current time is earlier than this
/// instant, which is something that can happen if an `Instant` is
/// produced synthetically.
pub fn elapsed(&self) -> Duration {
Instant::now().0 - self.0
}
}
#[derive(Copy, Clone)]
pub struct SystemTime(Duration);
impl SystemTime {
/// Returns the system time corresponding to "now".
pub fn now() -> SystemTime {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_REALTIME, &mut tp).unwrap();
SystemTime(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
}
| {
self.nanos - rhs.nanos
} | conditional_block |
time.rs | //! A module for time
use system::syscall::{sys_clock_gettime, CLOCK_REALTIME, CLOCK_MONOTONIC, TimeSpec};
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ops::{Add, Sub, Mul, Div};
const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// A duration type to represent a span of time, typically used for system
/// timeouts.
///
/// Each duration is composed of a number of seconds and nanosecond precision.
/// APIs binding a system timeout will typically round up the nanosecond
/// precision if the underlying system does not support that level of precision.
///
/// Durations implement many common traits, including `Add`, `Sub`, and other
/// ops traits. Currently a duration may only be inspected for its number of
/// seconds and its nanosecond precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
///
/// let ten_millis = Duration::from_millis(10);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct Duration {
secs: u64,
nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
}
impl Duration {
/// Creates a new `Duration` from the specified number of seconds and
/// additional nanosecond precision.
///
/// If the nanoseconds is greater than 1 billion (the number of nanoseconds
/// in a second), then it will carry over into the seconds provided.
pub fn new(secs: u64, nanos: u32) -> Duration {
let secs = secs + (nanos / NANOS_PER_SEC) as u64;
let nanos = nanos % NANOS_PER_SEC;
Duration { secs: secs, nanos: nanos }
}
/// Creates a new `Duration` from the specified number of seconds.
pub fn from_secs(secs: u64) -> Duration {
Duration { secs: secs, nanos: 0 }
}
/// Creates a new `Duration` from the specified number of milliseconds.
pub fn from_millis(millis: u64) -> Duration {
let secs = millis / MILLIS_PER_SEC;
let nanos = ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI;
Duration { secs: secs, nanos: nanos }
}
/// Returns the number of whole seconds represented by this duration.
///
/// The extra precision represented by this duration is ignored (e.g. extra
/// nanoseconds are not represented in the returned value).
pub fn as_secs(&self) -> u64 { self.secs }
/// Returns the nanosecond precision represented by this duration.
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
/// fractional portion of a second (e.g. it is less than one billion).
pub fn subsec_nanos(&self) -> u32 { self.nanos }
}
impl Add for Duration {
type Output = Duration;
fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_add(rhs.secs)
.expect("overflow when adding durations");
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs = secs.checked_add(1).expect("overflow when adding durations");
}
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Sub for Duration {
type Output = Duration;
fn sub(self, rhs: Duration) -> Duration |
}
impl Mul<u32> for Duration {
type Output = Duration;
fn mul(self, rhs: u32) -> Duration {
// Multiply nanoseconds as u64, because it cannot overflow that way.
let total_nanos = self.nanos as u64 * rhs as u64;
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
let secs = self.secs.checked_mul(rhs as u64)
.and_then(|s| s.checked_add(extra_secs))
.expect("overflow when multiplying duration");
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Div<u32> for Duration {
type Output = Duration;
fn div(self, rhs: u32) -> Duration {
let secs = self.secs / (rhs as u64);
let carry = self.secs - secs * (rhs as u64);
let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
let nanos = self.nanos / rhs + (extra_nanos as u32);
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
#[derive(Copy, Clone)]
pub struct Instant(Duration);
impl Instant {
/// Returns an instant corresponding to "now".
pub fn now() -> Instant {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_MONOTONIC, &mut tp).unwrap();
Instant(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
/// Returns the amount of time between two instants
pub fn duration_since(&self, earlier: Instant) -> Duration {
self.0 - earlier.0
}
/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
///
/// This function may panic if the current time is earlier than this
/// instant, which is something that can happen if an `Instant` is
/// produced synthetically.
pub fn elapsed(&self) -> Duration {
Instant::now().0 - self.0
}
}
#[derive(Copy, Clone)]
pub struct SystemTime(Duration);
impl SystemTime {
/// Returns the system time corresponding to "now".
pub fn now() -> SystemTime {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_REALTIME, &mut tp).unwrap();
SystemTime(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
}
| {
let mut secs = self.secs.checked_sub(rhs.secs)
.expect("overflow when subtracting durations");
let nanos = if self.nanos >= rhs.nanos {
self.nanos - rhs.nanos
} else {
secs = secs.checked_sub(1)
.expect("overflow when subtracting durations");
self.nanos + NANOS_PER_SEC - rhs.nanos
};
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
} | identifier_body |
time.rs | //! A module for time
use system::syscall::{sys_clock_gettime, CLOCK_REALTIME, CLOCK_MONOTONIC, TimeSpec};
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ops::{Add, Sub, Mul, Div};
const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// A duration type to represent a span of time, typically used for system
/// timeouts.
///
/// Each duration is composed of a number of seconds and nanosecond precision.
/// APIs binding a system timeout will typically round up the nanosecond
/// precision if the underlying system does not support that level of precision.
///
/// Durations implement many common traits, including `Add`, `Sub`, and other
/// ops traits. Currently a duration may only be inspected for its number of
/// seconds and its nanosecond precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
///
/// let ten_millis = Duration::from_millis(10);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct Duration {
secs: u64,
nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
}
impl Duration {
/// Creates a new `Duration` from the specified number of seconds and
/// additional nanosecond precision.
///
/// If the nanoseconds is greater than 1 billion (the number of nanoseconds
/// in a second), then it will carry over into the seconds provided.
pub fn new(secs: u64, nanos: u32) -> Duration {
let secs = secs + (nanos / NANOS_PER_SEC) as u64;
let nanos = nanos % NANOS_PER_SEC;
Duration { secs: secs, nanos: nanos }
}
/// Creates a new `Duration` from the specified number of seconds.
pub fn from_secs(secs: u64) -> Duration {
Duration { secs: secs, nanos: 0 }
}
/// Creates a new `Duration` from the specified number of milliseconds.
pub fn from_millis(millis: u64) -> Duration {
let secs = millis / MILLIS_PER_SEC;
let nanos = ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI;
Duration { secs: secs, nanos: nanos }
}
/// Returns the number of whole seconds represented by this duration.
///
/// The extra precision represented by this duration is ignored (e.g. extra
/// nanoseconds are not represented in the returned value).
pub fn as_secs(&self) -> u64 { self.secs }
/// Returns the nanosecond precision represented by this duration.
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
/// fractional portion of a second (e.g. it is less than one billion).
pub fn subsec_nanos(&self) -> u32 { self.nanos }
}
impl Add for Duration {
type Output = Duration;
fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_add(rhs.secs)
.expect("overflow when adding durations");
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs = secs.checked_add(1).expect("overflow when adding durations");
}
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Sub for Duration {
type Output = Duration;
fn sub(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_sub(rhs.secs)
.expect("overflow when subtracting durations");
let nanos = if self.nanos >= rhs.nanos {
self.nanos - rhs.nanos
} else {
secs = secs.checked_sub(1)
.expect("overflow when subtracting durations");
self.nanos + NANOS_PER_SEC - rhs.nanos
};
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Mul<u32> for Duration {
type Output = Duration;
fn mul(self, rhs: u32) -> Duration {
// Multiply nanoseconds as u64, because it cannot overflow that way.
let total_nanos = self.nanos as u64 * rhs as u64;
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
let secs = self.secs.checked_mul(rhs as u64)
.and_then(|s| s.checked_add(extra_secs))
.expect("overflow when multiplying duration");
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Div<u32> for Duration {
type Output = Duration;
fn div(self, rhs: u32) -> Duration {
let secs = self.secs / (rhs as u64);
let carry = self.secs - secs * (rhs as u64);
let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
let nanos = self.nanos / rhs + (extra_nanos as u32);
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
#[derive(Copy, Clone)]
pub struct Instant(Duration);
impl Instant {
/// Returns an instant corresponding to "now".
pub fn now() -> Instant {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_MONOTONIC, &mut tp).unwrap();
Instant(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
/// Returns the amount of time between two instants
pub fn duration_since(&self, earlier: Instant) -> Duration {
self.0 - earlier.0
}
/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
///
/// This function may panic if the current time is earlier than this | /// produced synthetically.
pub fn elapsed(&self) -> Duration {
Instant::now().0 - self.0
}
}
#[derive(Copy, Clone)]
pub struct SystemTime(Duration);
impl SystemTime {
/// Returns the system time corresponding to "now".
pub fn now() -> SystemTime {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_REALTIME, &mut tp).unwrap();
SystemTime(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
} | /// instant, which is something that can happen if an `Instant` is | random_line_split |
time.rs | //! A module for time
use system::syscall::{sys_clock_gettime, CLOCK_REALTIME, CLOCK_MONOTONIC, TimeSpec};
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ops::{Add, Sub, Mul, Div};
const NANOS_PER_SEC: u32 = 1_000_000_000;
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
/// A duration type to represent a span of time, typically used for system
/// timeouts.
///
/// Each duration is composed of a number of seconds and nanosecond precision.
/// APIs binding a system timeout will typically round up the nanosecond
/// precision if the underlying system does not support that level of precision.
///
/// Durations implement many common traits, including `Add`, `Sub`, and other
/// ops traits. Currently a duration may only be inspected for its number of
/// seconds and its nanosecond precision.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// let five_seconds = Duration::new(5, 0);
/// let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 5);
///
/// assert_eq!(five_seconds_and_five_nanos.as_secs(), 5);
/// assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 5);
///
/// let ten_millis = Duration::from_millis(10);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
pub struct Duration {
secs: u64,
nanos: u32, // Always 0 <= nanos < NANOS_PER_SEC
}
impl Duration {
/// Creates a new `Duration` from the specified number of seconds and
/// additional nanosecond precision.
///
/// If the nanoseconds is greater than 1 billion (the number of nanoseconds
/// in a second), then it will carry over into the seconds provided.
pub fn new(secs: u64, nanos: u32) -> Duration {
let secs = secs + (nanos / NANOS_PER_SEC) as u64;
let nanos = nanos % NANOS_PER_SEC;
Duration { secs: secs, nanos: nanos }
}
/// Creates a new `Duration` from the specified number of seconds.
pub fn from_secs(secs: u64) -> Duration {
Duration { secs: secs, nanos: 0 }
}
/// Creates a new `Duration` from the specified number of milliseconds.
pub fn from_millis(millis: u64) -> Duration {
let secs = millis / MILLIS_PER_SEC;
let nanos = ((millis % MILLIS_PER_SEC) as u32) * NANOS_PER_MILLI;
Duration { secs: secs, nanos: nanos }
}
/// Returns the number of whole seconds represented by this duration.
///
/// The extra precision represented by this duration is ignored (e.g. extra
/// nanoseconds are not represented in the returned value).
pub fn as_secs(&self) -> u64 { self.secs }
/// Returns the nanosecond precision represented by this duration.
///
/// This method does **not** return the length of the duration when
/// represented by nanoseconds. The returned number always represents a
/// fractional portion of a second (e.g. it is less than one billion).
pub fn subsec_nanos(&self) -> u32 { self.nanos }
}
impl Add for Duration {
type Output = Duration;
fn add(self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_add(rhs.secs)
.expect("overflow when adding durations");
let mut nanos = self.nanos + rhs.nanos;
if nanos >= NANOS_PER_SEC {
nanos -= NANOS_PER_SEC;
secs = secs.checked_add(1).expect("overflow when adding durations");
}
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Sub for Duration {
type Output = Duration;
fn | (self, rhs: Duration) -> Duration {
let mut secs = self.secs.checked_sub(rhs.secs)
.expect("overflow when subtracting durations");
let nanos = if self.nanos >= rhs.nanos {
self.nanos - rhs.nanos
} else {
secs = secs.checked_sub(1)
.expect("overflow when subtracting durations");
self.nanos + NANOS_PER_SEC - rhs.nanos
};
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Mul<u32> for Duration {
type Output = Duration;
fn mul(self, rhs: u32) -> Duration {
// Multiply nanoseconds as u64, because it cannot overflow that way.
let total_nanos = self.nanos as u64 * rhs as u64;
let extra_secs = total_nanos / (NANOS_PER_SEC as u64);
let nanos = (total_nanos % (NANOS_PER_SEC as u64)) as u32;
let secs = self.secs.checked_mul(rhs as u64)
.and_then(|s| s.checked_add(extra_secs))
.expect("overflow when multiplying duration");
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
impl Div<u32> for Duration {
type Output = Duration;
fn div(self, rhs: u32) -> Duration {
let secs = self.secs / (rhs as u64);
let carry = self.secs - secs * (rhs as u64);
let extra_nanos = carry * (NANOS_PER_SEC as u64) / (rhs as u64);
let nanos = self.nanos / rhs + (extra_nanos as u32);
debug_assert!(nanos < NANOS_PER_SEC);
Duration { secs: secs, nanos: nanos }
}
}
#[derive(Copy, Clone)]
pub struct Instant(Duration);
impl Instant {
/// Returns an instant corresponding to "now".
pub fn now() -> Instant {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_MONOTONIC, &mut tp).unwrap();
Instant(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
/// Returns the amount of time between two instants
pub fn duration_since(&self, earlier: Instant) -> Duration {
self.0 - earlier.0
}
/// Returns the amount of time elapsed since this instant was created.
///
/// # Panics
///
/// This function may panic if the current time is earlier than this
/// instant, which is something that can happen if an `Instant` is
/// produced synthetically.
pub fn elapsed(&self) -> Duration {
Instant::now().0 - self.0
}
}
#[derive(Copy, Clone)]
pub struct SystemTime(Duration);
impl SystemTime {
/// Returns the system time corresponding to "now".
pub fn now() -> SystemTime {
let mut tp = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
sys_clock_gettime(CLOCK_REALTIME, &mut tp).unwrap();
SystemTime(Duration::new(tp.tv_sec as u64, tp.tv_nsec as u32))
}
}
| sub | identifier_name |
list-user-pools.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_cognitoidentityprovider::{Client, Error, Region, PKG_VERSION};
use aws_smithy_types_convert::date_time::DateTimeExt;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Lists your user pools.
// snippet-start:[cognitoidentityprovider.rust.list-user-pools]
async fn show_pools(client: &Client) -> Result<(), Error> {
let response = client.list_user_pools().max_results(10).send().await?;
if let Some(pools) = response.user_pools() {
println!("User pools:");
for pool in pools {
println!(" ID: {}", pool.id().unwrap_or_default());
println!(" Name: {}", pool.name().unwrap_or_default());
println!(" Status: {:?}", pool.status());
println!(" Lambda Config: {:?}", pool.lambda_config().unwrap());
println!(
" Last modified: {}",
pool.last_modified_date().unwrap().to_chrono_utc()
);
println!(
" Creation date: {:?}",
pool.creation_date().unwrap().to_chrono_utc()
);
println!();
}
}
println!("Next token: {}", response.next_token().unwrap_or_default());
Ok(())
}
// snippet-end:[cognitoidentityprovider.rust.list-user-pools]
/// Lists your Amazon Cognito user pools in the Region.
/// # Arguments
///
/// * `[-r REGION]` - The region containing the buckets.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { region, verbose } = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_pools(&client).await
}
| {
println!("Cognito client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
} | conditional_block |
list-user-pools.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_cognitoidentityprovider::{Client, Error, Region, PKG_VERSION};
use aws_smithy_types_convert::date_time::DateTimeExt;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Lists your user pools.
// snippet-start:[cognitoidentityprovider.rust.list-user-pools]
async fn | (client: &Client) -> Result<(), Error> {
let response = client.list_user_pools().max_results(10).send().await?;
if let Some(pools) = response.user_pools() {
println!("User pools:");
for pool in pools {
println!(" ID: {}", pool.id().unwrap_or_default());
println!(" Name: {}", pool.name().unwrap_or_default());
println!(" Status: {:?}", pool.status());
println!(" Lambda Config: {:?}", pool.lambda_config().unwrap());
println!(
" Last modified: {}",
pool.last_modified_date().unwrap().to_chrono_utc()
);
println!(
" Creation date: {:?}",
pool.creation_date().unwrap().to_chrono_utc()
);
println!();
}
}
println!("Next token: {}", response.next_token().unwrap_or_default());
Ok(())
}
// snippet-end:[cognitoidentityprovider.rust.list-user-pools]
/// Lists your Amazon Cognito user pools in the Region.
/// # Arguments
///
/// * `[-r REGION]` - The region containing the buckets.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { region, verbose } = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("Cognito client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_pools(&client).await
}
| show_pools | identifier_name |
list-user-pools.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_cognitoidentityprovider::{Client, Error, Region, PKG_VERSION};
use aws_smithy_types_convert::date_time::DateTimeExt;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Lists your user pools.
// snippet-start:[cognitoidentityprovider.rust.list-user-pools]
async fn show_pools(client: &Client) -> Result<(), Error> {
let response = client.list_user_pools().max_results(10).send().await?;
if let Some(pools) = response.user_pools() {
println!("User pools:");
for pool in pools {
println!(" ID: {}", pool.id().unwrap_or_default());
println!(" Name: {}", pool.name().unwrap_or_default());
println!(" Status: {:?}", pool.status());
println!(" Lambda Config: {:?}", pool.lambda_config().unwrap());
println!( | pool.creation_date().unwrap().to_chrono_utc()
);
println!();
}
}
println!("Next token: {}", response.next_token().unwrap_or_default());
Ok(())
}
// snippet-end:[cognitoidentityprovider.rust.list-user-pools]
/// Lists your Amazon Cognito user pools in the Region.
/// # Arguments
///
/// * `[-r REGION]` - The region containing the buckets.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt { region, verbose } = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("Cognito client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_pools(&client).await
} | " Last modified: {}",
pool.last_modified_date().unwrap().to_chrono_utc()
);
println!(
" Creation date: {:?}", | random_line_split |
diagnostics.rs | // Copyright (c) 2014 Richard Diamond & contributors.
//
// This file is part of Rust Rocket.
//
// Rust Rocket 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.
//
// Rust Rocket is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>.
/*!
TODO designing this to:
1. facilitate embedding in IDEs, cmds, CI bots, etc,
2. connect rustc's diagnostic API to Rocket's, and
3. operate efficiently,
is turning out to be a prickly problem.
*/
use syntax::codemap::{BytePos, FileName, CodeMap, Span, mk_sp};
use syntax::diagnostic::EmitterWriter;
use std::cell::Cell;
use std::comm::{Sender, Receiver};
use std::collections::HashMap;
use std::default::Default;
use std::io::IoResult;
use std::str;
use std::sync::{Arc, mpsc_queue};
pub use rustc::driver::diagnostic::{Level, FatalError};
use rustc::driver::diagnostic::{Bug, Fatal, Error, Warning, Note,
RenderSpan, Emitter};
use address::Address;
use override::{Origin, SpanOrigin};
use super::address;
pub trait Driver {
fn fatal<M: Str>(&self, origin: Origin, msg: M) ->!;
fn err<M: Str>(&self, origin: Origin, msg: M);
fn warn<M: Str>(&self, origin: Origin, msg: M);
fn info<M: Str>(&self, origin: Origin, msg: M);
fn fail_if_errors(&self);
}
enum Message {
AddIfRef,
DropIfRef(Option<Sender<uint>>),
// the diag task will send when it has finished using the reference to the
// codemap.
DiagMessage(Address, String),
QueryErrorCountMessage(Address, Sender<uint>),
}
// TODO: This needs to be able send the various diags to their appropriate
// dest. For example, in terminal mode, messages are just sent to stdout,
// however in IDE mode messages should be sent to the IDE. Additionally for IDE,
// we will need to be able to handle managing multiple builds.
// To keep things initially simple, I'm just coding support for terminal mode.
struct Session {
ref_count: uint,
errors: HashMap<Address, uint>,
}
impl Session {
fn task(&mut self, port: Receiver<Message>) {
use syntax::diagnostic::{Error, Bug, Fatal,
Warning, Note};
'msg_loop: for msg in port.iter() {
match msg {
AddIfRef => {
self.ref_count += 1;
}
DropIfRef(ret) => {
self.ref_count -= 1;
match ret {
Some(ret) => ret.send(self.ref_count),
_ => (),
}
if self.ref_count == 0 {
break'msg_loop;
}
}
DiagMessage(addr, s) => {
println!("{}", s);
}
QueryErrorCountMessage(addr, ret) => {
let c = self.errors
.find(&addr)
.map(|&c| c )
.unwrap_or(0);
ret.send(c);
}
}
}
}
}
#[deriving(Clone, Eq, PartialEq)]
pub enum NestedOrigin {
RegEntry(Origin),
NestedEntry(Option<(Address, BytePos, BytePos)>, Option<Box<NestedOrigin>>),
}
impl NestedOrigin {
pub fn new(origin: Origin, cm: &CodeMap) -> NestedOrigin {
match origin {
SpanOrigin(mut sp) => |
_ => NestedEntry(None, None),
}
}
}
#[deriving(Clone)]
pub struct Emittion {
addr: Address,
// Note to Rocket devs: if SpanOrigin, the Span offsets must be normalized
// as if the offending file is the only member of the CodeMap. This is so we
// don't have to share or otherwise copy CodeMaps.
origin: NestedOrigin,
original_origin: Origin,
//lvl: Level,
}
type DiagQueue = Arc<mpsc_queue::Queue<Emittion>>;
#[deriving(Clone)]
pub struct SessionIf {
errors: Cell<uint>,
queue: DiagQueue,
}
impl SessionIf {
pub fn new() -> SessionIf {
SessionIf {
errors: Cell::new(0),
queue: Arc::new(mpsc_queue::Queue::new()),
}
}
// An expected failure.
pub fn fail(&self) ->! {
fail!(FatalError)
}
fn bump_error_count(&self) {
self.errors.set(self.errors.get() + 1);
}
pub fn errors(&self) -> uint {
self.errors.get()
}
}
impl Driver for SessionIf {
fn fatal<M: Str>(&self, origin: Origin, msg: M) ->! {
self.bump_error_count();
let addr = address().clone();
self.fail();
}
fn err<M: Str>(&self, origin: Origin, msg: M) {
}
fn warn<M: Str>(&self, origin: Origin, msg: M) {
}
fn info<M: Str>(&self, origin: Origin, msg: M) {
}
pub fn fail_if_errors(&self) {
if self.errors()!= 0 {
self.fail();
}
}
}
impl Emitter for SessionIf {
fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
}
fn custom_emit(&mut self, cm: &CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
}
}
| {
let filemap = cm.lookup_byte_offset(sp.lo).fm;
let addr = address()
.clone()
.with_source(Path::new(filemap.name));
unimplemented!();
let file_start = filemap.start_pos;
let new_sp = mk_sp(sp.lo - file_start,
sp.hi - file_start);
let nested = sp.expn_info
.map(|expn_info| {
box NestedOrigin::new(SpanOrigin(expn_info.call_site),
cm)
});
NestedEntry(Some((addr, new_sp.lo, new_sp.hi)), nested)
} | conditional_block |
diagnostics.rs | // Copyright (c) 2014 Richard Diamond & contributors.
//
// This file is part of Rust Rocket.
//
// Rust Rocket 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.
//
// Rust Rocket is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>.
/*!
TODO designing this to:
1. facilitate embedding in IDEs, cmds, CI bots, etc,
2. connect rustc's diagnostic API to Rocket's, and
3. operate efficiently,
is turning out to be a prickly problem.
*/
use syntax::codemap::{BytePos, FileName, CodeMap, Span, mk_sp};
use syntax::diagnostic::EmitterWriter;
use std::cell::Cell;
use std::comm::{Sender, Receiver};
use std::collections::HashMap;
use std::default::Default;
use std::io::IoResult;
use std::str;
use std::sync::{Arc, mpsc_queue};
pub use rustc::driver::diagnostic::{Level, FatalError};
use rustc::driver::diagnostic::{Bug, Fatal, Error, Warning, Note,
RenderSpan, Emitter};
use address::Address;
use override::{Origin, SpanOrigin};
use super::address;
pub trait Driver {
fn fatal<M: Str>(&self, origin: Origin, msg: M) ->!;
fn err<M: Str>(&self, origin: Origin, msg: M);
fn warn<M: Str>(&self, origin: Origin, msg: M);
fn info<M: Str>(&self, origin: Origin, msg: M);
fn fail_if_errors(&self);
}
enum Message {
AddIfRef,
DropIfRef(Option<Sender<uint>>),
// the diag task will send when it has finished using the reference to the
// codemap.
DiagMessage(Address, String),
QueryErrorCountMessage(Address, Sender<uint>),
}
// TODO: This needs to be able send the various diags to their appropriate
// dest. For example, in terminal mode, messages are just sent to stdout,
// however in IDE mode messages should be sent to the IDE. Additionally for IDE,
// we will need to be able to handle managing multiple builds.
// To keep things initially simple, I'm just coding support for terminal mode.
struct Session {
ref_count: uint,
errors: HashMap<Address, uint>,
}
impl Session {
fn task(&mut self, port: Receiver<Message>) {
use syntax::diagnostic::{Error, Bug, Fatal,
Warning, Note};
'msg_loop: for msg in port.iter() {
match msg {
AddIfRef => {
self.ref_count += 1;
}
DropIfRef(ret) => {
self.ref_count -= 1;
match ret {
Some(ret) => ret.send(self.ref_count),
_ => (),
}
if self.ref_count == 0 {
break'msg_loop;
}
}
DiagMessage(addr, s) => {
println!("{}", s);
}
QueryErrorCountMessage(addr, ret) => {
let c = self.errors
.find(&addr)
.map(|&c| c )
.unwrap_or(0);
ret.send(c);
}
}
}
}
}
#[deriving(Clone, Eq, PartialEq)]
pub enum NestedOrigin {
RegEntry(Origin),
NestedEntry(Option<(Address, BytePos, BytePos)>, Option<Box<NestedOrigin>>),
}
impl NestedOrigin {
pub fn new(origin: Origin, cm: &CodeMap) -> NestedOrigin {
match origin {
SpanOrigin(mut sp) => { | .clone()
.with_source(Path::new(filemap.name));
unimplemented!();
let file_start = filemap.start_pos;
let new_sp = mk_sp(sp.lo - file_start,
sp.hi - file_start);
let nested = sp.expn_info
.map(|expn_info| {
box NestedOrigin::new(SpanOrigin(expn_info.call_site),
cm)
});
NestedEntry(Some((addr, new_sp.lo, new_sp.hi)), nested)
}
_ => NestedEntry(None, None),
}
}
}
#[deriving(Clone)]
pub struct Emittion {
addr: Address,
// Note to Rocket devs: if SpanOrigin, the Span offsets must be normalized
// as if the offending file is the only member of the CodeMap. This is so we
// don't have to share or otherwise copy CodeMaps.
origin: NestedOrigin,
original_origin: Origin,
//lvl: Level,
}
type DiagQueue = Arc<mpsc_queue::Queue<Emittion>>;
#[deriving(Clone)]
pub struct SessionIf {
errors: Cell<uint>,
queue: DiagQueue,
}
impl SessionIf {
pub fn new() -> SessionIf {
SessionIf {
errors: Cell::new(0),
queue: Arc::new(mpsc_queue::Queue::new()),
}
}
// An expected failure.
pub fn fail(&self) ->! {
fail!(FatalError)
}
fn bump_error_count(&self) {
self.errors.set(self.errors.get() + 1);
}
pub fn errors(&self) -> uint {
self.errors.get()
}
}
impl Driver for SessionIf {
fn fatal<M: Str>(&self, origin: Origin, msg: M) ->! {
self.bump_error_count();
let addr = address().clone();
self.fail();
}
fn err<M: Str>(&self, origin: Origin, msg: M) {
}
fn warn<M: Str>(&self, origin: Origin, msg: M) {
}
fn info<M: Str>(&self, origin: Origin, msg: M) {
}
pub fn fail_if_errors(&self) {
if self.errors()!= 0 {
self.fail();
}
}
}
impl Emitter for SessionIf {
fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
}
fn custom_emit(&mut self, cm: &CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
}
} | let filemap = cm.lookup_byte_offset(sp.lo).fm;
let addr = address() | random_line_split |
diagnostics.rs | // Copyright (c) 2014 Richard Diamond & contributors.
//
// This file is part of Rust Rocket.
//
// Rust Rocket 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.
//
// Rust Rocket is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Rust Rocket. If not, see <http://www.gnu.org/licenses/>.
/*!
TODO designing this to:
1. facilitate embedding in IDEs, cmds, CI bots, etc,
2. connect rustc's diagnostic API to Rocket's, and
3. operate efficiently,
is turning out to be a prickly problem.
*/
use syntax::codemap::{BytePos, FileName, CodeMap, Span, mk_sp};
use syntax::diagnostic::EmitterWriter;
use std::cell::Cell;
use std::comm::{Sender, Receiver};
use std::collections::HashMap;
use std::default::Default;
use std::io::IoResult;
use std::str;
use std::sync::{Arc, mpsc_queue};
pub use rustc::driver::diagnostic::{Level, FatalError};
use rustc::driver::diagnostic::{Bug, Fatal, Error, Warning, Note,
RenderSpan, Emitter};
use address::Address;
use override::{Origin, SpanOrigin};
use super::address;
pub trait Driver {
fn fatal<M: Str>(&self, origin: Origin, msg: M) ->!;
fn err<M: Str>(&self, origin: Origin, msg: M);
fn warn<M: Str>(&self, origin: Origin, msg: M);
fn info<M: Str>(&self, origin: Origin, msg: M);
fn fail_if_errors(&self);
}
enum Message {
AddIfRef,
DropIfRef(Option<Sender<uint>>),
// the diag task will send when it has finished using the reference to the
// codemap.
DiagMessage(Address, String),
QueryErrorCountMessage(Address, Sender<uint>),
}
// TODO: This needs to be able send the various diags to their appropriate
// dest. For example, in terminal mode, messages are just sent to stdout,
// however in IDE mode messages should be sent to the IDE. Additionally for IDE,
// we will need to be able to handle managing multiple builds.
// To keep things initially simple, I'm just coding support for terminal mode.
struct Session {
ref_count: uint,
errors: HashMap<Address, uint>,
}
impl Session {
fn task(&mut self, port: Receiver<Message>) {
use syntax::diagnostic::{Error, Bug, Fatal,
Warning, Note};
'msg_loop: for msg in port.iter() {
match msg {
AddIfRef => {
self.ref_count += 1;
}
DropIfRef(ret) => {
self.ref_count -= 1;
match ret {
Some(ret) => ret.send(self.ref_count),
_ => (),
}
if self.ref_count == 0 {
break'msg_loop;
}
}
DiagMessage(addr, s) => {
println!("{}", s);
}
QueryErrorCountMessage(addr, ret) => {
let c = self.errors
.find(&addr)
.map(|&c| c )
.unwrap_or(0);
ret.send(c);
}
}
}
}
}
#[deriving(Clone, Eq, PartialEq)]
pub enum NestedOrigin {
RegEntry(Origin),
NestedEntry(Option<(Address, BytePos, BytePos)>, Option<Box<NestedOrigin>>),
}
impl NestedOrigin {
pub fn new(origin: Origin, cm: &CodeMap) -> NestedOrigin {
match origin {
SpanOrigin(mut sp) => {
let filemap = cm.lookup_byte_offset(sp.lo).fm;
let addr = address()
.clone()
.with_source(Path::new(filemap.name));
unimplemented!();
let file_start = filemap.start_pos;
let new_sp = mk_sp(sp.lo - file_start,
sp.hi - file_start);
let nested = sp.expn_info
.map(|expn_info| {
box NestedOrigin::new(SpanOrigin(expn_info.call_site),
cm)
});
NestedEntry(Some((addr, new_sp.lo, new_sp.hi)), nested)
}
_ => NestedEntry(None, None),
}
}
}
#[deriving(Clone)]
pub struct Emittion {
addr: Address,
// Note to Rocket devs: if SpanOrigin, the Span offsets must be normalized
// as if the offending file is the only member of the CodeMap. This is so we
// don't have to share or otherwise copy CodeMaps.
origin: NestedOrigin,
original_origin: Origin,
//lvl: Level,
}
type DiagQueue = Arc<mpsc_queue::Queue<Emittion>>;
#[deriving(Clone)]
pub struct SessionIf {
errors: Cell<uint>,
queue: DiagQueue,
}
impl SessionIf {
pub fn | () -> SessionIf {
SessionIf {
errors: Cell::new(0),
queue: Arc::new(mpsc_queue::Queue::new()),
}
}
// An expected failure.
pub fn fail(&self) ->! {
fail!(FatalError)
}
fn bump_error_count(&self) {
self.errors.set(self.errors.get() + 1);
}
pub fn errors(&self) -> uint {
self.errors.get()
}
}
impl Driver for SessionIf {
fn fatal<M: Str>(&self, origin: Origin, msg: M) ->! {
self.bump_error_count();
let addr = address().clone();
self.fail();
}
fn err<M: Str>(&self, origin: Origin, msg: M) {
}
fn warn<M: Str>(&self, origin: Origin, msg: M) {
}
fn info<M: Str>(&self, origin: Origin, msg: M) {
}
pub fn fail_if_errors(&self) {
if self.errors()!= 0 {
self.fail();
}
}
}
impl Emitter for SessionIf {
fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>,
msg: &str, code: Option<&str>, lvl: Level) {
}
fn custom_emit(&mut self, cm: &CodeMap,
sp: RenderSpan, msg: &str, lvl: Level) {
}
}
| new | identifier_name |
mod.rs | pub mod op;
use std::any::Any;
use std::fmt;
use std::fmt::{Display, Formatter};
use spv::Op;
use spv::ExtInst;
use spv::ExtInstSet;
use spv::raw::MemoryBlock;
use spv::raw::MemoryBlockResult;
use spv::raw::ReadError;
use self::op::*;
#[derive(Clone, Debug, PartialEq)]
pub enum Inst {
Sin(Sin),
Cos(Cos),
}
impl ExtInst for Inst {
fn get_op(&self) -> &Op {
match *self {
Inst::Sin(ref op) => op,
Inst::Cos(ref op) => op,
}
}
fn as_any(&self) -> &Any {
self
}
fn eq(&self, other: &ExtInst) -> bool {
match other.as_any().downcast_ref::<Inst>() {
Some(other_glsl450) => PartialEq::eq(self, other_glsl450),
None => false,
}
}
}
impl Display for Inst {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use self::Inst::*; | Sin(ref op) => op.fmt(f),
Cos(ref op) => op.fmt(f),
}
}
}
pub struct InstSet;
impl ExtInstSet for InstSet {
fn get_name(&self) -> &'static str {
"GLSL.std.450"
}
fn read_instruction<'a, 'b>(&'b self,
instruction: u32,
block: MemoryBlock<'a>)
-> MemoryBlockResult<'a, Box<ExtInst>> {
let (block, inst) = try!(match instruction {
13 => read_sin(block),
14 => read_cos(block),
_ => return Err(ReadError::UnknownExtInstOp(self.get_name(), instruction)),
});
Ok((block, Box::new(inst)))
}
fn duplicate(&self) -> Box<ExtInstSet> {
Box::new(InstSet)
}
}
fn read_sin<'a>(block: MemoryBlock<'a>) -> MemoryBlockResult<'a, Inst> {
let (block, x) = try!(block.read_op_id());
Ok((block, Inst::Sin(Sin { x: x })))
}
fn read_cos(block: MemoryBlock) -> MemoryBlockResult<Inst> {
let (block, x) = try!(block.read_op_id());
Ok((block, Inst::Cos(Cos { x: x })))
} | match *self { | random_line_split |
mod.rs |
pub mod op;
use std::any::Any;
use std::fmt;
use std::fmt::{Display, Formatter};
use spv::Op;
use spv::ExtInst;
use spv::ExtInstSet;
use spv::raw::MemoryBlock;
use spv::raw::MemoryBlockResult;
use spv::raw::ReadError;
use self::op::*;
#[derive(Clone, Debug, PartialEq)]
pub enum Inst {
Sin(Sin),
Cos(Cos),
}
impl ExtInst for Inst {
fn get_op(&self) -> &Op {
match *self {
Inst::Sin(ref op) => op,
Inst::Cos(ref op) => op,
}
}
fn as_any(&self) -> &Any {
self
}
fn eq(&self, other: &ExtInst) -> bool {
match other.as_any().downcast_ref::<Inst>() {
Some(other_glsl450) => PartialEq::eq(self, other_glsl450),
None => false,
}
}
}
impl Display for Inst {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use self::Inst::*;
match *self {
Sin(ref op) => op.fmt(f),
Cos(ref op) => op.fmt(f),
}
}
}
pub struct InstSet;
impl ExtInstSet for InstSet {
fn get_name(&self) -> &'static str {
"GLSL.std.450"
}
fn read_instruction<'a, 'b>(&'b self,
instruction: u32,
block: MemoryBlock<'a>)
-> MemoryBlockResult<'a, Box<ExtInst>> {
let (block, inst) = try!(match instruction {
13 => read_sin(block),
14 => read_cos(block),
_ => return Err(ReadError::UnknownExtInstOp(self.get_name(), instruction)),
});
Ok((block, Box::new(inst)))
}
fn duplicate(&self) -> Box<ExtInstSet> |
}
fn read_sin<'a>(block: MemoryBlock<'a>) -> MemoryBlockResult<'a, Inst> {
let (block, x) = try!(block.read_op_id());
Ok((block, Inst::Sin(Sin { x: x })))
}
fn read_cos(block: MemoryBlock) -> MemoryBlockResult<Inst> {
let (block, x) = try!(block.read_op_id());
Ok((block, Inst::Cos(Cos { x: x })))
}
| {
Box::new(InstSet)
} | identifier_body |
mod.rs |
pub mod op;
use std::any::Any;
use std::fmt;
use std::fmt::{Display, Formatter};
use spv::Op;
use spv::ExtInst;
use spv::ExtInstSet;
use spv::raw::MemoryBlock;
use spv::raw::MemoryBlockResult;
use spv::raw::ReadError;
use self::op::*;
#[derive(Clone, Debug, PartialEq)]
pub enum Inst {
Sin(Sin),
Cos(Cos),
}
impl ExtInst for Inst {
fn get_op(&self) -> &Op {
match *self {
Inst::Sin(ref op) => op,
Inst::Cos(ref op) => op,
}
}
fn as_any(&self) -> &Any {
self
}
fn eq(&self, other: &ExtInst) -> bool {
match other.as_any().downcast_ref::<Inst>() {
Some(other_glsl450) => PartialEq::eq(self, other_glsl450),
None => false,
}
}
}
impl Display for Inst {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use self::Inst::*;
match *self {
Sin(ref op) => op.fmt(f),
Cos(ref op) => op.fmt(f),
}
}
}
pub struct InstSet;
impl ExtInstSet for InstSet {
fn | (&self) -> &'static str {
"GLSL.std.450"
}
fn read_instruction<'a, 'b>(&'b self,
instruction: u32,
block: MemoryBlock<'a>)
-> MemoryBlockResult<'a, Box<ExtInst>> {
let (block, inst) = try!(match instruction {
13 => read_sin(block),
14 => read_cos(block),
_ => return Err(ReadError::UnknownExtInstOp(self.get_name(), instruction)),
});
Ok((block, Box::new(inst)))
}
fn duplicate(&self) -> Box<ExtInstSet> {
Box::new(InstSet)
}
}
fn read_sin<'a>(block: MemoryBlock<'a>) -> MemoryBlockResult<'a, Inst> {
let (block, x) = try!(block.read_op_id());
Ok((block, Inst::Sin(Sin { x: x })))
}
fn read_cos(block: MemoryBlock) -> MemoryBlockResult<Inst> {
let (block, x) = try!(block.read_op_id());
Ok((block, Inst::Cos(Cos { x: x })))
}
| get_name | identifier_name |
clock.rs | use std::time::{Duration, Instant};
use tokio_core::reactor::Handle;
use error::{Error, Result};
use component::Component;
use tokio_timer::Timer;
use futures::Stream;
use time;
/// A `Clock` that automatically determines the refresh rate.
///
/// This uses the default [strftime](http://man7.org/linux/man-pages/man3/strftime.3.html)
/// syntax for formatting.
pub struct Clock {
format: String,
refresh_rate: Duration,
}
impl Default for Clock {
/// Creates a `Clock` without any arguments.
///
/// This uses `%T` as the default time format.
/// [Read more](https://doc.rust-lang.org/core/default/trait.Default.html#tymethod.default)
fn default() -> Clock {
Clock {
format: "%T".into(),
refresh_rate: Duration::from_secs(1),
}
}
}
impl Clock {
/// Create a new `Clock` specifying the time format as argument.
///
/// # Errors
///
/// Returns `Err` if the specified `strftime` format could not be parsed.
pub fn new<T: Into<String>>(format: T) -> Result<Clock> {
let format = format.into();
let refresh_rate = get_refresh_rate(&format)?;
Ok(Clock {
format: format,
refresh_rate,
})
}
}
// Checks if seconds are part of the `strftime` format.
// If there are no seconds the refresh rate is one minute, otherwise it's one second.
fn get_refresh_rate(format: &str) -> Result<Duration> {
// Create a time with any non-zero second value
let mut time = time::now();
time.tm_sec = 15;
// Convert to String and back to Tm
let time_str = time::strftime(format, &time)
.map_err(|_| "Invalid clock format.")?;
let time = time::strptime(&time_str, format)
.map_err(|_| "Invalid clock format.")?;
// Check if seconds are still there
if time.tm_sec!= 0 | else {
Ok(Duration::from_secs(60))
}
}
impl Component for Clock {
type Error = Error;
type Stream = Box<Stream<Item = String, Error = Error>>;
fn stream(self, _: Handle) -> Self::Stream {
let timer = Timer::default();
let format = self.format.clone();
timer.interval_at(Instant::now(), self.refresh_rate).and_then(move |()| {
Ok(time::strftime(&format, &time::now()).unwrap())
}).map_err(|_| "timer error".into()).boxed()
}
}
| {
Ok(Duration::from_secs(1))
} | conditional_block |
clock.rs | use std::time::{Duration, Instant};
use tokio_core::reactor::Handle;
use error::{Error, Result};
use component::Component;
use tokio_timer::Timer;
use futures::Stream;
use time;
/// A `Clock` that automatically determines the refresh rate.
///
/// This uses the default [strftime](http://man7.org/linux/man-pages/man3/strftime.3.html)
/// syntax for formatting.
pub struct Clock {
format: String,
refresh_rate: Duration,
}
impl Default for Clock {
/// Creates a `Clock` without any arguments.
///
/// This uses `%T` as the default time format.
/// [Read more](https://doc.rust-lang.org/core/default/trait.Default.html#tymethod.default)
fn default() -> Clock {
Clock {
format: "%T".into(),
refresh_rate: Duration::from_secs(1),
}
}
}
impl Clock {
/// Create a new `Clock` specifying the time format as argument.
///
/// # Errors
///
/// Returns `Err` if the specified `strftime` format could not be parsed.
pub fn new<T: Into<String>>(format: T) -> Result<Clock> {
let format = format.into();
let refresh_rate = get_refresh_rate(&format)?;
Ok(Clock {
format: format,
refresh_rate,
})
}
}
// Checks if seconds are part of the `strftime` format.
// If there are no seconds the refresh rate is one minute, otherwise it's one second.
fn get_refresh_rate(format: &str) -> Result<Duration> {
// Create a time with any non-zero second value
let mut time = time::now();
time.tm_sec = 15;
// Convert to String and back to Tm
let time_str = time::strftime(format, &time)
.map_err(|_| "Invalid clock format.")?;
let time = time::strptime(&time_str, format)
.map_err(|_| "Invalid clock format.")?;
// Check if seconds are still there
if time.tm_sec!= 0 {
Ok(Duration::from_secs(1))
} else {
Ok(Duration::from_secs(60))
}
}
impl Component for Clock {
type Error = Error;
type Stream = Box<Stream<Item = String, Error = Error>>;
fn stream(self, _: Handle) -> Self::Stream {
let timer = Timer::default();
let format = self.format.clone();
timer.interval_at(Instant::now(), self.refresh_rate).and_then(move |()| {
Ok(time::strftime(&format, &time::now()).unwrap())
}).map_err(|_| "timer error".into()).boxed()
} | } | random_line_split |
|
clock.rs | use std::time::{Duration, Instant};
use tokio_core::reactor::Handle;
use error::{Error, Result};
use component::Component;
use tokio_timer::Timer;
use futures::Stream;
use time;
/// A `Clock` that automatically determines the refresh rate.
///
/// This uses the default [strftime](http://man7.org/linux/man-pages/man3/strftime.3.html)
/// syntax for formatting.
pub struct Clock {
format: String,
refresh_rate: Duration,
}
impl Default for Clock {
/// Creates a `Clock` without any arguments.
///
/// This uses `%T` as the default time format.
/// [Read more](https://doc.rust-lang.org/core/default/trait.Default.html#tymethod.default)
fn | () -> Clock {
Clock {
format: "%T".into(),
refresh_rate: Duration::from_secs(1),
}
}
}
impl Clock {
/// Create a new `Clock` specifying the time format as argument.
///
/// # Errors
///
/// Returns `Err` if the specified `strftime` format could not be parsed.
pub fn new<T: Into<String>>(format: T) -> Result<Clock> {
let format = format.into();
let refresh_rate = get_refresh_rate(&format)?;
Ok(Clock {
format: format,
refresh_rate,
})
}
}
// Checks if seconds are part of the `strftime` format.
// If there are no seconds the refresh rate is one minute, otherwise it's one second.
fn get_refresh_rate(format: &str) -> Result<Duration> {
// Create a time with any non-zero second value
let mut time = time::now();
time.tm_sec = 15;
// Convert to String and back to Tm
let time_str = time::strftime(format, &time)
.map_err(|_| "Invalid clock format.")?;
let time = time::strptime(&time_str, format)
.map_err(|_| "Invalid clock format.")?;
// Check if seconds are still there
if time.tm_sec!= 0 {
Ok(Duration::from_secs(1))
} else {
Ok(Duration::from_secs(60))
}
}
impl Component for Clock {
type Error = Error;
type Stream = Box<Stream<Item = String, Error = Error>>;
fn stream(self, _: Handle) -> Self::Stream {
let timer = Timer::default();
let format = self.format.clone();
timer.interval_at(Instant::now(), self.refresh_rate).and_then(move |()| {
Ok(time::strftime(&format, &time::now()).unwrap())
}).map_err(|_| "timer error".into()).boxed()
}
}
| default | identifier_name |
pkt_deserializer.rs | use std::io::Read;
use byteorder::{BigEndian, ReadBytesExt};
use serde::de;
use serde::de::Visitor;
use error::{Error, ResultE};
use super::osc_reader::OscReader;
use super::msg_visitor::MsgVisitor;
use super::bundle_visitor::BundleVisitor;
/// Deserializes an entire OSC packet or bundle element (they are syntactically identical).
/// An OSC packet consists of an `i32` indicating its length, followed by
/// the packet contents: EITHER a message OR a bundle.
///
/// This is designed to be symmetric with the [`serde_osc::ser::Serializer`] behavior,
/// so note that no "#bundle" string is emitted when decoding bundles;
/// bundles and messages are differentiated by the consumer based on whether the
/// first emitted piece of data is a String (the address of the message) or a
/// `(u32, u32)` sequence (the bundle time-tag).
///
/// See [`serde_osc::ser::Serializer`] for more info regarding valid
/// deserialization targets.
///
/// [`serde_osc::ser::Serializer`]:../ser/struct.Serializer.html
#[derive(Debug)]
pub struct PktDeserializer<'a, R: Read + 'a> {
reader: &'a mut R,
}
impl<'a, R> PktDeserializer<'a, R>
where R: Read + 'a
{
pub fn | (reader: &'a mut R) -> Self {
Self{ reader }
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut PktDeserializer<'a, R>
where R: Read + 'a
{
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> ResultE<V::Value>
where V: Visitor<'de>
{
// First, extract the length of the packet.
let length = self.reader.read_i32::<BigEndian>()?;
let mut reader = self.reader.take(length as u64);
// See if packet is a bundle or a message.
let address = reader.parse_str()?;
let result = match address.as_str() {
"#bundle" => visitor.visit_seq(BundleVisitor::new(&mut reader)),
_ => visitor.visit_seq(MsgVisitor::new(&mut reader, address)),
};
// If the consumer only handled a portion of the sequence, we still
// need to advance the reader so as to be ready for any next message.
// TODO: it should be possible to read any extra chars w/o allocating.
// Tracking: https://github.com/rust-lang/rust/issues/13989
let size = reader.limit() as usize;
let mut extra_chars = Vec::with_capacity(size);
extra_chars.resize(size, Default::default());
reader.read_exact(&mut extra_chars)?;
result
}
// This struct only deserializes sequences; ignore all type hints.
// More info: https://github.com/serde-rs/serde/blob/b7d6c5d9f7b3085a4d40a446eeb95976d2337e07/serde/src/macros.rs#L106
forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
}
}
| new | identifier_name |
pkt_deserializer.rs | use std::io::Read;
use byteorder::{BigEndian, ReadBytesExt};
use serde::de;
use serde::de::Visitor;
use error::{Error, ResultE};
use super::osc_reader::OscReader;
use super::msg_visitor::MsgVisitor;
use super::bundle_visitor::BundleVisitor;
/// Deserializes an entire OSC packet or bundle element (they are syntactically identical).
/// An OSC packet consists of an `i32` indicating its length, followed by
/// the packet contents: EITHER a message OR a bundle.
///
/// This is designed to be symmetric with the [`serde_osc::ser::Serializer`] behavior,
/// so note that no "#bundle" string is emitted when decoding bundles;
/// bundles and messages are differentiated by the consumer based on whether the
/// first emitted piece of data is a String (the address of the message) or a
/// `(u32, u32)` sequence (the bundle time-tag).
///
/// See [`serde_osc::ser::Serializer`] for more info regarding valid
/// deserialization targets.
///
/// [`serde_osc::ser::Serializer`]:../ser/struct.Serializer.html
#[derive(Debug)]
pub struct PktDeserializer<'a, R: Read + 'a> {
reader: &'a mut R,
}
| {
pub fn new(reader: &'a mut R) -> Self {
Self{ reader }
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut PktDeserializer<'a, R>
where R: Read + 'a
{
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> ResultE<V::Value>
where V: Visitor<'de>
{
// First, extract the length of the packet.
let length = self.reader.read_i32::<BigEndian>()?;
let mut reader = self.reader.take(length as u64);
// See if packet is a bundle or a message.
let address = reader.parse_str()?;
let result = match address.as_str() {
"#bundle" => visitor.visit_seq(BundleVisitor::new(&mut reader)),
_ => visitor.visit_seq(MsgVisitor::new(&mut reader, address)),
};
// If the consumer only handled a portion of the sequence, we still
// need to advance the reader so as to be ready for any next message.
// TODO: it should be possible to read any extra chars w/o allocating.
// Tracking: https://github.com/rust-lang/rust/issues/13989
let size = reader.limit() as usize;
let mut extra_chars = Vec::with_capacity(size);
extra_chars.resize(size, Default::default());
reader.read_exact(&mut extra_chars)?;
result
}
// This struct only deserializes sequences; ignore all type hints.
// More info: https://github.com/serde-rs/serde/blob/b7d6c5d9f7b3085a4d40a446eeb95976d2337e07/serde/src/macros.rs#L106
forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
}
} | impl<'a, R> PktDeserializer<'a, R>
where R: Read + 'a | random_line_split |
pkt_deserializer.rs | use std::io::Read;
use byteorder::{BigEndian, ReadBytesExt};
use serde::de;
use serde::de::Visitor;
use error::{Error, ResultE};
use super::osc_reader::OscReader;
use super::msg_visitor::MsgVisitor;
use super::bundle_visitor::BundleVisitor;
/// Deserializes an entire OSC packet or bundle element (they are syntactically identical).
/// An OSC packet consists of an `i32` indicating its length, followed by
/// the packet contents: EITHER a message OR a bundle.
///
/// This is designed to be symmetric with the [`serde_osc::ser::Serializer`] behavior,
/// so note that no "#bundle" string is emitted when decoding bundles;
/// bundles and messages are differentiated by the consumer based on whether the
/// first emitted piece of data is a String (the address of the message) or a
/// `(u32, u32)` sequence (the bundle time-tag).
///
/// See [`serde_osc::ser::Serializer`] for more info regarding valid
/// deserialization targets.
///
/// [`serde_osc::ser::Serializer`]:../ser/struct.Serializer.html
#[derive(Debug)]
pub struct PktDeserializer<'a, R: Read + 'a> {
reader: &'a mut R,
}
impl<'a, R> PktDeserializer<'a, R>
where R: Read + 'a
{
pub fn new(reader: &'a mut R) -> Self {
Self{ reader }
}
}
impl<'de, 'a, R> de::Deserializer<'de> for &'a mut PktDeserializer<'a, R>
where R: Read + 'a
{
type Error = Error;
fn deserialize_any<V>(self, visitor: V) -> ResultE<V::Value>
where V: Visitor<'de>
|
// This struct only deserializes sequences; ignore all type hints.
// More info: https://github.com/serde-rs/serde/blob/b7d6c5d9f7b3085a4d40a446eeb95976d2337e07/serde/src/macros.rs#L106
forward_to_deserialize_any! {
bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit option
seq bytes byte_buf map unit_struct newtype_struct
tuple_struct struct identifier tuple enum ignored_any
}
}
| {
// First, extract the length of the packet.
let length = self.reader.read_i32::<BigEndian>()?;
let mut reader = self.reader.take(length as u64);
// See if packet is a bundle or a message.
let address = reader.parse_str()?;
let result = match address.as_str() {
"#bundle" => visitor.visit_seq(BundleVisitor::new(&mut reader)),
_ => visitor.visit_seq(MsgVisitor::new(&mut reader, address)),
};
// If the consumer only handled a portion of the sequence, we still
// need to advance the reader so as to be ready for any next message.
// TODO: it should be possible to read any extra chars w/o allocating.
// Tracking: https://github.com/rust-lang/rust/issues/13989
let size = reader.limit() as usize;
let mut extra_chars = Vec::with_capacity(size);
extra_chars.resize(size, Default::default());
reader.read_exact(&mut extra_chars)?;
result
} | identifier_body |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Error, Result};
use tikv_util::codec;
use tikv_util::codec::number::{self, NumberEncoder};
/// Check if key in range [`start_key`, `end_key`).
#[allow(dead_code)]
pub fn check_key_in_range(
key: &[u8],
region_id: u64,
start_key: &[u8],
end_key: &[u8],
) -> Result<()> {
if key >= start_key && (end_key.is_empty() || key < end_key) {
Ok(())
} else {
Err(Error::NotInRange {
key: key.to_vec(),
region_id,
start: start_key.to_vec(),
end: end_key.to_vec(),
})
}
}
pub fn append_expire_ts(value: &mut Vec<u8>, expire_ts: u64) {
value.encode_u64(expire_ts).unwrap();
}
pub fn get_expire_ts(value_with_ttl: &[u8]) -> Result<u64> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
let mut ts = &value_with_ttl[len - number::U64_SIZE..];
Ok(number::decode_u64(&mut ts)?)
}
pub fn | (value_with_ttl: &[u8]) -> &[u8] {
let len = value_with_ttl.len();
&value_with_ttl[..len - number::U64_SIZE]
}
pub fn truncate_expire_ts(value_with_ttl: &mut Vec<u8>) -> Result<()> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
value_with_ttl.truncate(len - number::U64_SIZE);
Ok(())
}
| strip_expire_ts | identifier_name |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Error, Result};
use tikv_util::codec;
use tikv_util::codec::number::{self, NumberEncoder};
/// Check if key in range [`start_key`, `end_key`).
#[allow(dead_code)]
pub fn check_key_in_range(
key: &[u8],
region_id: u64,
start_key: &[u8],
end_key: &[u8],
) -> Result<()> {
if key >= start_key && (end_key.is_empty() || key < end_key) {
Ok(())
} else {
Err(Error::NotInRange {
key: key.to_vec(),
region_id,
start: start_key.to_vec(),
end: end_key.to_vec(),
})
}
} | pub fn get_expire_ts(value_with_ttl: &[u8]) -> Result<u64> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
let mut ts = &value_with_ttl[len - number::U64_SIZE..];
Ok(number::decode_u64(&mut ts)?)
}
pub fn strip_expire_ts(value_with_ttl: &[u8]) -> &[u8] {
let len = value_with_ttl.len();
&value_with_ttl[..len - number::U64_SIZE]
}
pub fn truncate_expire_ts(value_with_ttl: &mut Vec<u8>) -> Result<()> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
value_with_ttl.truncate(len - number::U64_SIZE);
Ok(())
} |
pub fn append_expire_ts(value: &mut Vec<u8>, expire_ts: u64) {
value.encode_u64(expire_ts).unwrap();
}
| random_line_split |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Error, Result};
use tikv_util::codec;
use tikv_util::codec::number::{self, NumberEncoder};
/// Check if key in range [`start_key`, `end_key`).
#[allow(dead_code)]
pub fn check_key_in_range(
key: &[u8],
region_id: u64,
start_key: &[u8],
end_key: &[u8],
) -> Result<()> {
if key >= start_key && (end_key.is_empty() || key < end_key) | else {
Err(Error::NotInRange {
key: key.to_vec(),
region_id,
start: start_key.to_vec(),
end: end_key.to_vec(),
})
}
}
pub fn append_expire_ts(value: &mut Vec<u8>, expire_ts: u64) {
value.encode_u64(expire_ts).unwrap();
}
pub fn get_expire_ts(value_with_ttl: &[u8]) -> Result<u64> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
let mut ts = &value_with_ttl[len - number::U64_SIZE..];
Ok(number::decode_u64(&mut ts)?)
}
pub fn strip_expire_ts(value_with_ttl: &[u8]) -> &[u8] {
let len = value_with_ttl.len();
&value_with_ttl[..len - number::U64_SIZE]
}
pub fn truncate_expire_ts(value_with_ttl: &mut Vec<u8>) -> Result<()> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
value_with_ttl.truncate(len - number::U64_SIZE);
Ok(())
}
| {
Ok(())
} | conditional_block |
util.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use super::{Error, Result};
use tikv_util::codec;
use tikv_util::codec::number::{self, NumberEncoder};
/// Check if key in range [`start_key`, `end_key`).
#[allow(dead_code)]
pub fn check_key_in_range(
key: &[u8],
region_id: u64,
start_key: &[u8],
end_key: &[u8],
) -> Result<()> {
if key >= start_key && (end_key.is_empty() || key < end_key) {
Ok(())
} else {
Err(Error::NotInRange {
key: key.to_vec(),
region_id,
start: start_key.to_vec(),
end: end_key.to_vec(),
})
}
}
pub fn append_expire_ts(value: &mut Vec<u8>, expire_ts: u64) |
pub fn get_expire_ts(value_with_ttl: &[u8]) -> Result<u64> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
let mut ts = &value_with_ttl[len - number::U64_SIZE..];
Ok(number::decode_u64(&mut ts)?)
}
pub fn strip_expire_ts(value_with_ttl: &[u8]) -> &[u8] {
let len = value_with_ttl.len();
&value_with_ttl[..len - number::U64_SIZE]
}
pub fn truncate_expire_ts(value_with_ttl: &mut Vec<u8>) -> Result<()> {
let len = value_with_ttl.len();
if len < number::U64_SIZE {
return Err(Error::Codec(codec::Error::ValueLength));
}
value_with_ttl.truncate(len - number::U64_SIZE);
Ok(())
}
| {
value.encode_u64(expire_ts).unwrap();
} | identifier_body |
mod.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
#[macro_use]
mod test_common;
mod transaction;
mod executive;
mod state;
mod chain;
mod homestead_state;
mod homestead_chain;
mod eip150_state;
mod eip161_state;
mod trie; | // GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
ip.rs | //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IPProtocol {
HOPOPT,
ICMP,
IGMP,
GGP,
IPINIP,
ST,
TCP,
CBT,
EGP,
IGP,
BBNRCCMON,
NVPII,
PUP,
ARGUS,
EMCON,
XNET,
CHAOS,
UDP,
IPV6,
ICMP6,
Other(u8),
}
impl From<u8> for IPProtocol {
fn from(raw: u8) -> Self | 41 => IPProtocol::IPV6,
58 => IPProtocol::ICMP6,
other => IPProtocol::Other(other),
}
}
}
pub(crate) fn two_nibbles(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(4u8),
bits::streaming::take(4u8),
))(input)
}
pub(crate) fn protocol(input: &[u8]) -> IResult<&[u8], IPProtocol> {
let (input, protocol) = number::streaming::be_u8(input)?;
Ok((input, protocol.into()))
}
| {
match raw {
0 => IPProtocol::HOPOPT,
1 => IPProtocol::ICMP,
2 => IPProtocol::IGMP,
3 => IPProtocol::GGP,
4 => IPProtocol::IPINIP,
5 => IPProtocol::ST,
6 => IPProtocol::TCP,
7 => IPProtocol::CBT,
8 => IPProtocol::EGP,
9 => IPProtocol::IGP,
10 => IPProtocol::BBNRCCMON,
11 => IPProtocol::NVPII,
12 => IPProtocol::PUP,
13 => IPProtocol::ARGUS,
14 => IPProtocol::EMCON,
15 => IPProtocol::XNET,
16 => IPProtocol::CHAOS,
17 => IPProtocol::UDP, | identifier_body |
ip.rs | //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IPProtocol {
HOPOPT,
ICMP,
IGMP,
GGP,
IPINIP,
ST,
TCP,
CBT,
EGP,
IGP,
BBNRCCMON,
NVPII,
PUP,
ARGUS,
EMCON,
XNET,
CHAOS,
UDP,
IPV6,
ICMP6,
Other(u8),
}
impl From<u8> for IPProtocol {
fn from(raw: u8) -> Self {
match raw {
0 => IPProtocol::HOPOPT,
1 => IPProtocol::ICMP,
2 => IPProtocol::IGMP,
3 => IPProtocol::GGP,
4 => IPProtocol::IPINIP,
5 => IPProtocol::ST,
6 => IPProtocol::TCP,
7 => IPProtocol::CBT,
8 => IPProtocol::EGP,
9 => IPProtocol::IGP,
10 => IPProtocol::BBNRCCMON,
11 => IPProtocol::NVPII,
12 => IPProtocol::PUP,
13 => IPProtocol::ARGUS,
14 => IPProtocol::EMCON,
15 => IPProtocol::XNET, | other => IPProtocol::Other(other),
}
}
}
pub(crate) fn two_nibbles(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(4u8),
bits::streaming::take(4u8),
))(input)
}
pub(crate) fn protocol(input: &[u8]) -> IResult<&[u8], IPProtocol> {
let (input, protocol) = number::streaming::be_u8(input)?;
Ok((input, protocol.into()))
} | 16 => IPProtocol::CHAOS,
17 => IPProtocol::UDP,
41 => IPProtocol::IPV6,
58 => IPProtocol::ICMP6, | random_line_split |
ip.rs | //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum | {
HOPOPT,
ICMP,
IGMP,
GGP,
IPINIP,
ST,
TCP,
CBT,
EGP,
IGP,
BBNRCCMON,
NVPII,
PUP,
ARGUS,
EMCON,
XNET,
CHAOS,
UDP,
IPV6,
ICMP6,
Other(u8),
}
impl From<u8> for IPProtocol {
fn from(raw: u8) -> Self {
match raw {
0 => IPProtocol::HOPOPT,
1 => IPProtocol::ICMP,
2 => IPProtocol::IGMP,
3 => IPProtocol::GGP,
4 => IPProtocol::IPINIP,
5 => IPProtocol::ST,
6 => IPProtocol::TCP,
7 => IPProtocol::CBT,
8 => IPProtocol::EGP,
9 => IPProtocol::IGP,
10 => IPProtocol::BBNRCCMON,
11 => IPProtocol::NVPII,
12 => IPProtocol::PUP,
13 => IPProtocol::ARGUS,
14 => IPProtocol::EMCON,
15 => IPProtocol::XNET,
16 => IPProtocol::CHAOS,
17 => IPProtocol::UDP,
41 => IPProtocol::IPV6,
58 => IPProtocol::ICMP6,
other => IPProtocol::Other(other),
}
}
}
pub(crate) fn two_nibbles(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(4u8),
bits::streaming::take(4u8),
))(input)
}
pub(crate) fn protocol(input: &[u8]) -> IResult<&[u8], IPProtocol> {
let (input, protocol) = number::streaming::be_u8(input)?;
Ok((input, protocol.into()))
}
| IPProtocol | identifier_name |
glb.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::combine::CombineFields;
use super::higher_ranked::HigherRankedRelations;
use super::InferCtxt;
use super::lattice::{self, LatticeDir};
use super::Subtype;
use middle::ty::{self, Ty};
use middle::ty_relate::{Relate, RelateResult, TypeRelation};
use util::ppaux::Repr;
/// "Greatest lower bound" (common subtype)
pub struct Glb<'a, 'tcx: 'a> {
fields: CombineFields<'a, 'tcx>
}
impl<'a, 'tcx> Glb<'a, 'tcx> {
pub fn new(fields: CombineFields<'a, 'tcx>) -> Glb<'a, 'tcx> {
Glb { fields: fields }
}
}
impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Glb<'a, 'tcx> {
fn tag(&self) -> &'static str { "Glb" }
fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.fields.tcx() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expected }
fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self,
variance: ty::Variance,
a: &T,
b: &T)
-> RelateResult<'tcx, T>
{
match variance {
ty::Invariant => self.fields.equate().relate(a, b),
ty::Covariant => self.relate(a, b),
ty::Bivariant => self.fields.bivariate().relate(a, b),
ty::Contravariant => self.fields.lub().relate(a, b),
}
}
fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> |
fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.fields.infcx.tcx),
b.repr(self.fields.infcx.tcx));
let origin = Subtype(self.fields.trace.clone());
Ok(self.fields.infcx.region_vars.glb_regions(origin, a, b))
}
fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
-> RelateResult<'tcx, ty::Binder<T>>
where T: Relate<'a, 'tcx>
{
self.fields.higher_ranked_glb(a, b)
}
}
impl<'a, 'tcx> LatticeDir<'a,'tcx> for Glb<'a, 'tcx> {
fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
self.fields.infcx
}
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
let mut sub = self.fields.sub();
try!(sub.relate(&v, &a));
try!(sub.relate(&v, &b));
Ok(())
}
}
| {
lattice::super_lattice_tys(self, a, b)
} | identifier_body |
glb.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | use super::combine::CombineFields;
use super::higher_ranked::HigherRankedRelations;
use super::InferCtxt;
use super::lattice::{self, LatticeDir};
use super::Subtype;
use middle::ty::{self, Ty};
use middle::ty_relate::{Relate, RelateResult, TypeRelation};
use util::ppaux::Repr;
/// "Greatest lower bound" (common subtype)
pub struct Glb<'a, 'tcx: 'a> {
fields: CombineFields<'a, 'tcx>
}
impl<'a, 'tcx> Glb<'a, 'tcx> {
pub fn new(fields: CombineFields<'a, 'tcx>) -> Glb<'a, 'tcx> {
Glb { fields: fields }
}
}
impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Glb<'a, 'tcx> {
fn tag(&self) -> &'static str { "Glb" }
fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.fields.tcx() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expected }
fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self,
variance: ty::Variance,
a: &T,
b: &T)
-> RelateResult<'tcx, T>
{
match variance {
ty::Invariant => self.fields.equate().relate(a, b),
ty::Covariant => self.relate(a, b),
ty::Bivariant => self.fields.bivariate().relate(a, b),
ty::Contravariant => self.fields.lub().relate(a, b),
}
}
fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
lattice::super_lattice_tys(self, a, b)
}
fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.fields.infcx.tcx),
b.repr(self.fields.infcx.tcx));
let origin = Subtype(self.fields.trace.clone());
Ok(self.fields.infcx.region_vars.glb_regions(origin, a, b))
}
fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
-> RelateResult<'tcx, ty::Binder<T>>
where T: Relate<'a, 'tcx>
{
self.fields.higher_ranked_glb(a, b)
}
}
impl<'a, 'tcx> LatticeDir<'a,'tcx> for Glb<'a, 'tcx> {
fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
self.fields.infcx
}
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
let mut sub = self.fields.sub();
try!(sub.relate(&v, &a));
try!(sub.relate(&v, &b));
Ok(())
}
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
glb.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use super::combine::CombineFields;
use super::higher_ranked::HigherRankedRelations;
use super::InferCtxt;
use super::lattice::{self, LatticeDir};
use super::Subtype;
use middle::ty::{self, Ty};
use middle::ty_relate::{Relate, RelateResult, TypeRelation};
use util::ppaux::Repr;
/// "Greatest lower bound" (common subtype)
pub struct Glb<'a, 'tcx: 'a> {
fields: CombineFields<'a, 'tcx>
}
impl<'a, 'tcx> Glb<'a, 'tcx> {
pub fn | (fields: CombineFields<'a, 'tcx>) -> Glb<'a, 'tcx> {
Glb { fields: fields }
}
}
impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Glb<'a, 'tcx> {
fn tag(&self) -> &'static str { "Glb" }
fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.fields.tcx() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expected }
fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self,
variance: ty::Variance,
a: &T,
b: &T)
-> RelateResult<'tcx, T>
{
match variance {
ty::Invariant => self.fields.equate().relate(a, b),
ty::Covariant => self.relate(a, b),
ty::Bivariant => self.fields.bivariate().relate(a, b),
ty::Contravariant => self.fields.lub().relate(a, b),
}
}
fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
lattice::super_lattice_tys(self, a, b)
}
fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.fields.infcx.tcx),
b.repr(self.fields.infcx.tcx));
let origin = Subtype(self.fields.trace.clone());
Ok(self.fields.infcx.region_vars.glb_regions(origin, a, b))
}
fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>)
-> RelateResult<'tcx, ty::Binder<T>>
where T: Relate<'a, 'tcx>
{
self.fields.higher_ranked_glb(a, b)
}
}
impl<'a, 'tcx> LatticeDir<'a,'tcx> for Glb<'a, 'tcx> {
fn infcx(&self) -> &'a InferCtxt<'a,'tcx> {
self.fields.infcx
}
fn relate_bound(&self, v: Ty<'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, ()> {
let mut sub = self.fields.sub();
try!(sub.relate(&v, &a));
try!(sub.relate(&v, &b));
Ok(())
}
}
| new | identifier_name |
text.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/. */
//! Generic types for text properties.
use app_units::Au;
use cssparser::Parser;
use parser::ParserContext;
use properties::animated_properties::Animatable;
use style_traits::ParseError;
use values::animated::ToAnimatedZero;
/// A generic value for the `initial-letter` property.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToComputedValue, ToCss)]
pub enum InitialLetter<Number, Integer> {
/// `normal`
Normal,
/// `<number> <integer>?`
Specified(Number, Option<Integer>),
}
impl<N, I> InitialLetter<N, I> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
InitialLetter::Normal
}
}
/// A generic spacing value for the `letter-spacing` and `word-spacing` properties.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToComputedValue, ToCss)]
pub enum Spacing<Value> { | /// `<value>`
Value(Value),
}
impl<Value> Spacing<Value> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
Spacing::Normal
}
/// Parses.
#[inline]
pub fn parse_with<'i, 't, F>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
parse: F)
-> Result<Self, ParseError<'i>>
where F: FnOnce(&ParserContext, &mut Parser<'i, 't>) -> Result<Value, ParseError<'i>>
{
if input.try(|i| i.expect_ident_matching("normal")).is_ok() {
return Ok(Spacing::Normal);
}
parse(context, input).map(Spacing::Value)
}
/// Returns the spacing value, if not `normal`.
#[inline]
pub fn value(&self) -> Option<&Value> {
match *self {
Spacing::Normal => None,
Spacing::Value(ref value) => Some(value),
}
}
}
impl<Value> Animatable for Spacing<Value>
where Value: Animatable + From<Au>,
{
#[inline]
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
if let (&Spacing::Normal, &Spacing::Normal) = (self, other) {
return Ok(Spacing::Normal);
}
let zero = Value::from(Au(0));
let this = self.value().unwrap_or(&zero);
let other = other.value().unwrap_or(&zero);
this.add_weighted(other, self_portion, other_portion).map(Spacing::Value)
}
#[inline]
fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
let zero = Value::from(Au(0));
let this = self.value().unwrap_or(&zero);
let other = other.value().unwrap_or(&zero);
this.compute_distance(other)
}
}
impl<V> ToAnimatedZero for Spacing<V>
where
V: From<Au>,
{
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) }
}
/// A generic value for the `line-height` property.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToCss)]
pub enum LineHeight<Number, LengthOrPercentage> {
/// `normal`
Normal,
/// `-moz-block-height`
#[cfg(feature = "gecko")]
MozBlockHeight,
/// `<number>`
Number(Number),
/// `<length-or-percentage>`
Length(LengthOrPercentage),
}
impl<N, L> LineHeight<N, L> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
LineHeight::Normal
}
} | /// `normal`
Normal, | random_line_split |
text.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/. */
//! Generic types for text properties.
use app_units::Au;
use cssparser::Parser;
use parser::ParserContext;
use properties::animated_properties::Animatable;
use style_traits::ParseError;
use values::animated::ToAnimatedZero;
/// A generic value for the `initial-letter` property.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToComputedValue, ToCss)]
pub enum InitialLetter<Number, Integer> {
/// `normal`
Normal,
/// `<number> <integer>?`
Specified(Number, Option<Integer>),
}
impl<N, I> InitialLetter<N, I> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
InitialLetter::Normal
}
}
/// A generic spacing value for the `letter-spacing` and `word-spacing` properties.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToComputedValue, ToCss)]
pub enum | <Value> {
/// `normal`
Normal,
/// `<value>`
Value(Value),
}
impl<Value> Spacing<Value> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
Spacing::Normal
}
/// Parses.
#[inline]
pub fn parse_with<'i, 't, F>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
parse: F)
-> Result<Self, ParseError<'i>>
where F: FnOnce(&ParserContext, &mut Parser<'i, 't>) -> Result<Value, ParseError<'i>>
{
if input.try(|i| i.expect_ident_matching("normal")).is_ok() {
return Ok(Spacing::Normal);
}
parse(context, input).map(Spacing::Value)
}
/// Returns the spacing value, if not `normal`.
#[inline]
pub fn value(&self) -> Option<&Value> {
match *self {
Spacing::Normal => None,
Spacing::Value(ref value) => Some(value),
}
}
}
impl<Value> Animatable for Spacing<Value>
where Value: Animatable + From<Au>,
{
#[inline]
fn add_weighted(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> {
if let (&Spacing::Normal, &Spacing::Normal) = (self, other) {
return Ok(Spacing::Normal);
}
let zero = Value::from(Au(0));
let this = self.value().unwrap_or(&zero);
let other = other.value().unwrap_or(&zero);
this.add_weighted(other, self_portion, other_portion).map(Spacing::Value)
}
#[inline]
fn compute_distance(&self, other: &Self) -> Result<f64, ()> {
let zero = Value::from(Au(0));
let this = self.value().unwrap_or(&zero);
let other = other.value().unwrap_or(&zero);
this.compute_distance(other)
}
}
impl<V> ToAnimatedZero for Spacing<V>
where
V: From<Au>,
{
#[inline]
fn to_animated_zero(&self) -> Result<Self, ()> { Err(()) }
}
/// A generic value for the `line-height` property.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, HasViewportPercentage, PartialEq, ToCss)]
pub enum LineHeight<Number, LengthOrPercentage> {
/// `normal`
Normal,
/// `-moz-block-height`
#[cfg(feature = "gecko")]
MozBlockHeight,
/// `<number>`
Number(Number),
/// `<length-or-percentage>`
Length(LengthOrPercentage),
}
impl<N, L> LineHeight<N, L> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
LineHeight::Normal
}
}
| Spacing | identifier_name |
instr_movntdqa.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn movntdqa_1() {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledIndexed(EBX, EDI, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 42, 20, 187], OperandSize::Dword)
}
#[test]
fn movntdqa_2() | {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(RBX, RSI, Two, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 42, 52, 115], OperandSize::Qword)
} | identifier_body |
|
instr_movntdqa.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledIndexed(EBX, EDI, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 42, 20, 187], OperandSize::Dword)
}
#[test]
fn movntdqa_2() {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(RBX, RSI, Two, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, 42, 52, 115], OperandSize::Qword)
}
| movntdqa_1 | identifier_name |
main.rs | extern crate term_mux;
extern crate termion;
extern crate chan_signal;
use std::io::{Read, Write, Result};
use std::fs::File;
use std::thread;
use std::time::Duration;
use termion::get_tty;
use termion::raw::IntoRawMode;
use chan_signal::{notify, Signal};
use term_mux::pty::Pty;
use term_mux::tui::{get_terminal_size, Size};
use term_mux::get_shell;
fn | () {
let signal = notify(&[Signal::WINCH]);
let mut tty_output = get_tty().unwrap().into_raw_mode().unwrap();
let mut tty_input = tty_output.try_clone().unwrap();
let pty_resize = Pty::spawn(&get_shell(), &get_terminal_size().unwrap()).unwrap();
let mut pty_output = pty_resize.try_clone().unwrap();
let mut pty_input = pty_output.try_clone().unwrap();
let handle = thread::spawn(move || {
loop {
match pipe(&mut pty_input, &mut tty_output) {
Err(_) => return,
_ => (),
}
}
});
thread::spawn(move || {
loop {
match pipe(&mut tty_input, &mut pty_output) {
Err(_) => return,
_ => (),
}
}
});
thread::spawn(move || {
loop {
signal.recv().unwrap();
pty_resize.resize(&get_terminal_size().unwrap());
}
});
handle.join();
}
/// Sends the content of input into output
fn pipe(input: &mut File, output: &mut File) -> Result<()> {
let mut packet = [0; 4096];
let count = input.read(&mut packet)?;
let read = &packet[..count];
output.write_all(&read)?;
output.flush()?;
Ok(())
}
| main | identifier_name |
main.rs | extern crate term_mux;
extern crate termion;
extern crate chan_signal;
use std::io::{Read, Write, Result};
use std::fs::File;
use std::thread;
use std::time::Duration;
use termion::get_tty;
use termion::raw::IntoRawMode;
use chan_signal::{notify, Signal};
use term_mux::pty::Pty;
use term_mux::tui::{get_terminal_size, Size};
use term_mux::get_shell;
fn main () | loop {
match pipe(&mut tty_input, &mut pty_output) {
Err(_) => return,
_ => (),
}
}
});
thread::spawn(move || {
loop {
signal.recv().unwrap();
pty_resize.resize(&get_terminal_size().unwrap());
}
});
handle.join();
}
/// Sends the content of input into output
fn pipe(input: &mut File, output: &mut File) -> Result<()> {
let mut packet = [0; 4096];
let count = input.read(&mut packet)?;
let read = &packet[..count];
output.write_all(&read)?;
output.flush()?;
Ok(())
}
| {
let signal = notify(&[Signal::WINCH]);
let mut tty_output = get_tty().unwrap().into_raw_mode().unwrap();
let mut tty_input = tty_output.try_clone().unwrap();
let pty_resize = Pty::spawn(&get_shell(), &get_terminal_size().unwrap()).unwrap();
let mut pty_output = pty_resize.try_clone().unwrap();
let mut pty_input = pty_output.try_clone().unwrap();
let handle = thread::spawn(move || {
loop {
match pipe(&mut pty_input, &mut tty_output) {
Err(_) => return,
_ => (),
}
}
});
thread::spawn(move || { | identifier_body |
main.rs | extern crate term_mux;
extern crate termion;
extern crate chan_signal;
use std::io::{Read, Write, Result};
use std::fs::File;
use std::thread;
use std::time::Duration;
use termion::get_tty;
use termion::raw::IntoRawMode;
use chan_signal::{notify, Signal};
use term_mux::pty::Pty;
use term_mux::tui::{get_terminal_size, Size};
use term_mux::get_shell;
fn main () {
let signal = notify(&[Signal::WINCH]);
let mut tty_output = get_tty().unwrap().into_raw_mode().unwrap();
let mut tty_input = tty_output.try_clone().unwrap();
let pty_resize = Pty::spawn(&get_shell(), &get_terminal_size().unwrap()).unwrap();
let mut pty_output = pty_resize.try_clone().unwrap();
let mut pty_input = pty_output.try_clone().unwrap();
let handle = thread::spawn(move || {
loop {
match pipe(&mut pty_input, &mut tty_output) {
Err(_) => return,
_ => (),
}
}
});
thread::spawn(move || {
loop {
match pipe(&mut tty_input, &mut pty_output) {
Err(_) => return,
_ => (),
}
}
});
thread::spawn(move || {
loop {
signal.recv().unwrap();
pty_resize.resize(&get_terminal_size().unwrap());
}
});
handle.join();
}
/// Sends the content of input into output | fn pipe(input: &mut File, output: &mut File) -> Result<()> {
let mut packet = [0; 4096];
let count = input.read(&mut packet)?;
let read = &packet[..count];
output.write_all(&read)?;
output.flush()?;
Ok(())
} | random_line_split |
|
instr_kshiftrd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kshiftrd_1() {
run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 203, 43], OperandSize::Dword)
}
#[test]
fn kshiftrd_2() | {
run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K2)), operand2: Some(Direct(K6)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 214, 43], OperandSize::Qword)
} | identifier_body |
|
instr_kshiftrd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kshiftrd_1() { | run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K2)), operand2: Some(Direct(K6)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 214, 43], OperandSize::Qword)
} | run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 203, 43], OperandSize::Dword)
}
#[test]
fn kshiftrd_2() { | random_line_split |
instr_kshiftrd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kshiftrd_1() {
run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K1)), operand2: Some(Direct(K3)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 203, 43], OperandSize::Dword)
}
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::KSHIFTRD, operand1: Some(Direct(K2)), operand2: Some(Direct(K6)), operand3: Some(Literal8(43)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 49, 214, 43], OperandSize::Qword)
}
| kshiftrd_2 | identifier_name |
transit.rs | #[derive(Debug, Clone)]
pub struct Transit {
period: f64,
base: f64,
depth: f64,
duration: f64,
decay: f64,
phase: f64,
}
impl Transit { | let k = (time/self.period).floor();
let t = time - k * self.period;
if t < self.phase {
self.base
} else if t < (self.phase + self.decay) {
let start = self.phase;
let f = (t - start) / self.decay;
self.base - f * self.depth
} else if t < (self.phase + self.decay + self.duration) {
self.base - self.depth
} else if t < (self.phase + self.decay + self.duration + self.decay) {
let start = self.phase + self.decay + self.duration;
let f = (t - start) / self.decay;
self.base - (1f64 - f) * self.depth
} else {
self.base
}
}
} | pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit {
Transit { period, base, depth, duration, decay, phase }
}
pub fn value(&self, time: &f64) -> f64 { | random_line_split |
transit.rs | #[derive(Debug, Clone)]
pub struct Transit {
period: f64,
base: f64,
depth: f64,
duration: f64,
decay: f64,
phase: f64,
}
impl Transit {
pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit {
Transit { period, base, depth, duration, decay, phase }
}
pub fn value(&self, time: &f64) -> f64 |
}
| {
let k = (time/self.period).floor();
let t = time - k * self.period;
if t < self.phase {
self.base
} else if t < (self.phase + self.decay) {
let start = self.phase;
let f = (t - start) / self.decay;
self.base - f * self.depth
} else if t < (self.phase + self.decay + self.duration) {
self.base - self.depth
} else if t < (self.phase + self.decay + self.duration + self.decay) {
let start = self.phase + self.decay + self.duration;
let f = (t - start) / self.decay;
self.base - (1f64 - f) * self.depth
} else {
self.base
}
} | identifier_body |
transit.rs | #[derive(Debug, Clone)]
pub struct | {
period: f64,
base: f64,
depth: f64,
duration: f64,
decay: f64,
phase: f64,
}
impl Transit {
pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit {
Transit { period, base, depth, duration, decay, phase }
}
pub fn value(&self, time: &f64) -> f64 {
let k = (time/self.period).floor();
let t = time - k * self.period;
if t < self.phase {
self.base
} else if t < (self.phase + self.decay) {
let start = self.phase;
let f = (t - start) / self.decay;
self.base - f * self.depth
} else if t < (self.phase + self.decay + self.duration) {
self.base - self.depth
} else if t < (self.phase + self.decay + self.duration + self.decay) {
let start = self.phase + self.decay + self.duration;
let f = (t - start) / self.decay;
self.base - (1f64 - f) * self.depth
} else {
self.base
}
}
}
| Transit | identifier_name |
transit.rs | #[derive(Debug, Clone)]
pub struct Transit {
period: f64,
base: f64,
depth: f64,
duration: f64,
decay: f64,
phase: f64,
}
impl Transit {
pub fn new((period, base, depth, duration, decay, phase): (f64,f64,f64,f64,f64,f64)) -> Transit {
Transit { period, base, depth, duration, decay, phase }
}
pub fn value(&self, time: &f64) -> f64 {
let k = (time/self.period).floor();
let t = time - k * self.period;
if t < self.phase | else if t < (self.phase + self.decay) {
let start = self.phase;
let f = (t - start) / self.decay;
self.base - f * self.depth
} else if t < (self.phase + self.decay + self.duration) {
self.base - self.depth
} else if t < (self.phase + self.decay + self.duration + self.decay) {
let start = self.phase + self.decay + self.duration;
let f = (t - start) / self.decay;
self.base - (1f64 - f) * self.depth
} else {
self.base
}
}
}
| {
self.base
} | conditional_block |
main.rs | use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
fn | () {
let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));
for i in 0..3{
let data = data.clone();
thread::spawn(move||{
let mut data = data.lock().unwrap();
data[i] += 1;
});
}
thread::sleep_ms(50);
let handle = thread::spawn(||{
println!("This is in a thread, not main");
thread::sleep_ms(5000);
"return from thread"
});
thread::sleep_ms(5000);
println!("{}",handle.join().unwrap());
thread::sleep_ms(5000);
println!("Hello, world, in main thread!");
println!("-------------------------------");
let (tx, rx) = mpsc::channel();
for _ in 0..10{
let tx = tx.clone();
thread::spawn(move ||{
let answer = 42u32;
tx.send(answer);
});
}
let mut receive = rx.recv().ok().expect("Could not receive answer");
println!("{}",receive);
}
| main | identifier_name |
main.rs | use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
fn main() | thread::sleep_ms(5000);
println!("{}",handle.join().unwrap());
thread::sleep_ms(5000);
println!("Hello, world, in main thread!");
println!("-------------------------------");
let (tx, rx) = mpsc::channel();
for _ in 0..10{
let tx = tx.clone();
thread::spawn(move ||{
let answer = 42u32;
tx.send(answer);
});
}
let mut receive = rx.recv().ok().expect("Could not receive answer");
println!("{}",receive);
}
| {
let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));
for i in 0..3{
let data = data.clone();
thread::spawn(move||{
let mut data = data.lock().unwrap();
data[i] += 1;
});
}
thread::sleep_ms(50);
let handle = thread::spawn(||{
println!("This is in a thread, not main");
thread::sleep_ms(5000);
"return from thread"
});
| identifier_body |
main.rs | use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc;
fn main() {
let data = Arc::new(Mutex::new(vec![1u32, 2, 3]));
for i in 0..3{
let data = data.clone();
thread::spawn(move||{
let mut data = data.lock().unwrap();
data[i] += 1; |
let handle = thread::spawn(||{
println!("This is in a thread, not main");
thread::sleep_ms(5000);
"return from thread"
});
thread::sleep_ms(5000);
println!("{}",handle.join().unwrap());
thread::sleep_ms(5000);
println!("Hello, world, in main thread!");
println!("-------------------------------");
let (tx, rx) = mpsc::channel();
for _ in 0..10{
let tx = tx.clone();
thread::spawn(move ||{
let answer = 42u32;
tx.send(answer);
});
}
let mut receive = rx.recv().ok().expect("Could not receive answer");
println!("{}",receive);
} | });
}
thread::sleep_ms(50); | random_line_split |
security.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use collections::HashSet;
use encryption_export::EncryptionConfig;
use grpcio::{ChannelCredentials, ChannelCredentialsBuilder};
use security::SecurityConfig;
pub fn new_security_cfg(cn: Option<HashSet<String>>) -> SecurityConfig {
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
SecurityConfig {
ca_path: format!("{}", p.join("data/ca.pem").display()),
cert_path: format!("{}", p.join("data/server.pem").display()),
key_path: format!("{}", p.join("data/key.pem").display()),
override_ssl_target: "".to_owned(),
cert_allowed_cn: cn.unwrap_or_default(),
encryption: EncryptionConfig::default(),
redact_info_log: Some(true),
}
}
pub fn new_channel_cred() -> ChannelCredentials {
let (ca, cert, key) = load_certs();
ChannelCredentialsBuilder::new()
.root_cert(ca.into())
.cert(cert.into(), key.into())
.build()
}
fn load_certs() -> (String, String, String) {
let mut cert = String::new();
let mut key = String::new();
let mut ca = String::new();
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
fs::File::open(format!("{}", p.join("data/server.pem").display()))
.unwrap() | .unwrap();
fs::File::open(format!("{}", p.join("data/key.pem").display()))
.unwrap()
.read_to_string(&mut key)
.unwrap();
fs::File::open(format!("{}", p.join("data/ca.pem").display()))
.unwrap()
.read_to_string(&mut ca)
.unwrap();
(ca, cert, key)
} | .read_to_string(&mut cert) | random_line_split |
security.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use collections::HashSet;
use encryption_export::EncryptionConfig;
use grpcio::{ChannelCredentials, ChannelCredentialsBuilder};
use security::SecurityConfig;
pub fn new_security_cfg(cn: Option<HashSet<String>>) -> SecurityConfig {
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
SecurityConfig {
ca_path: format!("{}", p.join("data/ca.pem").display()),
cert_path: format!("{}", p.join("data/server.pem").display()),
key_path: format!("{}", p.join("data/key.pem").display()),
override_ssl_target: "".to_owned(),
cert_allowed_cn: cn.unwrap_or_default(),
encryption: EncryptionConfig::default(),
redact_info_log: Some(true),
}
}
pub fn | () -> ChannelCredentials {
let (ca, cert, key) = load_certs();
ChannelCredentialsBuilder::new()
.root_cert(ca.into())
.cert(cert.into(), key.into())
.build()
}
fn load_certs() -> (String, String, String) {
let mut cert = String::new();
let mut key = String::new();
let mut ca = String::new();
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
fs::File::open(format!("{}", p.join("data/server.pem").display()))
.unwrap()
.read_to_string(&mut cert)
.unwrap();
fs::File::open(format!("{}", p.join("data/key.pem").display()))
.unwrap()
.read_to_string(&mut key)
.unwrap();
fs::File::open(format!("{}", p.join("data/ca.pem").display()))
.unwrap()
.read_to_string(&mut ca)
.unwrap();
(ca, cert, key)
}
| new_channel_cred | identifier_name |
security.rs | // Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0.
use std::fs;
use std::io::Read;
use std::path::PathBuf;
use collections::HashSet;
use encryption_export::EncryptionConfig;
use grpcio::{ChannelCredentials, ChannelCredentialsBuilder};
use security::SecurityConfig;
pub fn new_security_cfg(cn: Option<HashSet<String>>) -> SecurityConfig |
pub fn new_channel_cred() -> ChannelCredentials {
let (ca, cert, key) = load_certs();
ChannelCredentialsBuilder::new()
.root_cert(ca.into())
.cert(cert.into(), key.into())
.build()
}
fn load_certs() -> (String, String, String) {
let mut cert = String::new();
let mut key = String::new();
let mut ca = String::new();
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
fs::File::open(format!("{}", p.join("data/server.pem").display()))
.unwrap()
.read_to_string(&mut cert)
.unwrap();
fs::File::open(format!("{}", p.join("data/key.pem").display()))
.unwrap()
.read_to_string(&mut key)
.unwrap();
fs::File::open(format!("{}", p.join("data/ca.pem").display()))
.unwrap()
.read_to_string(&mut ca)
.unwrap();
(ca, cert, key)
}
| {
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
SecurityConfig {
ca_path: format!("{}", p.join("data/ca.pem").display()),
cert_path: format!("{}", p.join("data/server.pem").display()),
key_path: format!("{}", p.join("data/key.pem").display()),
override_ssl_target: "".to_owned(),
cert_allowed_cn: cn.unwrap_or_default(),
encryption: EncryptionConfig::default(),
redact_info_log: Some(true),
}
} | identifier_body |
echo.rs | #[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "echo";
#[test]
fn test_default() {
let (_, mut ucmd) = testing(UTIL_NAME);
assert_eq!(ucmd.run().stdout, "\n");
}
#[test]
fn test_no_trailing_newline() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-n")
.arg("hello_world");
assert_eq!(ucmd.run().stdout, "hello_world");
}
#[test]
fn test_enable_escapes() |
#[test]
fn test_disable_escapes() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-E")
.arg("\\b\\c\\e");
assert_eq!(ucmd.run().stdout, "\\b\\c\\e\n");
}
| {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-e")
.arg("\\\\\\t\\r");
assert_eq!(ucmd.run().stdout, "\\\t\r\n");
} | identifier_body |
echo.rs | #[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "echo";
#[test]
fn test_default() {
let (_, mut ucmd) = testing(UTIL_NAME);
assert_eq!(ucmd.run().stdout, "\n");
}
#[test]
fn test_no_trailing_newline() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-n")
.arg("hello_world");
assert_eq!(ucmd.run().stdout, "hello_world");
}
#[test]
fn test_enable_escapes() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-e")
.arg("\\\\\\t\\r");
assert_eq!(ucmd.run().stdout, "\\\t\r\n");
}
#[test]
fn | () {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-E")
.arg("\\b\\c\\e");
assert_eq!(ucmd.run().stdout, "\\b\\c\\e\n");
}
| test_disable_escapes | identifier_name |
echo.rs | #[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "echo";
#[test]
fn test_default() {
let (_, mut ucmd) = testing(UTIL_NAME); | }
#[test]
fn test_no_trailing_newline() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-n")
.arg("hello_world");
assert_eq!(ucmd.run().stdout, "hello_world");
}
#[test]
fn test_enable_escapes() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-e")
.arg("\\\\\\t\\r");
assert_eq!(ucmd.run().stdout, "\\\t\r\n");
}
#[test]
fn test_disable_escapes() {
let (_, mut ucmd) = testing(UTIL_NAME);
ucmd.arg("-E")
.arg("\\b\\c\\e");
assert_eq!(ucmd.run().stdout, "\\b\\c\\e\n");
} | assert_eq!(ucmd.run().stdout, "\n"); | random_line_split |
d2.rs | fn run(program: Vec<usize>) -> usize {
let mut arr = program.clone();
let mut i = 0;
loop {
let op = arr[i];
if op == 99 {
return arr[0];
} | let to = arr[i + 3];
if op == 1 {
arr[to] = arr[a] + arr[b]
} else if op == 2 {
arr[to] = arr[a] * arr[b]
}
i += 4
}
}
fn main() {
let program: Vec<usize> = include_str!("./input.txt")
.split(",")
.map(|i| i.parse::<usize>().unwrap())
.collect();
// p1
let mut p1 = program.clone();
p1[1] = 12;
p1[2] = 2;
println!("{}", run(p1));
// p2
for x in 0..100 {
for y in 0..100 {
let mut p2 = program.clone();
p2[1] = x;
p2[2] = y;
if run(p2) == 19690720 {
println!("{}", 100 * x + y)
}
}
}
} | let a = arr[i + 1];
let b = arr[i + 2]; | random_line_split |
d2.rs | fn run(program: Vec<usize>) -> usize {
let mut arr = program.clone();
let mut i = 0;
loop {
let op = arr[i];
if op == 99 {
return arr[0];
}
let a = arr[i + 1];
let b = arr[i + 2];
let to = arr[i + 3];
if op == 1 {
arr[to] = arr[a] + arr[b]
} else if op == 2 {
arr[to] = arr[a] * arr[b]
}
i += 4
}
}
fn main() {
let program: Vec<usize> = include_str!("./input.txt")
.split(",")
.map(|i| i.parse::<usize>().unwrap())
.collect();
// p1
let mut p1 = program.clone();
p1[1] = 12;
p1[2] = 2;
println!("{}", run(p1));
// p2
for x in 0..100 {
for y in 0..100 {
let mut p2 = program.clone();
p2[1] = x;
p2[2] = y;
if run(p2) == 19690720 |
}
}
}
| {
println!("{}", 100 * x + y)
} | conditional_block |
d2.rs | fn run(program: Vec<usize>) -> usize {
let mut arr = program.clone();
let mut i = 0;
loop {
let op = arr[i];
if op == 99 {
return arr[0];
}
let a = arr[i + 1];
let b = arr[i + 2];
let to = arr[i + 3];
if op == 1 {
arr[to] = arr[a] + arr[b]
} else if op == 2 {
arr[to] = arr[a] * arr[b]
}
i += 4
}
}
fn | () {
let program: Vec<usize> = include_str!("./input.txt")
.split(",")
.map(|i| i.parse::<usize>().unwrap())
.collect();
// p1
let mut p1 = program.clone();
p1[1] = 12;
p1[2] = 2;
println!("{}", run(p1));
// p2
for x in 0..100 {
for y in 0..100 {
let mut p2 = program.clone();
p2[1] = x;
p2[2] = y;
if run(p2) == 19690720 {
println!("{}", 100 * x + y)
}
}
}
}
| main | identifier_name |
d2.rs | fn run(program: Vec<usize>) -> usize {
let mut arr = program.clone();
let mut i = 0;
loop {
let op = arr[i];
if op == 99 {
return arr[0];
}
let a = arr[i + 1];
let b = arr[i + 2];
let to = arr[i + 3];
if op == 1 {
arr[to] = arr[a] + arr[b]
} else if op == 2 {
arr[to] = arr[a] * arr[b]
}
i += 4
}
}
fn main() | }
}
}
}
| {
let program: Vec<usize> = include_str!("./input.txt")
.split(",")
.map(|i| i.parse::<usize>().unwrap())
.collect();
// p1
let mut p1 = program.clone();
p1[1] = 12;
p1[2] = 2;
println!("{}", run(p1));
// p2
for x in 0..100 {
for y in 0..100 {
let mut p2 = program.clone();
p2[1] = x;
p2[2] = y;
if run(p2) == 19690720 {
println!("{}", 100 * x + y) | identifier_body |
returnck.rs | use dora_parser::ast::*;
use dora_parser::lexer::position::Position;
pub fn returns_value(s: &Stmt) -> Result<(), Position> {
match *s {
Stmt::Return(_) => Ok(()),
Stmt::For(ref stmt) => Err(stmt.pos),
Stmt::While(ref stmt) => Err(stmt.pos),
Stmt::Break(ref stmt) => Err(stmt.pos),
Stmt::Continue(ref stmt) => Err(stmt.pos),
Stmt::Let(ref stmt) => Err(stmt.pos),
Stmt::Expr(ref stmt) => expr_returns_value(&stmt.expr),
}
}
pub fn expr_returns_value(e: &Expr) -> Result<(), Position> {
match *e {
Expr::Block(ref block) => expr_block_returns_value(block),
Expr::If(ref expr) => expr_if_returns_value(expr),
_ => Err(e.pos()),
}
}
pub fn | (e: &ExprBlockType) -> Result<(), Position> {
let mut pos = e.pos;
for stmt in &e.stmts {
match returns_value(stmt) {
Ok(_) => return Ok(()),
Err(err_pos) => pos = err_pos,
}
}
if let Some(ref expr) = e.expr {
expr_returns_value(expr)
} else {
Err(pos)
}
}
fn expr_if_returns_value(e: &ExprIfType) -> Result<(), Position> {
expr_returns_value(&e.then_block)?;
match e.else_block {
Some(ref block) => expr_returns_value(block),
None => Err(e.pos),
}
}
#[cfg(test)]
mod tests {
use crate::language::error::msg::SemError;
use crate::language::tests::*;
#[test]
fn returns_unit() {
ok("fun f() {}");
ok("fun f() { if true { return; } }");
ok("fun f() { while true { return; } }");
}
#[test]
fn returns_int() {
err(
"fun f(): Int32 { }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { if true { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { if true { } else { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { while true { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
ok("fun f(): Int32 { if true { return 1; } else { return 2; } }");
ok("fun f(): Int32 { return 1; 1+2; }");
}
}
| expr_block_returns_value | identifier_name |
returnck.rs | use dora_parser::ast::*;
use dora_parser::lexer::position::Position;
pub fn returns_value(s: &Stmt) -> Result<(), Position> {
match *s {
Stmt::Return(_) => Ok(()),
Stmt::For(ref stmt) => Err(stmt.pos),
Stmt::While(ref stmt) => Err(stmt.pos),
Stmt::Break(ref stmt) => Err(stmt.pos),
Stmt::Continue(ref stmt) => Err(stmt.pos),
Stmt::Let(ref stmt) => Err(stmt.pos),
Stmt::Expr(ref stmt) => expr_returns_value(&stmt.expr),
}
}
pub fn expr_returns_value(e: &Expr) -> Result<(), Position> {
match *e {
Expr::Block(ref block) => expr_block_returns_value(block),
Expr::If(ref expr) => expr_if_returns_value(expr),
_ => Err(e.pos()),
}
}
pub fn expr_block_returns_value(e: &ExprBlockType) -> Result<(), Position> {
let mut pos = e.pos;
for stmt in &e.stmts {
match returns_value(stmt) {
Ok(_) => return Ok(()),
Err(err_pos) => pos = err_pos,
}
}
if let Some(ref expr) = e.expr {
expr_returns_value(expr)
} else {
Err(pos)
}
}
fn expr_if_returns_value(e: &ExprIfType) -> Result<(), Position> {
expr_returns_value(&e.then_block)?;
match e.else_block {
Some(ref block) => expr_returns_value(block),
None => Err(e.pos),
}
}
#[cfg(test)]
mod tests {
use crate::language::error::msg::SemError;
use crate::language::tests::*;
#[test]
fn returns_unit() {
ok("fun f() {}");
ok("fun f() { if true { return; } }");
ok("fun f() { while true { return; } }");
}
#[test] | "fun f(): Int32 { }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { if true { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { if true { } else { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { while true { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
ok("fun f(): Int32 { if true { return 1; } else { return 2; } }");
ok("fun f(): Int32 { return 1; 1+2; }");
}
} | fn returns_int() {
err( | random_line_split |
returnck.rs | use dora_parser::ast::*;
use dora_parser::lexer::position::Position;
pub fn returns_value(s: &Stmt) -> Result<(), Position> {
match *s {
Stmt::Return(_) => Ok(()),
Stmt::For(ref stmt) => Err(stmt.pos),
Stmt::While(ref stmt) => Err(stmt.pos),
Stmt::Break(ref stmt) => Err(stmt.pos),
Stmt::Continue(ref stmt) => Err(stmt.pos),
Stmt::Let(ref stmt) => Err(stmt.pos),
Stmt::Expr(ref stmt) => expr_returns_value(&stmt.expr),
}
}
pub fn expr_returns_value(e: &Expr) -> Result<(), Position> {
match *e {
Expr::Block(ref block) => expr_block_returns_value(block),
Expr::If(ref expr) => expr_if_returns_value(expr),
_ => Err(e.pos()),
}
}
pub fn expr_block_returns_value(e: &ExprBlockType) -> Result<(), Position> |
fn expr_if_returns_value(e: &ExprIfType) -> Result<(), Position> {
expr_returns_value(&e.then_block)?;
match e.else_block {
Some(ref block) => expr_returns_value(block),
None => Err(e.pos),
}
}
#[cfg(test)]
mod tests {
use crate::language::error::msg::SemError;
use crate::language::tests::*;
#[test]
fn returns_unit() {
ok("fun f() {}");
ok("fun f() { if true { return; } }");
ok("fun f() { while true { return; } }");
}
#[test]
fn returns_int() {
err(
"fun f(): Int32 { }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { if true { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { if true { } else { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
err(
"fun f(): Int32 { while true { return 1; } }",
pos(1, 16),
SemError::ReturnType("Int32".into(), "()".into()),
);
ok("fun f(): Int32 { if true { return 1; } else { return 2; } }");
ok("fun f(): Int32 { return 1; 1+2; }");
}
}
| {
let mut pos = e.pos;
for stmt in &e.stmts {
match returns_value(stmt) {
Ok(_) => return Ok(()),
Err(err_pos) => pos = err_pos,
}
}
if let Some(ref expr) = e.expr {
expr_returns_value(expr)
} else {
Err(pos)
}
} | identifier_body |
util.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 layout::box::Box;
use layout::construct::{ConstructionResult, NoConstructionResult};
use layout::wrapper::LayoutNode;
use extra::arc::Arc;
use script::dom::node::AbstractNode;
use servo_util::range::Range;
use servo_util::slot::{MutSlotRef, SlotRef};
use std::cast;
use std::iter::Enumerate;
use std::libc::uintptr_t;
use std::vec::VecIterator;
use style::{ComputedValues, PropertyDeclaration};
/// A range of nodes.
pub struct NodeRange {
node: OpaqueNode,
range: Range,
}
impl NodeRange {
pub fn new(node: OpaqueNode, range: &Range) -> NodeRange {
NodeRange {
node: node,
range: (*range).clone()
}
}
}
struct | {
priv entries: ~[NodeRange],
}
impl ElementMapping {
pub fn new() -> ElementMapping {
ElementMapping {
entries: ~[],
}
}
pub fn add_mapping(&mut self, node: OpaqueNode, range: &Range) {
self.entries.push(NodeRange::new(node, range))
}
pub fn each(&self, callback: &fn(nr: &NodeRange) -> bool) -> bool {
for nr in self.entries.iter() {
if!callback(nr) {
break
}
}
true
}
pub fn eachi<'a>(&'a self) -> Enumerate<VecIterator<'a, NodeRange>> {
self.entries.iter().enumerate()
}
pub fn repair_for_box_changes(&mut self, old_boxes: &[Box], new_boxes: &[Box]) {
let entries = &mut self.entries;
debug!("--- Old boxes: ---");
for (i, box) in old_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- New boxes: ---");
for (i, box) in new_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- Elem ranges before repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
let mut old_i = 0;
let mut new_j = 0;
struct WorkItem {
begin_idx: uint,
entry_idx: uint,
};
let mut repair_stack : ~[WorkItem] = ~[];
// index into entries
let mut entries_k = 0;
while old_i < old_boxes.len() {
debug!("repair_for_box_changes: Considering old box {:u}", old_i);
// possibly push several items
while entries_k < entries.len() && old_i == entries[entries_k].range.begin() {
let item = WorkItem {begin_idx: new_j, entry_idx: entries_k};
debug!("repair_for_box_changes: Push work item for elem {:u}: {:?}", entries_k, item);
repair_stack.push(item);
entries_k += 1;
}
while new_j < new_boxes.len() && old_boxes[old_i].node!= new_boxes[new_j].node {
debug!("repair_for_box_changes: Slide through new box {:u}", new_j);
new_j += 1;
}
old_i += 1;
// possibly pop several items
while repair_stack.len() > 0 && old_i == entries[repair_stack.last().entry_idx].range.end() {
let item = repair_stack.pop();
debug!("repair_for_box_changes: Set range for {:u} to {}",
item.entry_idx, Range::new(item.begin_idx, new_j - item.begin_idx));
entries[item.entry_idx].range = Range::new(item.begin_idx, new_j - item.begin_idx);
}
}
debug!("--- Elem ranges after repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
}
}
/// Data that layout associates with a node.
pub struct LayoutData {
/// The results of CSS matching for this node.
applicable_declarations: ~[Arc<~[PropertyDeclaration]>],
/// The results of CSS styling for this node.
style: Option<Arc<ComputedValues>>,
/// Description of how to account for recent style changes.
restyle_damage: Option<int>,
/// The current results of flow construction for this node. This is either a flow or a
/// `ConstructionItem`. See comments in `construct.rs` for more details.
flow_construction_result: ConstructionResult,
}
impl LayoutData {
/// Creates new layout data.
pub fn new() -> LayoutData {
LayoutData {
applicable_declarations: ~[],
style: None,
restyle_damage: None,
flow_construction_result: NoConstructionResult,
}
}
}
/// A trait that allows access to the layout data of a DOM node.
pub trait LayoutDataAccess {
/// Borrows the layout data without checks.
///
/// FIXME(pcwalton): Make safe.
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData>;
/// Borrows the layout data immutably. Fails on a conflicting borrow.
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>>;
/// Borrows the layout data mutably. Fails on a conflicting borrow.
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>>;
}
impl<'self> LayoutDataAccess for LayoutNode<'self> {
#[inline(always)]
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData> {
cast::transmute(self.get().layout_data.borrow_unchecked())
}
#[inline(always)]
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.borrow())
}
}
#[inline(always)]
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.mutate())
}
}
}
/// An opaque handle to a node. The only safe operation that can be performed on this node is to
/// compare it to another opaque handle or to another node.
///
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[deriving(Clone, Eq)]
pub struct OpaqueNode(uintptr_t);
impl OpaqueNode {
/// Converts a DOM node (layout view) to an `OpaqueNode`.
pub fn from_layout_node(node: &LayoutNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Converts a DOM node (script view) to an `OpaqueNode`.
pub fn from_script_node(node: &AbstractNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Unsafely converts an `OpaqueNode` to a DOM node (script view). Use this only if you
/// absolutely know what you're doing.
pub unsafe fn to_script_node(&self) -> AbstractNode {
cast::transmute(**self)
}
/// Returns the address of this node, for debugging purposes.
pub fn id(&self) -> uintptr_t {
unsafe {
cast::transmute_copy(self)
}
}
}
| ElementMapping | identifier_name |
util.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 layout::box::Box;
use layout::construct::{ConstructionResult, NoConstructionResult};
use layout::wrapper::LayoutNode;
use extra::arc::Arc;
use script::dom::node::AbstractNode;
use servo_util::range::Range;
use servo_util::slot::{MutSlotRef, SlotRef};
use std::cast;
use std::iter::Enumerate;
use std::libc::uintptr_t;
use std::vec::VecIterator;
use style::{ComputedValues, PropertyDeclaration};
/// A range of nodes.
pub struct NodeRange {
node: OpaqueNode,
range: Range,
}
impl NodeRange {
pub fn new(node: OpaqueNode, range: &Range) -> NodeRange {
NodeRange {
node: node,
range: (*range).clone()
}
}
}
struct ElementMapping {
priv entries: ~[NodeRange],
}
impl ElementMapping {
pub fn new() -> ElementMapping {
ElementMapping {
entries: ~[],
}
}
pub fn add_mapping(&mut self, node: OpaqueNode, range: &Range) {
self.entries.push(NodeRange::new(node, range))
}
pub fn each(&self, callback: &fn(nr: &NodeRange) -> bool) -> bool {
for nr in self.entries.iter() {
if!callback(nr) |
}
true
}
pub fn eachi<'a>(&'a self) -> Enumerate<VecIterator<'a, NodeRange>> {
self.entries.iter().enumerate()
}
pub fn repair_for_box_changes(&mut self, old_boxes: &[Box], new_boxes: &[Box]) {
let entries = &mut self.entries;
debug!("--- Old boxes: ---");
for (i, box) in old_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- New boxes: ---");
for (i, box) in new_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- Elem ranges before repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
let mut old_i = 0;
let mut new_j = 0;
struct WorkItem {
begin_idx: uint,
entry_idx: uint,
};
let mut repair_stack : ~[WorkItem] = ~[];
// index into entries
let mut entries_k = 0;
while old_i < old_boxes.len() {
debug!("repair_for_box_changes: Considering old box {:u}", old_i);
// possibly push several items
while entries_k < entries.len() && old_i == entries[entries_k].range.begin() {
let item = WorkItem {begin_idx: new_j, entry_idx: entries_k};
debug!("repair_for_box_changes: Push work item for elem {:u}: {:?}", entries_k, item);
repair_stack.push(item);
entries_k += 1;
}
while new_j < new_boxes.len() && old_boxes[old_i].node!= new_boxes[new_j].node {
debug!("repair_for_box_changes: Slide through new box {:u}", new_j);
new_j += 1;
}
old_i += 1;
// possibly pop several items
while repair_stack.len() > 0 && old_i == entries[repair_stack.last().entry_idx].range.end() {
let item = repair_stack.pop();
debug!("repair_for_box_changes: Set range for {:u} to {}",
item.entry_idx, Range::new(item.begin_idx, new_j - item.begin_idx));
entries[item.entry_idx].range = Range::new(item.begin_idx, new_j - item.begin_idx);
}
}
debug!("--- Elem ranges after repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
}
}
/// Data that layout associates with a node.
pub struct LayoutData {
/// The results of CSS matching for this node.
applicable_declarations: ~[Arc<~[PropertyDeclaration]>],
/// The results of CSS styling for this node.
style: Option<Arc<ComputedValues>>,
/// Description of how to account for recent style changes.
restyle_damage: Option<int>,
/// The current results of flow construction for this node. This is either a flow or a
/// `ConstructionItem`. See comments in `construct.rs` for more details.
flow_construction_result: ConstructionResult,
}
impl LayoutData {
/// Creates new layout data.
pub fn new() -> LayoutData {
LayoutData {
applicable_declarations: ~[],
style: None,
restyle_damage: None,
flow_construction_result: NoConstructionResult,
}
}
}
/// A trait that allows access to the layout data of a DOM node.
pub trait LayoutDataAccess {
/// Borrows the layout data without checks.
///
/// FIXME(pcwalton): Make safe.
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData>;
/// Borrows the layout data immutably. Fails on a conflicting borrow.
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>>;
/// Borrows the layout data mutably. Fails on a conflicting borrow.
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>>;
}
impl<'self> LayoutDataAccess for LayoutNode<'self> {
#[inline(always)]
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData> {
cast::transmute(self.get().layout_data.borrow_unchecked())
}
#[inline(always)]
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.borrow())
}
}
#[inline(always)]
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.mutate())
}
}
}
/// An opaque handle to a node. The only safe operation that can be performed on this node is to
/// compare it to another opaque handle or to another node.
///
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[deriving(Clone, Eq)]
pub struct OpaqueNode(uintptr_t);
impl OpaqueNode {
/// Converts a DOM node (layout view) to an `OpaqueNode`.
pub fn from_layout_node(node: &LayoutNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Converts a DOM node (script view) to an `OpaqueNode`.
pub fn from_script_node(node: &AbstractNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Unsafely converts an `OpaqueNode` to a DOM node (script view). Use this only if you
/// absolutely know what you're doing.
pub unsafe fn to_script_node(&self) -> AbstractNode {
cast::transmute(**self)
}
/// Returns the address of this node, for debugging purposes.
pub fn id(&self) -> uintptr_t {
unsafe {
cast::transmute_copy(self)
}
}
}
| {
break
} | conditional_block |
util.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 layout::box::Box;
use layout::construct::{ConstructionResult, NoConstructionResult};
use layout::wrapper::LayoutNode;
use extra::arc::Arc;
use script::dom::node::AbstractNode;
use servo_util::range::Range;
use servo_util::slot::{MutSlotRef, SlotRef};
use std::cast;
use std::iter::Enumerate;
use std::libc::uintptr_t;
use std::vec::VecIterator;
use style::{ComputedValues, PropertyDeclaration};
/// A range of nodes.
pub struct NodeRange {
node: OpaqueNode,
range: Range,
}
impl NodeRange {
pub fn new(node: OpaqueNode, range: &Range) -> NodeRange {
NodeRange {
node: node,
range: (*range).clone()
}
}
}
struct ElementMapping {
priv entries: ~[NodeRange],
}
impl ElementMapping {
pub fn new() -> ElementMapping {
ElementMapping {
entries: ~[],
}
}
pub fn add_mapping(&mut self, node: OpaqueNode, range: &Range) {
self.entries.push(NodeRange::new(node, range))
}
pub fn each(&self, callback: &fn(nr: &NodeRange) -> bool) -> bool {
for nr in self.entries.iter() {
if!callback(nr) {
break
}
}
true
}
pub fn eachi<'a>(&'a self) -> Enumerate<VecIterator<'a, NodeRange>> {
self.entries.iter().enumerate()
}
pub fn repair_for_box_changes(&mut self, old_boxes: &[Box], new_boxes: &[Box]) {
let entries = &mut self.entries;
debug!("--- Old boxes: ---");
for (i, box) in old_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- New boxes: ---");
for (i, box) in new_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- Elem ranges before repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
let mut old_i = 0;
let mut new_j = 0;
struct WorkItem {
begin_idx: uint,
entry_idx: uint,
};
let mut repair_stack : ~[WorkItem] = ~[];
// index into entries
let mut entries_k = 0;
while old_i < old_boxes.len() {
debug!("repair_for_box_changes: Considering old box {:u}", old_i);
// possibly push several items
while entries_k < entries.len() && old_i == entries[entries_k].range.begin() {
let item = WorkItem {begin_idx: new_j, entry_idx: entries_k};
debug!("repair_for_box_changes: Push work item for elem {:u}: {:?}", entries_k, item);
repair_stack.push(item);
entries_k += 1;
} | old_i += 1;
// possibly pop several items
while repair_stack.len() > 0 && old_i == entries[repair_stack.last().entry_idx].range.end() {
let item = repair_stack.pop();
debug!("repair_for_box_changes: Set range for {:u} to {}",
item.entry_idx, Range::new(item.begin_idx, new_j - item.begin_idx));
entries[item.entry_idx].range = Range::new(item.begin_idx, new_j - item.begin_idx);
}
}
debug!("--- Elem ranges after repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
}
}
/// Data that layout associates with a node.
pub struct LayoutData {
/// The results of CSS matching for this node.
applicable_declarations: ~[Arc<~[PropertyDeclaration]>],
/// The results of CSS styling for this node.
style: Option<Arc<ComputedValues>>,
/// Description of how to account for recent style changes.
restyle_damage: Option<int>,
/// The current results of flow construction for this node. This is either a flow or a
/// `ConstructionItem`. See comments in `construct.rs` for more details.
flow_construction_result: ConstructionResult,
}
impl LayoutData {
/// Creates new layout data.
pub fn new() -> LayoutData {
LayoutData {
applicable_declarations: ~[],
style: None,
restyle_damage: None,
flow_construction_result: NoConstructionResult,
}
}
}
/// A trait that allows access to the layout data of a DOM node.
pub trait LayoutDataAccess {
/// Borrows the layout data without checks.
///
/// FIXME(pcwalton): Make safe.
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData>;
/// Borrows the layout data immutably. Fails on a conflicting borrow.
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>>;
/// Borrows the layout data mutably. Fails on a conflicting borrow.
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>>;
}
impl<'self> LayoutDataAccess for LayoutNode<'self> {
#[inline(always)]
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData> {
cast::transmute(self.get().layout_data.borrow_unchecked())
}
#[inline(always)]
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.borrow())
}
}
#[inline(always)]
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.mutate())
}
}
}
/// An opaque handle to a node. The only safe operation that can be performed on this node is to
/// compare it to another opaque handle or to another node.
///
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[deriving(Clone, Eq)]
pub struct OpaqueNode(uintptr_t);
impl OpaqueNode {
/// Converts a DOM node (layout view) to an `OpaqueNode`.
pub fn from_layout_node(node: &LayoutNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Converts a DOM node (script view) to an `OpaqueNode`.
pub fn from_script_node(node: &AbstractNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Unsafely converts an `OpaqueNode` to a DOM node (script view). Use this only if you
/// absolutely know what you're doing.
pub unsafe fn to_script_node(&self) -> AbstractNode {
cast::transmute(**self)
}
/// Returns the address of this node, for debugging purposes.
pub fn id(&self) -> uintptr_t {
unsafe {
cast::transmute_copy(self)
}
}
} | while new_j < new_boxes.len() && old_boxes[old_i].node != new_boxes[new_j].node {
debug!("repair_for_box_changes: Slide through new box {:u}", new_j);
new_j += 1;
}
| random_line_split |
util.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 layout::box::Box;
use layout::construct::{ConstructionResult, NoConstructionResult};
use layout::wrapper::LayoutNode;
use extra::arc::Arc;
use script::dom::node::AbstractNode;
use servo_util::range::Range;
use servo_util::slot::{MutSlotRef, SlotRef};
use std::cast;
use std::iter::Enumerate;
use std::libc::uintptr_t;
use std::vec::VecIterator;
use style::{ComputedValues, PropertyDeclaration};
/// A range of nodes.
pub struct NodeRange {
node: OpaqueNode,
range: Range,
}
impl NodeRange {
pub fn new(node: OpaqueNode, range: &Range) -> NodeRange {
NodeRange {
node: node,
range: (*range).clone()
}
}
}
struct ElementMapping {
priv entries: ~[NodeRange],
}
impl ElementMapping {
pub fn new() -> ElementMapping {
ElementMapping {
entries: ~[],
}
}
pub fn add_mapping(&mut self, node: OpaqueNode, range: &Range) {
self.entries.push(NodeRange::new(node, range))
}
pub fn each(&self, callback: &fn(nr: &NodeRange) -> bool) -> bool {
for nr in self.entries.iter() {
if!callback(nr) {
break
}
}
true
}
pub fn eachi<'a>(&'a self) -> Enumerate<VecIterator<'a, NodeRange>> {
self.entries.iter().enumerate()
}
pub fn repair_for_box_changes(&mut self, old_boxes: &[Box], new_boxes: &[Box]) {
let entries = &mut self.entries;
debug!("--- Old boxes: ---");
for (i, box) in old_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- New boxes: ---");
for (i, box) in new_boxes.iter().enumerate() {
debug!("{:u} --> {:s}", i, box.debug_str());
}
debug!("------------------");
debug!("--- Elem ranges before repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
let mut old_i = 0;
let mut new_j = 0;
struct WorkItem {
begin_idx: uint,
entry_idx: uint,
};
let mut repair_stack : ~[WorkItem] = ~[];
// index into entries
let mut entries_k = 0;
while old_i < old_boxes.len() {
debug!("repair_for_box_changes: Considering old box {:u}", old_i);
// possibly push several items
while entries_k < entries.len() && old_i == entries[entries_k].range.begin() {
let item = WorkItem {begin_idx: new_j, entry_idx: entries_k};
debug!("repair_for_box_changes: Push work item for elem {:u}: {:?}", entries_k, item);
repair_stack.push(item);
entries_k += 1;
}
while new_j < new_boxes.len() && old_boxes[old_i].node!= new_boxes[new_j].node {
debug!("repair_for_box_changes: Slide through new box {:u}", new_j);
new_j += 1;
}
old_i += 1;
// possibly pop several items
while repair_stack.len() > 0 && old_i == entries[repair_stack.last().entry_idx].range.end() {
let item = repair_stack.pop();
debug!("repair_for_box_changes: Set range for {:u} to {}",
item.entry_idx, Range::new(item.begin_idx, new_j - item.begin_idx));
entries[item.entry_idx].range = Range::new(item.begin_idx, new_j - item.begin_idx);
}
}
debug!("--- Elem ranges after repair: ---");
for (i, nr) in entries.iter().enumerate() {
debug!("{:u}: {} --> {:?}", i, nr.range, nr.node.id());
}
debug!("----------------------------------");
}
}
/// Data that layout associates with a node.
pub struct LayoutData {
/// The results of CSS matching for this node.
applicable_declarations: ~[Arc<~[PropertyDeclaration]>],
/// The results of CSS styling for this node.
style: Option<Arc<ComputedValues>>,
/// Description of how to account for recent style changes.
restyle_damage: Option<int>,
/// The current results of flow construction for this node. This is either a flow or a
/// `ConstructionItem`. See comments in `construct.rs` for more details.
flow_construction_result: ConstructionResult,
}
impl LayoutData {
/// Creates new layout data.
pub fn new() -> LayoutData {
LayoutData {
applicable_declarations: ~[],
style: None,
restyle_damage: None,
flow_construction_result: NoConstructionResult,
}
}
}
/// A trait that allows access to the layout data of a DOM node.
pub trait LayoutDataAccess {
/// Borrows the layout data without checks.
///
/// FIXME(pcwalton): Make safe.
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData>;
/// Borrows the layout data immutably. Fails on a conflicting borrow.
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>>;
/// Borrows the layout data mutably. Fails on a conflicting borrow.
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>>;
}
impl<'self> LayoutDataAccess for LayoutNode<'self> {
#[inline(always)]
unsafe fn borrow_layout_data_unchecked<'a>(&'a self) -> &'a Option<~LayoutData> {
cast::transmute(self.get().layout_data.borrow_unchecked())
}
#[inline(always)]
fn borrow_layout_data<'a>(&'a self) -> SlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.borrow())
}
}
#[inline(always)]
fn mutate_layout_data<'a>(&'a self) -> MutSlotRef<'a,Option<~LayoutData>> {
unsafe {
cast::transmute(self.get().layout_data.mutate())
}
}
}
/// An opaque handle to a node. The only safe operation that can be performed on this node is to
/// compare it to another opaque handle or to another node.
///
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[deriving(Clone, Eq)]
pub struct OpaqueNode(uintptr_t);
impl OpaqueNode {
/// Converts a DOM node (layout view) to an `OpaqueNode`.
pub fn from_layout_node(node: &LayoutNode) -> OpaqueNode |
/// Converts a DOM node (script view) to an `OpaqueNode`.
pub fn from_script_node(node: &AbstractNode) -> OpaqueNode {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
}
/// Unsafely converts an `OpaqueNode` to a DOM node (script view). Use this only if you
/// absolutely know what you're doing.
pub unsafe fn to_script_node(&self) -> AbstractNode {
cast::transmute(**self)
}
/// Returns the address of this node, for debugging purposes.
pub fn id(&self) -> uintptr_t {
unsafe {
cast::transmute_copy(self)
}
}
}
| {
unsafe {
OpaqueNode(cast::transmute_copy(node))
}
} | identifier_body |
factor_int.rs | // Implements http://rosettacode.org/wiki/Factors_of_an_integer
#[cfg(not(test))]
fn main() |
// Compute the factors of an integer
// This method uses a simple check on each value between 1 and sqrt(x) to find
// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in (1i32..bound) {
if x % i == 0 {
factors.push(i);
factors.push(x/i);
}
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
} | identifier_body |
factor_int.rs | // Implements http://rosettacode.org/wiki/Factors_of_an_integer
#[cfg(not(test))]
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
// Compute the factors of an integer
// This method uses a simple check on each value between 1 and sqrt(x) to find
// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in (1i32..bound) {
if x % i == 0 |
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| {
factors.push(i);
factors.push(x/i);
} | conditional_block |
factor_int.rs | // Implements http://rosettacode.org/wiki/Factors_of_an_integer
#[cfg(not(test))]
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
// Compute the factors of an integer
// This method uses a simple check on each value between 1 and sqrt(x) to find
// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
for i in (1i32..bound) {
if x % i == 0 {
factors.push(i);
factors.push(x/i);
}
}
factors
}
#[test]
fn | () {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
}
| test | identifier_name |
factor_int.rs | // Implements http://rosettacode.org/wiki/Factors_of_an_integer
#[cfg(not(test))]
fn main() {
let target = 78i32;
println!("Factors of integer {}:", target);
let factors = factor_int(target);
for f in factors {
println!("{}", f);
}
}
// Compute the factors of an integer
// This method uses a simple check on each value between 1 and sqrt(x) to find
// pairs of factors
fn factor_int(x: i32) -> Vec<i32> {
let mut factors: Vec<i32> = Vec::new();
let bound: i32 = (x as f64).sqrt().floor() as i32;
| factors.push(i);
factors.push(x/i);
}
}
factors
}
#[test]
fn test() {
let result = factor_int(78i32);
assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]);
} | for i in (1i32..bound) {
if x % i == 0 { | random_line_split |
topic.rs | use std::fmt;
use protocol::command::CMD_TOPIC;
use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct TopicCommand<'a> {
channel: &'a str,
topic: Option<&'a str>,
}
impl<'a> TopicCommand<'a> {
pub fn new(channel: &'a str, topic: Option<&'a str>) -> TopicCommand<'a> {
TopicCommand {
channel: channel,
topic: topic,
}
}
pub fn | (&self) -> &'a str {
self.channel
}
pub fn topic(&self) -> Option<&'a str> {
self.topic
}
}
impl<'a> fmt::Display for TopicCommand<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{} {}", CMD_TOPIC, self.channel));
match self.topic {
None => Ok(()),
Some(t) => write!(f, " :{}", t),
}
}
}
impl<'a> IrcMessage<'a> for TopicCommand<'a> {
fn from_raw(raw: &RawMessage<'a>) -> Result<TopicCommand<'a>, ParseMessageError> {
let mut params = raw.parameters();
let channel = match params.next() {
None => {
return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams,
"TOPIC requires a channel"));
},
Some(t) => t,
};
Ok(TopicCommand::new(channel, params.next()))
}
}
| channel | identifier_name |
topic.rs | use std::fmt;
use protocol::command::CMD_TOPIC;
use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind};
#[derive(Debug, Clone, Eq, PartialEq)] | impl<'a> TopicCommand<'a> {
pub fn new(channel: &'a str, topic: Option<&'a str>) -> TopicCommand<'a> {
TopicCommand {
channel: channel,
topic: topic,
}
}
pub fn channel(&self) -> &'a str {
self.channel
}
pub fn topic(&self) -> Option<&'a str> {
self.topic
}
}
impl<'a> fmt::Display for TopicCommand<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{} {}", CMD_TOPIC, self.channel));
match self.topic {
None => Ok(()),
Some(t) => write!(f, " :{}", t),
}
}
}
impl<'a> IrcMessage<'a> for TopicCommand<'a> {
fn from_raw(raw: &RawMessage<'a>) -> Result<TopicCommand<'a>, ParseMessageError> {
let mut params = raw.parameters();
let channel = match params.next() {
None => {
return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams,
"TOPIC requires a channel"));
},
Some(t) => t,
};
Ok(TopicCommand::new(channel, params.next()))
}
} | pub struct TopicCommand<'a> {
channel: &'a str,
topic: Option<&'a str>,
}
| random_line_split |
regionmanip.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.
// #![warn(deprecated_mode)]
use middle::ty;
use middle::ty_fold;
use middle::ty_fold::TypeFolder;
use collections::HashMap;
use util::ppaux::Repr;
use util::ppaux;
// Helper functions related to manipulating region types.
pub fn replace_late_bound_regions_in_fn_sig(
tcx: &ty::ctxt,
fn_sig: &ty::FnSig,
mapf: |ty::BoundRegion| -> ty::Region)
-> (HashMap<ty::BoundRegion,ty::Region>, ty::FnSig) {
debug!("replace_late_bound_regions_in_fn_sig({})", fn_sig.repr(tcx));
let mut map = HashMap::new();
let fn_sig = {
let mut f = ty_fold::RegionFolder::regions(tcx, |r| {
debug!("region r={}", r.to_str());
match r {
ty::ReLateBound(s, br) if s == fn_sig.binder_id => {
*map.find_or_insert_with(br, |_| mapf(br))
}
_ => r
}
});
ty_fold::super_fold_sig(&mut f, fn_sig)
};
debug!("resulting map: {}", map);
(map, fn_sig)
}
pub fn relate_nested_regions(tcx: &ty::ctxt,
opt_region: Option<ty::Region>,
ty: ty::t,
relate_op: |ty::Region, ty::Region|) {
/*!
* This rather specialized function walks each region `r` that appear
* in `ty` and invokes `relate_op(r_encl, r)` for each one. `r_encl`
* here is the region of any enclosing `&'r T` pointer. If there is
* no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
* is used instead. Otherwise, no callback occurs at all).
*
* Here are some examples to give you an intution:
*
* - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_op('r2, 'r4)`
* - `relate_op('r3, 'r4)`
*
* This function is used in various pieces of code because we enforce the
* constraint that a region pointer cannot outlive the things it points at.
* Hence, in the second example above, `'r2` must be a subregion of `'r3`.
*/
let mut rr = RegionRelator { tcx: tcx,
stack: Vec::new(),
relate_op: relate_op };
match opt_region {
Some(o_r) => { rr.stack.push(o_r); }
None => {}
}
rr.fold_ty(ty);
struct RegionRelator<'a> {
tcx: &'a ty::ctxt,
stack: Vec<ty::Region>,
relate_op: |ty::Region, ty::Region|: 'a,
}
// FIXME(#10151) -- Define more precisely when a region is
// considered "nested". Consider taking variance into account as
// well.
impl<'a> TypeFolder for RegionRelator<'a> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.tcx
}
fn fold_ty(&mut self, ty: ty::t) -> ty::t {
match ty::get(ty).sty {
ty::ty_rptr(r, ty::mt {ty,..}) => {
self.relate(r);
self.stack.push(r);
ty_fold::super_fold_ty(self, ty);
self.stack.pop().unwrap();
} |
ty
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.relate(r);
r
}
}
impl<'a> RegionRelator<'a> {
fn relate(&mut self, r_sub: ty::Region) {
for &r in self.stack.iter() {
if!r.is_bound() &&!r_sub.is_bound() {
(self.relate_op)(r, r_sub);
}
}
}
}
}
pub fn relate_free_regions(tcx: &ty::ctxt, fn_sig: &ty::FnSig) {
/*!
* This function populates the region map's `free_region_map`.
* It walks over the transformed self type and argument types
* for each function just before we check the body of that
* function, looking for types where you have a borrowed
* pointer to other borrowed data (e.g., `&'a &'b [uint]`.
* We do not allow references to outlive the things they
* point at, so we can assume that `'a <= 'b`.
*
* Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
*/
debug!("relate_free_regions >>");
let mut all_tys = Vec::new();
for arg in fn_sig.inputs.iter() {
all_tys.push(*arg);
}
for &t in all_tys.iter() {
debug!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
relate_nested_regions(tcx, None, t, |a, b| {
match (&a, &b) {
(&ty::ReFree(free_a), &ty::ReFree(free_b)) => {
tcx.region_maps.relate_free_regions(free_a, free_b);
}
_ => {}
}
})
}
debug!("<< relate_free_regions");
} |
_ => {
ty_fold::super_fold_ty(self, ty);
}
} | random_line_split |
regionmanip.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.
// #![warn(deprecated_mode)]
use middle::ty;
use middle::ty_fold;
use middle::ty_fold::TypeFolder;
use collections::HashMap;
use util::ppaux::Repr;
use util::ppaux;
// Helper functions related to manipulating region types.
pub fn replace_late_bound_regions_in_fn_sig(
tcx: &ty::ctxt,
fn_sig: &ty::FnSig,
mapf: |ty::BoundRegion| -> ty::Region)
-> (HashMap<ty::BoundRegion,ty::Region>, ty::FnSig) {
debug!("replace_late_bound_regions_in_fn_sig({})", fn_sig.repr(tcx));
let mut map = HashMap::new();
let fn_sig = {
let mut f = ty_fold::RegionFolder::regions(tcx, |r| {
debug!("region r={}", r.to_str());
match r {
ty::ReLateBound(s, br) if s == fn_sig.binder_id => {
*map.find_or_insert_with(br, |_| mapf(br))
}
_ => r
}
});
ty_fold::super_fold_sig(&mut f, fn_sig)
};
debug!("resulting map: {}", map);
(map, fn_sig)
}
pub fn relate_nested_regions(tcx: &ty::ctxt,
opt_region: Option<ty::Region>,
ty: ty::t,
relate_op: |ty::Region, ty::Region|) {
/*!
* This rather specialized function walks each region `r` that appear
* in `ty` and invokes `relate_op(r_encl, r)` for each one. `r_encl`
* here is the region of any enclosing `&'r T` pointer. If there is
* no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
* is used instead. Otherwise, no callback occurs at all).
*
* Here are some examples to give you an intution:
*
* - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_op('r2, 'r4)`
* - `relate_op('r3, 'r4)`
*
* This function is used in various pieces of code because we enforce the
* constraint that a region pointer cannot outlive the things it points at.
* Hence, in the second example above, `'r2` must be a subregion of `'r3`.
*/
let mut rr = RegionRelator { tcx: tcx,
stack: Vec::new(),
relate_op: relate_op };
match opt_region {
Some(o_r) => { rr.stack.push(o_r); }
None => |
}
rr.fold_ty(ty);
struct RegionRelator<'a> {
tcx: &'a ty::ctxt,
stack: Vec<ty::Region>,
relate_op: |ty::Region, ty::Region|: 'a,
}
// FIXME(#10151) -- Define more precisely when a region is
// considered "nested". Consider taking variance into account as
// well.
impl<'a> TypeFolder for RegionRelator<'a> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.tcx
}
fn fold_ty(&mut self, ty: ty::t) -> ty::t {
match ty::get(ty).sty {
ty::ty_rptr(r, ty::mt {ty,..}) => {
self.relate(r);
self.stack.push(r);
ty_fold::super_fold_ty(self, ty);
self.stack.pop().unwrap();
}
_ => {
ty_fold::super_fold_ty(self, ty);
}
}
ty
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.relate(r);
r
}
}
impl<'a> RegionRelator<'a> {
fn relate(&mut self, r_sub: ty::Region) {
for &r in self.stack.iter() {
if!r.is_bound() &&!r_sub.is_bound() {
(self.relate_op)(r, r_sub);
}
}
}
}
}
pub fn relate_free_regions(tcx: &ty::ctxt, fn_sig: &ty::FnSig) {
/*!
* This function populates the region map's `free_region_map`.
* It walks over the transformed self type and argument types
* for each function just before we check the body of that
* function, looking for types where you have a borrowed
* pointer to other borrowed data (e.g., `&'a &'b [uint]`.
* We do not allow references to outlive the things they
* point at, so we can assume that `'a <= 'b`.
*
* Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
*/
debug!("relate_free_regions >>");
let mut all_tys = Vec::new();
for arg in fn_sig.inputs.iter() {
all_tys.push(*arg);
}
for &t in all_tys.iter() {
debug!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
relate_nested_regions(tcx, None, t, |a, b| {
match (&a, &b) {
(&ty::ReFree(free_a), &ty::ReFree(free_b)) => {
tcx.region_maps.relate_free_regions(free_a, free_b);
}
_ => {}
}
})
}
debug!("<< relate_free_regions");
}
| {} | conditional_block |
regionmanip.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.
// #![warn(deprecated_mode)]
use middle::ty;
use middle::ty_fold;
use middle::ty_fold::TypeFolder;
use collections::HashMap;
use util::ppaux::Repr;
use util::ppaux;
// Helper functions related to manipulating region types.
pub fn replace_late_bound_regions_in_fn_sig(
tcx: &ty::ctxt,
fn_sig: &ty::FnSig,
mapf: |ty::BoundRegion| -> ty::Region)
-> (HashMap<ty::BoundRegion,ty::Region>, ty::FnSig) {
debug!("replace_late_bound_regions_in_fn_sig({})", fn_sig.repr(tcx));
let mut map = HashMap::new();
let fn_sig = {
let mut f = ty_fold::RegionFolder::regions(tcx, |r| {
debug!("region r={}", r.to_str());
match r {
ty::ReLateBound(s, br) if s == fn_sig.binder_id => {
*map.find_or_insert_with(br, |_| mapf(br))
}
_ => r
}
});
ty_fold::super_fold_sig(&mut f, fn_sig)
};
debug!("resulting map: {}", map);
(map, fn_sig)
}
pub fn | (tcx: &ty::ctxt,
opt_region: Option<ty::Region>,
ty: ty::t,
relate_op: |ty::Region, ty::Region|) {
/*!
* This rather specialized function walks each region `r` that appear
* in `ty` and invokes `relate_op(r_encl, r)` for each one. `r_encl`
* here is the region of any enclosing `&'r T` pointer. If there is
* no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
* is used instead. Otherwise, no callback occurs at all).
*
* Here are some examples to give you an intution:
*
* - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_op('r2, 'r4)`
* - `relate_op('r3, 'r4)`
*
* This function is used in various pieces of code because we enforce the
* constraint that a region pointer cannot outlive the things it points at.
* Hence, in the second example above, `'r2` must be a subregion of `'r3`.
*/
let mut rr = RegionRelator { tcx: tcx,
stack: Vec::new(),
relate_op: relate_op };
match opt_region {
Some(o_r) => { rr.stack.push(o_r); }
None => {}
}
rr.fold_ty(ty);
struct RegionRelator<'a> {
tcx: &'a ty::ctxt,
stack: Vec<ty::Region>,
relate_op: |ty::Region, ty::Region|: 'a,
}
// FIXME(#10151) -- Define more precisely when a region is
// considered "nested". Consider taking variance into account as
// well.
impl<'a> TypeFolder for RegionRelator<'a> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.tcx
}
fn fold_ty(&mut self, ty: ty::t) -> ty::t {
match ty::get(ty).sty {
ty::ty_rptr(r, ty::mt {ty,..}) => {
self.relate(r);
self.stack.push(r);
ty_fold::super_fold_ty(self, ty);
self.stack.pop().unwrap();
}
_ => {
ty_fold::super_fold_ty(self, ty);
}
}
ty
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.relate(r);
r
}
}
impl<'a> RegionRelator<'a> {
fn relate(&mut self, r_sub: ty::Region) {
for &r in self.stack.iter() {
if!r.is_bound() &&!r_sub.is_bound() {
(self.relate_op)(r, r_sub);
}
}
}
}
}
pub fn relate_free_regions(tcx: &ty::ctxt, fn_sig: &ty::FnSig) {
/*!
* This function populates the region map's `free_region_map`.
* It walks over the transformed self type and argument types
* for each function just before we check the body of that
* function, looking for types where you have a borrowed
* pointer to other borrowed data (e.g., `&'a &'b [uint]`.
* We do not allow references to outlive the things they
* point at, so we can assume that `'a <= 'b`.
*
* Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
*/
debug!("relate_free_regions >>");
let mut all_tys = Vec::new();
for arg in fn_sig.inputs.iter() {
all_tys.push(*arg);
}
for &t in all_tys.iter() {
debug!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
relate_nested_regions(tcx, None, t, |a, b| {
match (&a, &b) {
(&ty::ReFree(free_a), &ty::ReFree(free_b)) => {
tcx.region_maps.relate_free_regions(free_a, free_b);
}
_ => {}
}
})
}
debug!("<< relate_free_regions");
}
| relate_nested_regions | identifier_name |
regionmanip.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.
// #![warn(deprecated_mode)]
use middle::ty;
use middle::ty_fold;
use middle::ty_fold::TypeFolder;
use collections::HashMap;
use util::ppaux::Repr;
use util::ppaux;
// Helper functions related to manipulating region types.
pub fn replace_late_bound_regions_in_fn_sig(
tcx: &ty::ctxt,
fn_sig: &ty::FnSig,
mapf: |ty::BoundRegion| -> ty::Region)
-> (HashMap<ty::BoundRegion,ty::Region>, ty::FnSig) {
debug!("replace_late_bound_regions_in_fn_sig({})", fn_sig.repr(tcx));
let mut map = HashMap::new();
let fn_sig = {
let mut f = ty_fold::RegionFolder::regions(tcx, |r| {
debug!("region r={}", r.to_str());
match r {
ty::ReLateBound(s, br) if s == fn_sig.binder_id => {
*map.find_or_insert_with(br, |_| mapf(br))
}
_ => r
}
});
ty_fold::super_fold_sig(&mut f, fn_sig)
};
debug!("resulting map: {}", map);
(map, fn_sig)
}
pub fn relate_nested_regions(tcx: &ty::ctxt,
opt_region: Option<ty::Region>,
ty: ty::t,
relate_op: |ty::Region, ty::Region|) {
/*!
* This rather specialized function walks each region `r` that appear
* in `ty` and invokes `relate_op(r_encl, r)` for each one. `r_encl`
* here is the region of any enclosing `&'r T` pointer. If there is
* no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
* is used instead. Otherwise, no callback occurs at all).
*
* Here are some examples to give you an intution:
*
* - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
* - `relate_op('r1, 'r2)`
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
* - `relate_op('r2, 'r3)`
* - `relate_op('r2, 'r4)`
* - `relate_op('r3, 'r4)`
*
* This function is used in various pieces of code because we enforce the
* constraint that a region pointer cannot outlive the things it points at.
* Hence, in the second example above, `'r2` must be a subregion of `'r3`.
*/
let mut rr = RegionRelator { tcx: tcx,
stack: Vec::new(),
relate_op: relate_op };
match opt_region {
Some(o_r) => { rr.stack.push(o_r); }
None => {}
}
rr.fold_ty(ty);
struct RegionRelator<'a> {
tcx: &'a ty::ctxt,
stack: Vec<ty::Region>,
relate_op: |ty::Region, ty::Region|: 'a,
}
// FIXME(#10151) -- Define more precisely when a region is
// considered "nested". Consider taking variance into account as
// well.
impl<'a> TypeFolder for RegionRelator<'a> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt {
self.tcx
}
fn fold_ty(&mut self, ty: ty::t) -> ty::t {
match ty::get(ty).sty {
ty::ty_rptr(r, ty::mt {ty,..}) => {
self.relate(r);
self.stack.push(r);
ty_fold::super_fold_ty(self, ty);
self.stack.pop().unwrap();
}
_ => {
ty_fold::super_fold_ty(self, ty);
}
}
ty
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
self.relate(r);
r
}
}
impl<'a> RegionRelator<'a> {
fn relate(&mut self, r_sub: ty::Region) {
for &r in self.stack.iter() {
if!r.is_bound() &&!r_sub.is_bound() {
(self.relate_op)(r, r_sub);
}
}
}
}
}
pub fn relate_free_regions(tcx: &ty::ctxt, fn_sig: &ty::FnSig) | for &t in all_tys.iter() {
debug!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
relate_nested_regions(tcx, None, t, |a, b| {
match (&a, &b) {
(&ty::ReFree(free_a), &ty::ReFree(free_b)) => {
tcx.region_maps.relate_free_regions(free_a, free_b);
}
_ => {}
}
})
}
debug!("<< relate_free_regions");
}
| {
/*!
* This function populates the region map's `free_region_map`.
* It walks over the transformed self type and argument types
* for each function just before we check the body of that
* function, looking for types where you have a borrowed
* pointer to other borrowed data (e.g., `&'a &'b [uint]`.
* We do not allow references to outlive the things they
* point at, so we can assume that `'a <= 'b`.
*
* Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
*/
debug!("relate_free_regions >>");
let mut all_tys = Vec::new();
for arg in fn_sig.inputs.iter() {
all_tys.push(*arg);
}
| identifier_body |
x86.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use metadata::loader::meta_section_name;
use syntax::abi;
pub fn | (target_triple: ~str, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" +
"-i32:32:32-i64:32:64" +
"-f32:32:32-f64:32:64-v64:64:64" +
"-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32"
}
abi::OsWin32 => {
~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32"
}
abi::OsLinux => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
abi::OsAndroid => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
abi::OsFreebsd => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
},
target_triple: target_triple,
cc_args: ~[~"-m32"],
};
}
| get_target_strs | identifier_name |
x86.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use metadata::loader::meta_section_name;
use syntax::abi;
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
| "-i32:32:32-i64:32:64" +
"-f32:32:32-f64:32:64-v64:64:64" +
"-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32"
}
abi::OsWin32 => {
~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32"
}
abi::OsLinux => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
abi::OsAndroid => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
abi::OsFreebsd => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
},
target_triple: target_triple,
cc_args: ~[~"-m32"],
};
} | data_layout: match target_os {
abi::OsMacos => {
~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" + | random_line_split |
x86.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use metadata::loader::meta_section_name;
use syntax::abi;
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t | }
abi::OsAndroid => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
abi::OsFreebsd => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
},
target_triple: target_triple,
cc_args: ~[~"-m32"],
};
}
| {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" +
"-i32:32:32-i64:32:64" +
"-f32:32:32-f64:32:64-v64:64:64" +
"-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32"
}
abi::OsWin32 => {
~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32"
}
abi::OsLinux => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32" | identifier_body |
x86.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use metadata::loader::meta_section_name;
use syntax::abi;
pub fn get_target_strs(target_triple: ~str, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(),
data_layout: match target_os {
abi::OsMacos => {
~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" +
"-i32:32:32-i64:32:64" +
"-f32:32:32-f64:32:64-v64:64:64" +
"-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32"
}
abi::OsWin32 => {
~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32"
}
abi::OsLinux => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
abi::OsAndroid => |
abi::OsFreebsd => {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
}
},
target_triple: target_triple,
cc_args: ~[~"-m32"],
};
}
| {
~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32"
} | conditional_block |
deriving-eq-ord-boxed-slice.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)] | let a = Foo(box [0, 1, 2]);
let b = Foo(box [0, 1, 2]);
assert!(a == b);
println!("{}", a!= b);
println!("{}", a < b);
println!("{}", a <= b);
println!("{}", a == b);
println!("{}", a > b);
println!("{}", a >= b);
} |
#[derive(PartialEq, PartialOrd, Eq, Ord)]
struct Foo(Box<[u8]>);
pub fn main() { | random_line_split |
deriving-eq-ord-boxed-slice.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
#[derive(PartialEq, PartialOrd, Eq, Ord)]
struct Foo(Box<[u8]>);
pub fn main() | {
let a = Foo(box [0, 1, 2]);
let b = Foo(box [0, 1, 2]);
assert!(a == b);
println!("{}", a != b);
println!("{}", a < b);
println!("{}", a <= b);
println!("{}", a == b);
println!("{}", a > b);
println!("{}", a >= b);
} | identifier_body |
|
deriving-eq-ord-boxed-slice.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(unknown_features)]
#![feature(box_syntax)]
#[derive(PartialEq, PartialOrd, Eq, Ord)]
struct Foo(Box<[u8]>);
pub fn | () {
let a = Foo(box [0, 1, 2]);
let b = Foo(box [0, 1, 2]);
assert!(a == b);
println!("{}", a!= b);
println!("{}", a < b);
println!("{}", a <= b);
println!("{}", a == b);
println!("{}", a > b);
println!("{}", a >= b);
}
| main | identifier_name |
abstractworkerglobalscope.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::abstractworker::WorkerScriptMsg;
use crate::dom::bindings::conversions::DerivedFrom;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::dedicatedworkerglobalscope::{AutoWorkerReset, DedicatedWorkerScriptMsg};
use crate::dom::globalscope::GlobalScope;
use crate::dom::worker::TrustedWorkerAddress;
use crate::dom::workerglobalscope::WorkerGlobalScope;
use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort};
use crate::task_queue::{QueuedTaskConversion, TaskQueue};
use crossbeam_channel::{Receiver, Sender};
use devtools_traits::DevtoolScriptControlMsg;
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// common event loop messages. While this SendableWorkerScriptChan is alive, the associated
/// Worker object will remain alive.
#[derive(Clone, JSTraceable)]
pub struct SendableWorkerScriptChan {
pub sender: Sender<DedicatedWorkerScriptMsg>,
pub worker: TrustedWorkerAddress,
}
impl ScriptChan for SendableWorkerScriptChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
let msg = DedicatedWorkerScriptMsg::CommonWorker(
self.worker.clone(),
WorkerScriptMsg::Common(msg),
);
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(SendableWorkerScriptChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
/// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with
/// worker event loop messages. While this SendableWorkerScriptChan is alive, the associated
/// Worker object will remain alive.
#[derive(Clone, JSTraceable)]
pub struct WorkerThreadWorkerChan {
pub sender: Sender<DedicatedWorkerScriptMsg>,
pub worker: TrustedWorkerAddress,
}
impl ScriptChan for WorkerThreadWorkerChan {
fn send(&self, msg: CommonScriptMsg) -> Result<(), ()> {
let msg = DedicatedWorkerScriptMsg::CommonWorker(
self.worker.clone(),
WorkerScriptMsg::Common(msg),
);
self.sender.send(msg).map_err(|_| ())
}
fn clone(&self) -> Box<dyn ScriptChan + Send> {
Box::new(WorkerThreadWorkerChan {
sender: self.sender.clone(),
worker: self.worker.clone(),
})
}
}
impl ScriptPort for Receiver<DedicatedWorkerScriptMsg> {
fn | (&self) -> Result<CommonScriptMsg, ()> {
let common_msg = match self.recv() {
Ok(DedicatedWorkerScriptMsg::CommonWorker(_worker, common_msg)) => common_msg,
Err(_) => return Err(()),
Ok(DedicatedWorkerScriptMsg::WakeUp) => panic!("unexpected worker event message!"),
};
match common_msg {
WorkerScriptMsg::Common(script_msg) => Ok(script_msg),
WorkerScriptMsg::DOMMessage {.. } => panic!("unexpected worker event message!"),
}
}
}
pub trait WorkerEventLoopMethods {
type TimerMsg: Send;
type WorkerMsg: QueuedTaskConversion + Send;
type Event;
fn timer_event_port(&self) -> &Receiver<Self::TimerMsg>;
fn task_queue(&self) -> &TaskQueue<Self::WorkerMsg>;
fn handle_event(&self, event: Self::Event);
fn handle_worker_post_event(&self, worker: &TrustedWorkerAddress) -> Option<AutoWorkerReset>;
fn from_worker_msg(&self, msg: Self::WorkerMsg) -> Self::Event;
fn from_timer_msg(&self, msg: Self::TimerMsg) -> Self::Event;
fn from_devtools_msg(&self, msg: DevtoolScriptControlMsg) -> Self::Event;
}
// https://html.spec.whatwg.org/multipage/#worker-event-loop
pub fn run_worker_event_loop<T, TimerMsg, WorkerMsg, Event>(
worker_scope: &T,
worker: Option<&TrustedWorkerAddress>,
) where
TimerMsg: Send,
WorkerMsg: QueuedTaskConversion + Send,
T: WorkerEventLoopMethods<TimerMsg = TimerMsg, WorkerMsg = WorkerMsg, Event = Event>
+ DerivedFrom<WorkerGlobalScope>
+ DerivedFrom<GlobalScope>
+ DomObject,
{
let scope = worker_scope.upcast::<WorkerGlobalScope>();
let timer_event_port = worker_scope.timer_event_port();
let devtools_port = match scope.from_devtools_sender() {
Some(_) => Some(scope.from_devtools_receiver()),
None => None,
};
let task_queue = worker_scope.task_queue();
let event = select! {
recv(task_queue.select()) -> msg => {
task_queue.take_tasks(msg.unwrap());
worker_scope.from_worker_msg(task_queue.recv().unwrap())
},
recv(timer_event_port) -> msg => worker_scope.from_timer_msg(msg.unwrap()),
recv(devtools_port.unwrap_or(&crossbeam_channel::never())) -> msg =>
worker_scope.from_devtools_msg(msg.unwrap()),
};
let mut sequential = vec![];
sequential.push(event);
// https://html.spec.whatwg.org/multipage/#worker-event-loop
// Once the WorkerGlobalScope's closing flag is set to true,
// the event loop's task queues must discard any further tasks
// that would be added to them
// (tasks already on the queue are unaffected except where otherwise specified).
while!scope.is_closing() {
// Batch all events that are ready.
// The task queue will throttle non-priority tasks if necessary.
match task_queue.try_recv() {
Err(_) => match timer_event_port.try_recv() {
Err(_) => match devtools_port.map(|port| port.try_recv()) {
None => {},
Some(Err(_)) => break,
Some(Ok(ev)) => sequential.push(worker_scope.from_devtools_msg(ev)),
},
Ok(ev) => sequential.push(worker_scope.from_timer_msg(ev)),
},
Ok(ev) => sequential.push(worker_scope.from_worker_msg(ev)),
}
}
// Step 3
for event in sequential {
worker_scope.handle_event(event);
// Step 6
let _ar = match worker {
Some(worker) => worker_scope.handle_worker_post_event(worker),
None => None,
};
worker_scope
.upcast::<GlobalScope>()
.perform_a_microtask_checkpoint();
}
worker_scope
.upcast::<GlobalScope>()
.perform_a_message_port_garbage_collection_checkpoint();
}
| recv | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.