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 |
---|---|---|---|---|
input_process.rs
|
extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn
|
(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () {
for event in graphics_state.display.poll_events() {
match event {
Closed => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::Escape)) => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::F3)) => {
graphics_state.reload_shaders = true;
}
KeyboardInput(Pressed, _, Some(VK::F4)) => {
core_state.reload = true
}
KeyboardInput(Pressed, _, Some(VK::F5)) => {
core_state.reset = true
}
_ => ()
}
}
}
|
execute
|
identifier_name
|
input_process.rs
|
extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn execute(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> ()
|
}
}
|
{
for event in graphics_state.display.poll_events() {
match event {
Closed => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::Escape)) => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::F3)) => {
graphics_state.reload_shaders = true;
}
KeyboardInput(Pressed, _, Some(VK::F4)) => {
core_state.reload = true
}
KeyboardInput(Pressed, _, Some(VK::F5)) => {
core_state.reset = true
}
_ => ()
}
|
identifier_body
|
input_process.rs
|
extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn execute(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () {
for event in graphics_state.display.poll_events() {
match event {
Closed => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::Escape)) => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::F3)) => {
graphics_state.reload_shaders = true;
}
KeyboardInput(Pressed, _, Some(VK::F4)) => {
core_state.reload = true
}
KeyboardInput(Pressed, _, Some(VK::F5)) =>
|
_ => ()
}
}
}
|
{
core_state.reset = true
}
|
conditional_block
|
version.rs
|
/*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use sys::version as ll;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct
|
{
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: ll::SDL_version) -> Version {
Version { major: v.major, minor: v.minor, patch: v.patch }
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
}
/// Get the version of SDL that is linked against your program.
pub fn version() -> Version {
unsafe {
let mut cver = ll::SDL_version { major: 0, minor: 0, patch: 0};
ll::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
pub fn revision() -> String {
unsafe {
let rev = ll::SDL_GetRevision();
String::from_utf8_lossy(CStr::from_ptr(rev).to_bytes()).to_string()
}
}
/// Get the revision number of SDL that is linked against your program.
pub fn revision_number() -> i32 {
unsafe {
ll::SDL_GetRevisionNumber()
}
}
|
Version
|
identifier_name
|
version.rs
|
/*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use sys::version as ll;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: ll::SDL_version) -> Version {
Version { major: v.major, minor: v.minor, patch: v.patch }
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
|
pub fn version() -> Version {
unsafe {
let mut cver = ll::SDL_version { major: 0, minor: 0, patch: 0};
ll::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
pub fn revision() -> String {
unsafe {
let rev = ll::SDL_GetRevision();
String::from_utf8_lossy(CStr::from_ptr(rev).to_bytes()).to_string()
}
}
/// Get the revision number of SDL that is linked against your program.
pub fn revision_number() -> i32 {
unsafe {
ll::SDL_GetRevisionNumber()
}
}
|
}
/// Get the version of SDL that is linked against your program.
|
random_line_split
|
version.rs
|
/*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use sys::version as ll;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: ll::SDL_version) -> Version {
Version { major: v.major, minor: v.minor, patch: v.patch }
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
/// Get the version of SDL that is linked against your program.
pub fn version() -> Version {
unsafe {
let mut cver = ll::SDL_version { major: 0, minor: 0, patch: 0};
ll::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
pub fn revision() -> String {
unsafe {
let rev = ll::SDL_GetRevision();
String::from_utf8_lossy(CStr::from_ptr(rev).to_bytes()).to_string()
}
}
/// Get the revision number of SDL that is linked against your program.
pub fn revision_number() -> i32 {
unsafe {
ll::SDL_GetRevisionNumber()
}
}
|
{
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
}
|
identifier_body
|
mod.rs
|
mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struct WatchDevices;
pub struct DevSerialWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
impl DevSerialWatcher {
pub async fn watch_dev_serial(&self) -> Result<()> {
// Normally serial ports are created at /dev/serial/by-id/
loop {
// /dev/serial is only created when a serial port is connected to the computer
block_on_serial_directory_create().await?;
// Once /dev/serial exists watch for new device files in it
watch_device_directory(
"/dev/serial/by-id/",
None,
self.device_manager.clone(),
).await?
}
}
}
#[async_trait::async_trait]
impl Actor for DevSerialWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()>
|
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for DevSerialWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
let result = self.watch_dev_serial().await;
if let Err(err) = result {
warn!("Error watching /dev/serial/by-id/ device files: {:?}", err);
ctx.stop(Some(err));
};
}
}
pub struct KlipperWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
#[async_trait::async_trait]
impl Actor for KlipperWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for KlipperWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
// The Klipper serial port is created in /tmp/printer so it needs a seperate
// watcher.
// If you are configuring multiple klipper printer (is that's even possible?)
// you MUST start each printer's path with /tmp/printer eg. /tmp/printer3
let result = watch_device_directory(
"/tmp/",
Some("printer"),
self.device_manager.clone(),
).await;
if let Err(err) = result {
warn!("Error watching klipper device files: {:?}", err);
ctx.stop(Some(err));
};
}
}
|
{
ctx.address().send(WatchDevices)?;
Ok(())
}
|
identifier_body
|
mod.rs
|
mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struct WatchDevices;
pub struct DevSerialWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
impl DevSerialWatcher {
pub async fn watch_dev_serial(&self) -> Result<()> {
// Normally serial ports are created at /dev/serial/by-id/
loop {
// /dev/serial is only created when a serial port is connected to the computer
block_on_serial_directory_create().await?;
// Once /dev/serial exists watch for new device files in it
watch_device_directory(
"/dev/serial/by-id/",
None,
self.device_manager.clone(),
).await?
}
}
}
#[async_trait::async_trait]
impl Actor for DevSerialWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for DevSerialWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
let result = self.watch_dev_serial().await;
if let Err(err) = result {
|
}
}
pub struct KlipperWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
#[async_trait::async_trait]
impl Actor for KlipperWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for KlipperWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
// The Klipper serial port is created in /tmp/printer so it needs a seperate
// watcher.
// If you are configuring multiple klipper printer (is that's even possible?)
// you MUST start each printer's path with /tmp/printer eg. /tmp/printer3
let result = watch_device_directory(
"/tmp/",
Some("printer"),
self.device_manager.clone(),
).await;
if let Err(err) = result {
warn!("Error watching klipper device files: {:?}", err);
ctx.stop(Some(err));
};
}
}
|
warn!("Error watching /dev/serial/by-id/ device files: {:?}", err);
ctx.stop(Some(err));
};
|
random_line_split
|
mod.rs
|
mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struct WatchDevices;
pub struct DevSerialWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
impl DevSerialWatcher {
pub async fn watch_dev_serial(&self) -> Result<()> {
// Normally serial ports are created at /dev/serial/by-id/
loop {
// /dev/serial is only created when a serial port is connected to the computer
block_on_serial_directory_create().await?;
// Once /dev/serial exists watch for new device files in it
watch_device_directory(
"/dev/serial/by-id/",
None,
self.device_manager.clone(),
).await?
}
}
}
#[async_trait::async_trait]
impl Actor for DevSerialWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for DevSerialWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
let result = self.watch_dev_serial().await;
if let Err(err) = result
|
;
}
}
pub struct KlipperWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
#[async_trait::async_trait]
impl Actor for KlipperWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for KlipperWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
// The Klipper serial port is created in /tmp/printer so it needs a seperate
// watcher.
// If you are configuring multiple klipper printer (is that's even possible?)
// you MUST start each printer's path with /tmp/printer eg. /tmp/printer3
let result = watch_device_directory(
"/tmp/",
Some("printer"),
self.device_manager.clone(),
).await;
if let Err(err) = result {
warn!("Error watching klipper device files: {:?}", err);
ctx.stop(Some(err));
};
}
}
|
{
warn!("Error watching /dev/serial/by-id/ device files: {:?}", err);
ctx.stop(Some(err));
}
|
conditional_block
|
mod.rs
|
mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struct WatchDevices;
pub struct DevSerialWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
impl DevSerialWatcher {
pub async fn
|
(&self) -> Result<()> {
// Normally serial ports are created at /dev/serial/by-id/
loop {
// /dev/serial is only created when a serial port is connected to the computer
block_on_serial_directory_create().await?;
// Once /dev/serial exists watch for new device files in it
watch_device_directory(
"/dev/serial/by-id/",
None,
self.device_manager.clone(),
).await?
}
}
}
#[async_trait::async_trait]
impl Actor for DevSerialWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for DevSerialWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
let result = self.watch_dev_serial().await;
if let Err(err) = result {
warn!("Error watching /dev/serial/by-id/ device files: {:?}", err);
ctx.stop(Some(err));
};
}
}
pub struct KlipperWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
#[async_trait::async_trait]
impl Actor for KlipperWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(())
}
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for KlipperWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
// The Klipper serial port is created in /tmp/printer so it needs a seperate
// watcher.
// If you are configuring multiple klipper printer (is that's even possible?)
// you MUST start each printer's path with /tmp/printer eg. /tmp/printer3
let result = watch_device_directory(
"/tmp/",
Some("printer"),
self.device_manager.clone(),
).await;
if let Err(err) = result {
warn!("Error watching klipper device files: {:?}", err);
ctx.stop(Some(err));
};
}
}
|
watch_dev_serial
|
identifier_name
|
re_set.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! define_set {
($name:ident, $exec_build:expr, $text_ty:ty, $as_bytes:expr) => {
pub mod $name {
use libtww::std::fmt;
use libtww::std::iter;
use libtww::std::slice;
use libtww::std::vec;
use error::Error;
use exec::{Exec, ExecBuilder};
use re_trait::RegularExpression;
/// Match multiple (possibly overlapping) regular expressions in a single scan.
///
/// A regex set corresponds to the union of two or more regular expressions.
/// That is, a regex set will match text where at least one of its
/// constituent regular expressions matches. A regex set as its formulated here
/// provides a touch more power: it will also report *which* regular
/// expressions in the set match. Indeed, this is the key difference between
/// regex sets and a single `Regex` with many alternates, since only one
/// alternate can match at a time.
///
/// For example, consider regular expressions to match email addresses and
/// domains: `[a-z]+@[a-z]+\.(com|org|net)` and `[a-z]+\.(com|org|net)`. If a
/// regex set is constructed from those regexes, then searching the text
/// `[email protected]` will report both regexes as matching. Of course, one
/// could accomplish this by compiling each regex on its own and doing two
/// searches over the text. The key advantage of using a regex set is that it
/// will report the matching regexes using a *single pass through the text*.
/// If one has hundreds or thousands of regexes to match repeatedly (like a URL
/// router for a complex web application or a user agent matcher), then a regex
/// set can realize huge performance gains.
///
/// # Example
///
/// This shows how the above two regexes (for matching email addresses and
/// domains) might work:
///
/// ```rust
/// # use regex::RegexSet;
/// let set = RegexSet::new(&[
/// r"[a-z]+@[a-z]+\.(com|org|net)",
/// r"[a-z]+\.(com|org|net)",
/// ]).unwrap();
///
/// // Ask whether any regexes in the set match.
/// assert!(set.is_match("[email protected]"));
///
/// // Identify which regexes in the set match.
/// let matches: Vec<_> = set.matches("[email protected]").into_iter().collect();
/// assert_eq!(vec![0, 1], matches);
///
/// // Try again, but with text that only matches one of the regexes.
/// let matches: Vec<_> = set.matches("example.com").into_iter().collect();
/// assert_eq!(vec![1], matches);
///
/// // Try again, but with text that doesn't match any regex in the set.
/// let matches: Vec<_> = set.matches("example").into_iter().collect();
/// assert!(matches.is_empty());
/// ```
///
/// Note that it would be possible to adapt the above example to using `Regex`
/// with an expression like:
///
/// ```ignore
/// (?P<email>[a-z]+@(?P<email_domain>[a-z]+[.](com|org|net)))|(?P<domain>[a-z]+[.](com|org|net))
/// ```
///
/// After a match, one could then inspect the capture groups to figure out
/// which alternates matched. The problem is that it is hard to make this
/// approach scale when there are many regexes since the overlap between each
/// alternate isn't always obvious to reason about.
///
/// # Limitations
///
/// Regex sets are limited to answering the following two questions:
///
/// 1. Does any regex in the set match?
/// 2. If so, which regexes in the set match?
///
/// As with the main `Regex` type, it is cheaper to ask (1) instead of (2)
/// since the matching engines can stop after the first match is found.
///
/// Other features like finding the location of successive matches or their
/// sub-captures aren't supported. If you need this functionality, the
/// recommended approach is to compile each regex in the set independently and
/// selectively match them based on which regexes in the set matched.
///
/// # Performance
///
/// A `RegexSet` has the same performance characteristics as `Regex`. Namely,
/// search takes `O(mn)` time, where `m` is proportional to the size of the
/// regex set and `n` is proportional to the length of the search text.
#[derive(Clone)]
pub struct RegexSet(Exec);
impl RegexSet {
/// Create a new regex set with the given regular expressions.
///
/// This takes an iterator of `S`, where `S` is something that can produce
/// a `&str`. If any of the strings in the iterator are not valid regular
/// expressions, then an error is returned.
///
/// # Example
///
/// Create a new regex set from an iterator of strings:
///
/// ```rust
/// # use regex::RegexSet;
/// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap();
/// assert!(set.is_match("foo"));
/// ```
pub fn new<I, S>(exprs: I) -> Result<RegexSet, Error>
where S: AsRef<str>, I: IntoIterator<Item=S> {
let exec = try!($exec_build(exprs));
Ok(RegexSet(exec))
}
/// Returns true if and only if one of the regexes in this set matches
/// the text given.
///
/// This method should be preferred if you only need to test whether any
/// of the regexes in the set should match, but don't care about *which*
/// regexes matched. This is because the underlying matching engine will
/// quit immediately after seeing the first match instead of continuing to
/// find all matches.
///
/// Note that as with searches using `Regex`, the expression is unanchored
/// by default. That is, if the regex does not start with `^` or `\A`, or
/// end with `$` or `\z`, then it is permitted to match anywhere in the
/// text.
///
/// # Example
///
/// Tests whether a set matches some text:
///
/// ```rust
/// # use regex::RegexSet;
/// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap();
/// assert!(set.is_match("foo"));
/// assert!(!set.is_match("☃"));
/// ```
pub fn is_match(&self, text: $text_ty) -> bool {
self.0.searcher().is_match_at($as_bytes(text), 0)
}
/// Returns the set of regular expressions that match in the given text.
///
/// The set returned contains the index of each regular expression that
/// matches in the given text. The index is in correspondence with the
/// order of regular expressions given to `RegexSet`'s constructor.
///
/// The set can also be used to iterate over the matched indices.
///
/// Note that as with searches using `Regex`, the expression is unanchored
/// by default. That is, if the regex does not start with `^` or `\A`, or
/// end with `$` or `\z`, then it is permitted to match anywhere in the
/// text.
///
/// # Example
///
/// Tests which regular expressions match the given text:
///
/// ```rust
/// # use regex::RegexSet;
/// let set = RegexSet::new(&[
/// r"\w+",
/// r"\d+",
/// r"\pL+",
/// r"foo",
/// r"bar",
/// r"barfoo",
/// r"foobar",
/// ]).unwrap();
/// let matches: Vec<_> = set.matches("foobar").into_iter().collect();
/// assert_eq!(matches, vec![0, 2, 3, 4, 6]);
///
/// // You can also test whether a particular regex matched:
/// let matches = set.matches("foobar");
/// assert!(!matches.matched(5));
/// assert!(matches.matched(6));
/// ```
pub fn matches(&self, text: $text_ty) -> SetMatches {
let mut matches = vec![false; self.0.regex_strings().len()];
let any = self.0.searcher().many_matches_at(
&mut matches, $as_bytes(text), 0);
SetMatches {
matched_any: any,
matches: matches,
}
}
/// Returns the total number of regular expressions in this set.
pub fn len(&self) -> usize {
self.0.regex_strings().len()
}
}
/// A set of matches returned by a regex set.
#[derive(Clone, Debug)]
pub struct SetMatches {
matched_any: bool,
matches: Vec<bool>,
}
impl SetMatches {
/// Whether this set contains any matches.
pub fn matched_any(&self) -> bool {
self.matched_any
}
/// Whether the regex at the given index matched.
///
/// The index for a regex is determined by its insertion order upon the
/// initial construction of a `RegexSet`, starting at `0`.
///
/// # Panics
///
/// If `regex_index` is greater than or equal to `self.len()`.
pub fn matched(&self, regex_index: usize) -> bool {
self.matches[regex_index]
}
/// The total number of regexes in the set that created these matches.
pub fn len(&self) -> usize {
self.matches.len()
}
/// Returns an iterator over indexes in the regex that matched.
pub fn iter(&self) -> SetMatchesIter {
SetMatchesIter((&*self.matches).into_iter().enumerate())
}
}
impl IntoIterator for SetMatches {
type IntoIter = SetMatchesIntoIter;
type Item = usize;
fn into_iter(self) -> Self::IntoIter {
SetMatchesIntoIter(self.matches.into_iter().enumerate())
}
}
impl<'a> IntoIterator for &'a SetMatches {
type IntoIter = SetMatchesIter<'a>;
type Item = usize;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// An owned iterator over the set of matches from a regex set.
pub struct SetMatchesIntoIter(iter::Enumerate<vec::IntoIter<bool>>);
impl Iterator for SetMatchesIntoIter {
type Item = usize;
fn next(&mut self) -> Option<usize> {
loop {
match self.0.next() {
None => return None,
Some((_, false)) => {}
Some((i, true)) => return Some(i),
}
}
}
}
impl DoubleEndedIterator for SetMatchesIntoIter {
fn next_back(&mut self) -> Option<usize> {
loop {
match self.0.next_back() {
None => return None,
Some((_, false)) => {}
Some((i, true)) => return Some(i),
}
}
}
}
/// A borrowed iterator over the set of matches from a regex set.
///
/// The lifetime `'a` refers to the lifetime of a `SetMatches` value.
#[derive(Clone)]
pub struct SetMatchesIter<'a>(iter::Enumerate<slice::Iter<'a, bool>>);
impl<'a> Iterator for SetMatchesIter<'a> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
loop {
match self.0.next() {
None => return None,
Some((_, &false)) => {}
Some((i, &true)) => return Some(i),
}
}
}
}
impl<'a> DoubleEndedIterator for SetMatchesIter<'a> {
fn next_back(&mut self) -> Option<usize> {
loop {
match self.0.next_back() {
None => return None,
Some((_, &false)) => {}
Some((i, &true)) => return Some(i),
}
}
}
}
#[doc(hidden)]
impl From<Exec> for RegexSet {
fn from(exec: Exec) -> Self {
RegexSet(exec)
}
}
impl fmt::Debug for RegexSet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "RegexSet({:?})", self.0.regex_strings())
}
}
#[allow(dead_code)] fn as_bytes_str(text: &str) -> &[u8] { text.as_bytes() }
#[allow(dead_code)] fn as_bytes_bytes(text: &[u8]) -> &[u8] { text }
}
}
}
define_set! {
unicode,
|exprs| ExecBuilder::new_many(exprs).build(),
&str,
as_bytes_str
|
define_set! {
bytes,
|exprs| ExecBuilder::new_many(exprs).only_utf8(false).build(),
&[u8],
as_bytes_bytes
}
|
}
|
random_line_split
|
indexed_vec.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt::Debug;
use std::iter::FromIterator;
use std::slice;
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::fmt;
use std::vec;
use std::u32;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
/// Represents some newtyped `usize` wrapper.
///
/// (purpose: avoid mixing indexes for different bitvector domains.)
pub trait Idx: Copy +'static + Eq + Debug {
fn new(idx: usize) -> Self;
fn index(self) -> usize;
}
impl Idx for usize {
fn new(idx: usize) -> Self { idx }
fn index(self) -> usize { self }
}
impl Idx for u32 {
fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
fn index(self) -> usize { self as usize }
}
#[derive(Clone)]
pub struct IndexVec<I: Idx, T> {
pub raw: Vec<T>,
_marker: PhantomData<Fn(&I)>
}
impl<I, T> Serialize for IndexVec<I, T>
where I: Idx,
T: Serialize
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.raw.serialize(serializer)
}
}
impl<'de, I, T> Deserialize<'de> for IndexVec<I, T>
where I: Idx,
T: Deserialize<'de>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Deserialize::deserialize(deserializer).map(|v| {
IndexVec { raw: v, _marker: PhantomData }
})
}
}
impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.raw, fmt)
}
}
impl<I: Idx, T> IndexVec<I, T> {
#[inline]
pub fn new() -> Self {
IndexVec { raw: Vec::new(), _marker: PhantomData }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
}
#[inline]
pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
where T: Clone
{
IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
}
#[inline]
pub fn from_elem_n(elem: T, n: usize) -> Self
where T: Clone
{
IndexVec { raw: vec![elem; n], _marker: PhantomData }
}
#[inline]
pub fn push(&mut self, d: T) -> I {
let idx = I::new(self.len());
self.raw.push(d);
idx
}
#[inline]
pub fn len(&self) -> usize {
self.raw.len()
}
#[inline]
pub fn
|
(&self) -> bool {
self.raw.is_empty()
}
#[inline]
pub fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
#[inline]
pub fn iter(&self) -> slice::Iter<T> {
self.raw.iter()
}
#[inline]
pub fn iter_mut(&mut self) -> slice::IterMut<T> {
self.raw.iter_mut()
}
#[inline]
pub fn last(&self) -> Option<I> {
self.len().checked_sub(1).map(I::new)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.raw.shrink_to_fit()
}
#[inline]
pub fn swap(&mut self, a: usize, b: usize) {
self.raw.swap(a, b)
}
#[inline]
pub fn truncate(&mut self, a: usize) {
self.raw.truncate(a)
}
#[inline]
pub fn get(&self, index: I) -> Option<&T> {
self.raw.get(index.index())
}
#[inline]
pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
self.raw.get_mut(index.index())
}
}
impl<I: Idx, T: Clone> IndexVec<I, T> {
#[inline]
pub fn resize(&mut self, new_len: usize, value: T) {
self.raw.resize(new_len, value)
}
}
impl<I: Idx, T> Index<I> for IndexVec<I, T> {
type Output = T;
#[inline]
fn index(&self, index: I) -> &T {
&self.raw[index.index()]
}
}
impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut T {
&mut self.raw[index.index()]
}
}
impl<I: Idx, T> Default for IndexVec<I, T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
#[inline]
fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
self.raw.extend(iter);
}
}
impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
#[inline]
fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
}
}
impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
type Item = T;
type IntoIter = vec::IntoIter<T>;
#[inline]
fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
}
impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
#[inline]
fn into_iter(self) -> slice::Iter<'a, T> {
self.raw.iter()
}
}
impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, T>;
#[inline]
fn into_iter(mut self) -> slice::IterMut<'a, T> {
self.raw.iter_mut()
}
}
|
is_empty
|
identifier_name
|
indexed_vec.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt::Debug;
use std::iter::FromIterator;
use std::slice;
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::fmt;
use std::vec;
use std::u32;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
/// Represents some newtyped `usize` wrapper.
///
/// (purpose: avoid mixing indexes for different bitvector domains.)
pub trait Idx: Copy +'static + Eq + Debug {
fn new(idx: usize) -> Self;
fn index(self) -> usize;
}
impl Idx for usize {
fn new(idx: usize) -> Self { idx }
fn index(self) -> usize { self }
}
impl Idx for u32 {
fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
fn index(self) -> usize { self as usize }
}
#[derive(Clone)]
pub struct IndexVec<I: Idx, T> {
pub raw: Vec<T>,
_marker: PhantomData<Fn(&I)>
}
impl<I, T> Serialize for IndexVec<I, T>
where I: Idx,
T: Serialize
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.raw.serialize(serializer)
}
}
impl<'de, I, T> Deserialize<'de> for IndexVec<I, T>
where I: Idx,
T: Deserialize<'de>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Deserialize::deserialize(deserializer).map(|v| {
IndexVec { raw: v, _marker: PhantomData }
})
}
}
impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.raw, fmt)
}
}
impl<I: Idx, T> IndexVec<I, T> {
#[inline]
pub fn new() -> Self {
IndexVec { raw: Vec::new(), _marker: PhantomData }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
}
#[inline]
pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
where T: Clone
{
IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
}
#[inline]
pub fn from_elem_n(elem: T, n: usize) -> Self
where T: Clone
{
IndexVec { raw: vec![elem; n], _marker: PhantomData }
}
#[inline]
pub fn push(&mut self, d: T) -> I {
let idx = I::new(self.len());
self.raw.push(d);
idx
}
#[inline]
pub fn len(&self) -> usize {
self.raw.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
#[inline]
pub fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
#[inline]
pub fn iter(&self) -> slice::Iter<T> {
self.raw.iter()
}
#[inline]
pub fn iter_mut(&mut self) -> slice::IterMut<T> {
self.raw.iter_mut()
}
#[inline]
pub fn last(&self) -> Option<I> {
self.len().checked_sub(1).map(I::new)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.raw.shrink_to_fit()
}
#[inline]
pub fn swap(&mut self, a: usize, b: usize) {
self.raw.swap(a, b)
}
#[inline]
pub fn truncate(&mut self, a: usize) {
self.raw.truncate(a)
}
#[inline]
pub fn get(&self, index: I) -> Option<&T> {
self.raw.get(index.index())
}
#[inline]
pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
self.raw.get_mut(index.index())
}
}
impl<I: Idx, T: Clone> IndexVec<I, T> {
#[inline]
pub fn resize(&mut self, new_len: usize, value: T) {
self.raw.resize(new_len, value)
}
}
impl<I: Idx, T> Index<I> for IndexVec<I, T> {
|
&self.raw[index.index()]
}
}
impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut T {
&mut self.raw[index.index()]
}
}
impl<I: Idx, T> Default for IndexVec<I, T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
#[inline]
fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
self.raw.extend(iter);
}
}
impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
#[inline]
fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
}
}
impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
type Item = T;
type IntoIter = vec::IntoIter<T>;
#[inline]
fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
}
impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
#[inline]
fn into_iter(self) -> slice::Iter<'a, T> {
self.raw.iter()
}
}
impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, T>;
#[inline]
fn into_iter(mut self) -> slice::IterMut<'a, T> {
self.raw.iter_mut()
}
}
|
type Output = T;
#[inline]
fn index(&self, index: I) -> &T {
|
random_line_split
|
indexed_vec.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt::Debug;
use std::iter::FromIterator;
use std::slice;
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::fmt;
use std::vec;
use std::u32;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
/// Represents some newtyped `usize` wrapper.
///
/// (purpose: avoid mixing indexes for different bitvector domains.)
pub trait Idx: Copy +'static + Eq + Debug {
fn new(idx: usize) -> Self;
fn index(self) -> usize;
}
impl Idx for usize {
fn new(idx: usize) -> Self { idx }
fn index(self) -> usize { self }
}
impl Idx for u32 {
fn new(idx: usize) -> Self { assert!(idx <= u32::MAX as usize); idx as u32 }
fn index(self) -> usize { self as usize }
}
#[derive(Clone)]
pub struct IndexVec<I: Idx, T> {
pub raw: Vec<T>,
_marker: PhantomData<Fn(&I)>
}
impl<I, T> Serialize for IndexVec<I, T>
where I: Idx,
T: Serialize
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
self.raw.serialize(serializer)
}
}
impl<'de, I, T> Deserialize<'de> for IndexVec<I, T>
where I: Idx,
T: Deserialize<'de>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Deserialize::deserialize(deserializer).map(|v| {
IndexVec { raw: v, _marker: PhantomData }
})
}
}
impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.raw, fmt)
}
}
impl<I: Idx, T> IndexVec<I, T> {
#[inline]
pub fn new() -> Self {
IndexVec { raw: Vec::new(), _marker: PhantomData }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Self {
IndexVec { raw: Vec::with_capacity(capacity), _marker: PhantomData }
}
#[inline]
pub fn from_elem<S>(elem: T, universe: &IndexVec<I, S>) -> Self
where T: Clone
{
IndexVec { raw: vec![elem; universe.len()], _marker: PhantomData }
}
#[inline]
pub fn from_elem_n(elem: T, n: usize) -> Self
where T: Clone
{
IndexVec { raw: vec![elem; n], _marker: PhantomData }
}
#[inline]
pub fn push(&mut self, d: T) -> I {
let idx = I::new(self.len());
self.raw.push(d);
idx
}
#[inline]
pub fn len(&self) -> usize {
self.raw.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
#[inline]
pub fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
#[inline]
pub fn iter(&self) -> slice::Iter<T> {
self.raw.iter()
}
#[inline]
pub fn iter_mut(&mut self) -> slice::IterMut<T> {
self.raw.iter_mut()
}
#[inline]
pub fn last(&self) -> Option<I> {
self.len().checked_sub(1).map(I::new)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.raw.shrink_to_fit()
}
#[inline]
pub fn swap(&mut self, a: usize, b: usize) {
self.raw.swap(a, b)
}
#[inline]
pub fn truncate(&mut self, a: usize) {
self.raw.truncate(a)
}
#[inline]
pub fn get(&self, index: I) -> Option<&T> {
self.raw.get(index.index())
}
#[inline]
pub fn get_mut(&mut self, index: I) -> Option<&mut T> {
self.raw.get_mut(index.index())
}
}
impl<I: Idx, T: Clone> IndexVec<I, T> {
#[inline]
pub fn resize(&mut self, new_len: usize, value: T) {
self.raw.resize(new_len, value)
}
}
impl<I: Idx, T> Index<I> for IndexVec<I, T> {
type Output = T;
#[inline]
fn index(&self, index: I) -> &T {
&self.raw[index.index()]
}
}
impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut T {
&mut self.raw[index.index()]
}
}
impl<I: Idx, T> Default for IndexVec<I, T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<I: Idx, T> Extend<T> for IndexVec<I, T> {
#[inline]
fn extend<J: IntoIterator<Item = T>>(&mut self, iter: J) {
self.raw.extend(iter);
}
}
impl<I: Idx, T> FromIterator<T> for IndexVec<I, T> {
#[inline]
fn from_iter<J>(iter: J) -> Self where J: IntoIterator<Item=T> {
IndexVec { raw: FromIterator::from_iter(iter), _marker: PhantomData }
}
}
impl<I: Idx, T> IntoIterator for IndexVec<I, T> {
type Item = T;
type IntoIter = vec::IntoIter<T>;
#[inline]
fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
}
impl<'a, I: Idx, T> IntoIterator for &'a IndexVec<I, T> {
type Item = &'a T;
type IntoIter = slice::Iter<'a, T>;
#[inline]
fn into_iter(self) -> slice::Iter<'a, T>
|
}
impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, T>;
#[inline]
fn into_iter(mut self) -> slice::IterMut<'a, T> {
self.raw.iter_mut()
}
}
|
{
self.raw.iter()
}
|
identifier_body
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "style_traits"]
#![crate_type = "rlib"]
#![deny(unsafe_code, missing_docs)]
#![cfg_attr(feature = "servo", feature(plugin))]
extern crate app_units;
#[macro_use]
extern crate cssparser;
extern crate euclid;
#[cfg(feature = "servo")] extern crate heapsize;
#[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive;
extern crate rustc_serialize;
#[cfg(feature = "servo")] #[macro_use] extern crate serde_derive;
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from `TNode`.
pub type UnsafeNode = (usize, usize);
/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// `ViewportPx` is equal to `ScreenPx` times a "page zoom" factor controlled by the user. This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one `PagePx` is equal to one `ScreenPx`. However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[derive(Clone, Copy, Debug)]
pub enum ViewportPx {}
/// One CSS "px" in the root coordinate system for the content document.
///
/// `PagePx` is equal to `ViewportPx` multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[derive(Clone, Copy, Debug)]
pub enum PagePx {}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
|
pub mod cursor;
#[macro_use]
pub mod values;
pub mod viewport;
pub use values::ToCss;
|
random_line_split
|
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "style_traits"]
#![crate_type = "rlib"]
#![deny(unsafe_code, missing_docs)]
#![cfg_attr(feature = "servo", feature(plugin))]
extern crate app_units;
#[macro_use]
extern crate cssparser;
extern crate euclid;
#[cfg(feature = "servo")] extern crate heapsize;
#[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive;
extern crate rustc_serialize;
#[cfg(feature = "servo")] #[macro_use] extern crate serde_derive;
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from `TNode`.
pub type UnsafeNode = (usize, usize);
/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// `ViewportPx` is equal to `ScreenPx` times a "page zoom" factor controlled by the user. This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one `PagePx` is equal to one `ScreenPx`. However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[derive(Clone, Copy, Debug)]
pub enum ViewportPx {}
/// One CSS "px" in the root coordinate system for the content document.
///
/// `PagePx` is equal to `ViewportPx` multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[derive(Clone, Copy, Debug)]
pub enum
|
{}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
pub mod cursor;
#[macro_use]
pub mod values;
pub mod viewport;
pub use values::ToCss;
|
PagePx
|
identifier_name
|
color.rs
|
use crate::{
DocumentSelector, DynamicRegistrationClientCapabilities, PartialResultParams, Range,
TextDocumentIdentifier, TextEdit, WorkDoneProgressParams,
};
use serde::{Deserialize, Serialize};
pub type DocumentColorClientCapabilities = DynamicRegistrationClientCapabilities;
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorProviderOptions {}
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StaticTextDocumentColorProviderOptions {
/// A document selector to identify the scope of the registration. If set to null
/// the document selector provided on the client side will be used.
pub document_selector: Option<DocumentSelector>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ColorProviderCapability {
Simple(bool),
ColorProvider(ColorProviderOptions),
Options(StaticTextDocumentColorProviderOptions),
}
impl From<ColorProviderOptions> for ColorProviderCapability {
fn from(from: ColorProviderOptions) -> Self {
Self::ColorProvider(from)
}
}
impl From<StaticTextDocumentColorProviderOptions> for ColorProviderCapability {
fn from(from: StaticTextDocumentColorProviderOptions) -> Self {
Self::Options(from)
}
}
impl From<bool> for ColorProviderCapability {
fn from(from: bool) -> Self {
Self::Simple(from)
}
}
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct
|
{
/// The text document
pub text_document: TextDocumentIdentifier,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorInformation {
/// The range in the document where this color appears.
pub range: Range,
/// The actual color value for this color range.
pub color: Color,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Color {
/// The red component of this color in the range [0-1].
pub red: f32,
/// The green component of this color in the range [0-1].
pub green: f32,
/// The blue component of this color in the range [0-1].
pub blue: f32,
/// The alpha component of this color in the range [0-1].
pub alpha: f32,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorPresentationParams {
/// The text document.
pub text_document: TextDocumentIdentifier,
/// The color information to request presentations for.
pub color: Color,
/// The range where the color would be inserted. Serves as a context.
pub range: Range,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ColorPresentation {
/// The label of this color presentation. It will be shown on the color
/// picker header. By default this is also the text that is inserted when selecting
/// this color presentation.
pub label: String,
/// An [edit](#TextEdit) which is applied to a document when selecting
/// this presentation for the color. When `falsy` the [label](#ColorPresentation.label)
/// is used.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_edit: Option<TextEdit>,
/// An optional array of additional [text edits](#TextEdit) that are applied when
/// selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves.
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_text_edits: Option<Vec<TextEdit>>,
}
|
DocumentColorParams
|
identifier_name
|
color.rs
|
use crate::{
DocumentSelector, DynamicRegistrationClientCapabilities, PartialResultParams, Range,
TextDocumentIdentifier, TextEdit, WorkDoneProgressParams,
};
use serde::{Deserialize, Serialize};
pub type DocumentColorClientCapabilities = DynamicRegistrationClientCapabilities;
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorProviderOptions {}
|
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StaticTextDocumentColorProviderOptions {
/// A document selector to identify the scope of the registration. If set to null
/// the document selector provided on the client side will be used.
pub document_selector: Option<DocumentSelector>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
}
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum ColorProviderCapability {
Simple(bool),
ColorProvider(ColorProviderOptions),
Options(StaticTextDocumentColorProviderOptions),
}
impl From<ColorProviderOptions> for ColorProviderCapability {
fn from(from: ColorProviderOptions) -> Self {
Self::ColorProvider(from)
}
}
impl From<StaticTextDocumentColorProviderOptions> for ColorProviderCapability {
fn from(from: StaticTextDocumentColorProviderOptions) -> Self {
Self::Options(from)
}
}
impl From<bool> for ColorProviderCapability {
fn from(from: bool) -> Self {
Self::Simple(from)
}
}
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentColorParams {
/// The text document
pub text_document: TextDocumentIdentifier,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorInformation {
/// The range in the document where this color appears.
pub range: Range,
/// The actual color value for this color range.
pub color: Color,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Color {
/// The red component of this color in the range [0-1].
pub red: f32,
/// The green component of this color in the range [0-1].
pub green: f32,
/// The blue component of this color in the range [0-1].
pub blue: f32,
/// The alpha component of this color in the range [0-1].
pub alpha: f32,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ColorPresentationParams {
/// The text document.
pub text_document: TextDocumentIdentifier,
/// The color information to request presentations for.
pub color: Color,
/// The range where the color would be inserted. Serves as a context.
pub range: Range,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ColorPresentation {
/// The label of this color presentation. It will be shown on the color
/// picker header. By default this is also the text that is inserted when selecting
/// this color presentation.
pub label: String,
/// An [edit](#TextEdit) which is applied to a document when selecting
/// this presentation for the color. When `falsy` the [label](#ColorPresentation.label)
/// is used.
#[serde(skip_serializing_if = "Option::is_none")]
pub text_edit: Option<TextEdit>,
/// An optional array of additional [text edits](#TextEdit) that are applied when
/// selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves.
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_text_edits: Option<Vec<TextEdit>>,
}
|
random_line_split
|
|
x86.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os)
-> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsiOS => {
"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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsWindows => {
"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string()
}
abi::OsLinux => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsAndroid => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsFreebsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsDragonfly => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsOpenbsd =>
|
},
target_triple: target_triple,
cc_args: vec!("-m32".to_string()),
};
}
|
{
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
|
conditional_block
|
x86.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn
|
(target_triple: String, target_os: abi::Os)
-> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsiOS => {
"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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsWindows => {
"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string()
}
abi::OsLinux => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsAndroid => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsFreebsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsDragonfly => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsOpenbsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
},
target_triple: target_triple,
cc_args: vec!("-m32".to_string()),
};
}
|
get_target_strs
|
identifier_name
|
x86.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os)
-> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsiOS => {
"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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsWindows => {
"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string()
}
abi::OsLinux => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsAndroid => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsFreebsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsDragonfly => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsOpenbsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
},
|
target_triple: target_triple,
cc_args: vec!("-m32".to_string()),
};
}
|
random_line_split
|
|
x86.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os)
-> target_strs::t
|
abi::OsWindows => {
"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string()
}
abi::OsLinux => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsAndroid => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsFreebsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsDragonfly => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsOpenbsd => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
},
target_triple: target_triple,
cc_args: vec!("-m32".to_string()),
};
}
|
{
return target_strs::t {
module_asm: "".to_string(),
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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
abi::OsiOS => {
"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-a:0:64-f80:128:128\
-n8:16:32".to_string()
}
|
identifier_body
|
http2.rs
|
extern crate hyper;
extern crate futures;
extern crate tokio_tls;
extern crate native_tls;
extern crate tokio_core;
extern crate httpbis;
extern crate tls_api_openssl;
use std::thread;
use std::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_core::reactor::Core;
use futures::{future, Stream, Future};
use tls_api_openssl::TlsAcceptor;
struct Proxy4Http2 {
routes: Arc<Vec<String>>,
roundrobin_counter: Arc<AtomicUsize>,
}
impl Proxy4Http2 {
fn new(routes: Vec<String>) -> Self
|
}
impl httpbis::Service for Proxy4Http2 {
fn start_request(&self, headers: httpbis::Headers, _req: httpbis::HttpPartStream)
-> httpbis::Response
{
let mut core = Core::new().expect("http2 backend client core error");
let handle = core.handle();
let backend_client = hyper::Client::new(&handle);
// FIXME: only use index 0
let backend_index = self.roundrobin_counter.fetch_add(1, Ordering::Relaxed);
let backend_addr = self.routes[backend_index % self.routes.len()].clone();
let url_str = format!("http://{}{}", backend_addr, headers.path());
let url = url_str.parse::<hyper::Uri>().expect("uri error");
let proxied_req = hyper::client::Request::new(
hyper::Method::from_str(headers.method()).expect("invalid method"), url);
let mut backend_req_headers = hyper::header::Headers::new();
for req_header in headers.0 {
if req_header.name()[0] as char == ':' {
continue;
}
backend_req_headers.set_raw(
String::from_utf8(req_header.name().into()).unwrap(),
req_header.value());
}
// TODO: set request body
//proxied_req.set_body(req.body());
// NOTE: sync request/response
let req = backend_client.request(proxied_req);
let work = req.and_then(|res| {
Ok(res)
});
let backend_resp = core.run(work).expect("backend client error");
// set origin status code and headers
let mut resp_headers = httpbis::Headers::from_status(
backend_resp.status().as_u16() as u32);
for header in backend_resp.headers().iter() {
match header.name().to_lowercase().as_str() {
"host" | "connection" => continue,
_ => {}
}
resp_headers.add(header.name().to_lowercase().as_str(), header.value_string().as_str());
}
// read body and set http2 response body
let body: Vec<u8> = vec![];
let w = backend_resp.body().fold(body, |mut acc, chunk| {
acc.extend_from_slice(chunk.as_ref());
Ok::<_, hyper::Error>(acc)
}).and_then(move |body_vec| {
future::ok(body_vec)
});
let body = core.run(w).expect("backend client error");
let b = String::from_utf8(body).unwrap();
httpbis::Response::headers_and_bytes(resp_headers, b)
}
}
pub fn spawn_proxy(routes: Vec<String>, addr_str: String, acceptor: TlsAcceptor) -> thread::JoinHandle<()> {
thread::spawn(move || {
let addr: SocketAddr = addr_str.as_str().parse().unwrap();
let port = addr.port();
let host = addr.ip();
let mut conf = httpbis::ServerConf::new();
conf.alpn = Some(httpbis::ServerAlpn::Require);
let mut server = httpbis::ServerBuilder::new();
server.set_port(port);
server.set_tls(acceptor);
server.conf = conf;
server.service.set_service("/", Arc::new(Proxy4Http2::new(routes)));
let server = server.build().expect("http2 server build error");
println!("Listening on {}:{} with http2", host, server.local_addr().port());
loop {
thread::park();
}
})
}
|
{
Self {
routes: Arc::new(routes),
roundrobin_counter: Arc::new(AtomicUsize::new(0)),
}
}
|
identifier_body
|
http2.rs
|
extern crate hyper;
extern crate futures;
extern crate tokio_tls;
extern crate native_tls;
extern crate tokio_core;
extern crate httpbis;
extern crate tls_api_openssl;
use std::thread;
use std::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_core::reactor::Core;
use futures::{future, Stream, Future};
use tls_api_openssl::TlsAcceptor;
struct Proxy4Http2 {
routes: Arc<Vec<String>>,
roundrobin_counter: Arc<AtomicUsize>,
}
impl Proxy4Http2 {
fn new(routes: Vec<String>) -> Self {
Self {
routes: Arc::new(routes),
roundrobin_counter: Arc::new(AtomicUsize::new(0)),
}
}
}
impl httpbis::Service for Proxy4Http2 {
fn start_request(&self, headers: httpbis::Headers, _req: httpbis::HttpPartStream)
-> httpbis::Response
{
let mut core = Core::new().expect("http2 backend client core error");
let handle = core.handle();
let backend_client = hyper::Client::new(&handle);
|
let url = url_str.parse::<hyper::Uri>().expect("uri error");
let proxied_req = hyper::client::Request::new(
hyper::Method::from_str(headers.method()).expect("invalid method"), url);
let mut backend_req_headers = hyper::header::Headers::new();
for req_header in headers.0 {
if req_header.name()[0] as char == ':' {
continue;
}
backend_req_headers.set_raw(
String::from_utf8(req_header.name().into()).unwrap(),
req_header.value());
}
// TODO: set request body
//proxied_req.set_body(req.body());
// NOTE: sync request/response
let req = backend_client.request(proxied_req);
let work = req.and_then(|res| {
Ok(res)
});
let backend_resp = core.run(work).expect("backend client error");
// set origin status code and headers
let mut resp_headers = httpbis::Headers::from_status(
backend_resp.status().as_u16() as u32);
for header in backend_resp.headers().iter() {
match header.name().to_lowercase().as_str() {
"host" | "connection" => continue,
_ => {}
}
resp_headers.add(header.name().to_lowercase().as_str(), header.value_string().as_str());
}
// read body and set http2 response body
let body: Vec<u8> = vec![];
let w = backend_resp.body().fold(body, |mut acc, chunk| {
acc.extend_from_slice(chunk.as_ref());
Ok::<_, hyper::Error>(acc)
}).and_then(move |body_vec| {
future::ok(body_vec)
});
let body = core.run(w).expect("backend client error");
let b = String::from_utf8(body).unwrap();
httpbis::Response::headers_and_bytes(resp_headers, b)
}
}
pub fn spawn_proxy(routes: Vec<String>, addr_str: String, acceptor: TlsAcceptor) -> thread::JoinHandle<()> {
thread::spawn(move || {
let addr: SocketAddr = addr_str.as_str().parse().unwrap();
let port = addr.port();
let host = addr.ip();
let mut conf = httpbis::ServerConf::new();
conf.alpn = Some(httpbis::ServerAlpn::Require);
let mut server = httpbis::ServerBuilder::new();
server.set_port(port);
server.set_tls(acceptor);
server.conf = conf;
server.service.set_service("/", Arc::new(Proxy4Http2::new(routes)));
let server = server.build().expect("http2 server build error");
println!("Listening on {}:{} with http2", host, server.local_addr().port());
loop {
thread::park();
}
})
}
|
// FIXME: only use index 0
let backend_index = self.roundrobin_counter.fetch_add(1, Ordering::Relaxed);
let backend_addr = self.routes[backend_index % self.routes.len()].clone();
let url_str = format!("http://{}{}", backend_addr, headers.path());
|
random_line_split
|
http2.rs
|
extern crate hyper;
extern crate futures;
extern crate tokio_tls;
extern crate native_tls;
extern crate tokio_core;
extern crate httpbis;
extern crate tls_api_openssl;
use std::thread;
use std::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_core::reactor::Core;
use futures::{future, Stream, Future};
use tls_api_openssl::TlsAcceptor;
struct Proxy4Http2 {
routes: Arc<Vec<String>>,
roundrobin_counter: Arc<AtomicUsize>,
}
impl Proxy4Http2 {
fn new(routes: Vec<String>) -> Self {
Self {
routes: Arc::new(routes),
roundrobin_counter: Arc::new(AtomicUsize::new(0)),
}
}
}
impl httpbis::Service for Proxy4Http2 {
fn
|
(&self, headers: httpbis::Headers, _req: httpbis::HttpPartStream)
-> httpbis::Response
{
let mut core = Core::new().expect("http2 backend client core error");
let handle = core.handle();
let backend_client = hyper::Client::new(&handle);
// FIXME: only use index 0
let backend_index = self.roundrobin_counter.fetch_add(1, Ordering::Relaxed);
let backend_addr = self.routes[backend_index % self.routes.len()].clone();
let url_str = format!("http://{}{}", backend_addr, headers.path());
let url = url_str.parse::<hyper::Uri>().expect("uri error");
let proxied_req = hyper::client::Request::new(
hyper::Method::from_str(headers.method()).expect("invalid method"), url);
let mut backend_req_headers = hyper::header::Headers::new();
for req_header in headers.0 {
if req_header.name()[0] as char == ':' {
continue;
}
backend_req_headers.set_raw(
String::from_utf8(req_header.name().into()).unwrap(),
req_header.value());
}
// TODO: set request body
//proxied_req.set_body(req.body());
// NOTE: sync request/response
let req = backend_client.request(proxied_req);
let work = req.and_then(|res| {
Ok(res)
});
let backend_resp = core.run(work).expect("backend client error");
// set origin status code and headers
let mut resp_headers = httpbis::Headers::from_status(
backend_resp.status().as_u16() as u32);
for header in backend_resp.headers().iter() {
match header.name().to_lowercase().as_str() {
"host" | "connection" => continue,
_ => {}
}
resp_headers.add(header.name().to_lowercase().as_str(), header.value_string().as_str());
}
// read body and set http2 response body
let body: Vec<u8> = vec![];
let w = backend_resp.body().fold(body, |mut acc, chunk| {
acc.extend_from_slice(chunk.as_ref());
Ok::<_, hyper::Error>(acc)
}).and_then(move |body_vec| {
future::ok(body_vec)
});
let body = core.run(w).expect("backend client error");
let b = String::from_utf8(body).unwrap();
httpbis::Response::headers_and_bytes(resp_headers, b)
}
}
pub fn spawn_proxy(routes: Vec<String>, addr_str: String, acceptor: TlsAcceptor) -> thread::JoinHandle<()> {
thread::spawn(move || {
let addr: SocketAddr = addr_str.as_str().parse().unwrap();
let port = addr.port();
let host = addr.ip();
let mut conf = httpbis::ServerConf::new();
conf.alpn = Some(httpbis::ServerAlpn::Require);
let mut server = httpbis::ServerBuilder::new();
server.set_port(port);
server.set_tls(acceptor);
server.conf = conf;
server.service.set_service("/", Arc::new(Proxy4Http2::new(routes)));
let server = server.build().expect("http2 server build error");
println!("Listening on {}:{} with http2", host, server.local_addr().port());
loop {
thread::park();
}
})
}
|
start_request
|
identifier_name
|
io.rs
|
use std::os::raw::{c_char, c_void};
use std::mem::transmute;
use super::CFixedString;
#[repr(C)]
pub enum
|
{
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub write_double: fn(priv_data: *mut c_void, data: f64),
pub write_string: fn(priv_data: *mut c_void, data: *const c_char),
}
pub struct StateSaver<'a>(&'a mut CPDSaveState);
impl<'a> StateSaver<'a> {
pub fn new(api: *mut CPDSaveState) -> StateSaver<'a> {
unsafe { StateSaver(&mut *api) }
}
pub fn write_int(&mut self, data: i64) {
((*self.0).write_int)((*self.0).priv_data, data)
}
pub fn write_double(&mut self, data: f64) {
((*self.0).write_double)((*self.0).priv_data, data)
}
pub fn write_str(&mut self, data: &str) {
let str = CFixedString::from_str(data);
((*self.0).write_string)((*self.0).priv_data, str.as_ptr())
}
}
#[repr(C)]
pub struct CPDLoadState {
pub priv_data: *mut c_void,
pub read_int: fn(priv_data: *mut c_void, dest: *mut i64) -> LoadState,
pub read_double: fn(priv_data: *mut c_void, dest: *mut f64) -> LoadState,
pub read_string: fn(priv_data: *mut c_void, dest: *mut c_char, max_len: i32) -> LoadState,
pub read_string_len: fn(priv_data: *const c_void, len: *mut i32) -> LoadState,
}
pub enum LoadResult<T> {
Ok(T),
Fail,
Converted(T),
Truncated(T),
OutOfData,
}
impl<T> LoadResult<T> {
pub fn from_state(state: LoadState, val: T) -> LoadResult<T> {
match state {
LoadState::Ok => LoadResult::Ok(val),
LoadState::Converted => LoadResult::Converted(val),
LoadState::Truncated => LoadResult::Truncated(val),
LoadState::Fail => LoadResult::Fail,
LoadState::OutOfData => LoadResult::OutOfData,
}
}
}
pub struct StateLoader<'a>(&'a mut CPDLoadState);
impl<'a> StateLoader<'a> {
pub fn new(api: *mut CPDLoadState) -> StateLoader<'a> {
unsafe { StateLoader(&mut *api) }
}
pub fn read_int(&mut self) -> LoadResult<i64> {
let mut res: i64 = 0;
let state = ((*self.0).read_int)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pub fn read_f64(&mut self) -> LoadResult<f64> {
let mut res: f64 = 0.0;
let state = ((*self.0).read_double)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pub fn read_string(&mut self) -> LoadResult<String> {
let mut len: i32 = 0;
let len_state = ((*self.0).read_string_len)((*self.0).priv_data, &mut len);
match len_state {
LoadState::Fail => return LoadResult::Fail,
LoadState::OutOfData => return LoadResult::OutOfData,
_ => {}
}
let mut buf = vec!(0u8; len as usize);
let state = unsafe {
((*self.0).read_string)((*self.0).priv_data, transmute(buf.as_mut_ptr()), len)
};
LoadResult::from_state(state, String::from_utf8(buf).unwrap())
}
}
|
LoadState
|
identifier_name
|
io.rs
|
use std::os::raw::{c_char, c_void};
use std::mem::transmute;
use super::CFixedString;
#[repr(C)]
pub enum LoadState {
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub write_double: fn(priv_data: *mut c_void, data: f64),
pub write_string: fn(priv_data: *mut c_void, data: *const c_char),
}
pub struct StateSaver<'a>(&'a mut CPDSaveState);
impl<'a> StateSaver<'a> {
pub fn new(api: *mut CPDSaveState) -> StateSaver<'a> {
unsafe { StateSaver(&mut *api) }
}
pub fn write_int(&mut self, data: i64) {
((*self.0).write_int)((*self.0).priv_data, data)
}
pub fn write_double(&mut self, data: f64) {
((*self.0).write_double)((*self.0).priv_data, data)
}
pub fn write_str(&mut self, data: &str) {
let str = CFixedString::from_str(data);
((*self.0).write_string)((*self.0).priv_data, str.as_ptr())
}
}
#[repr(C)]
pub struct CPDLoadState {
pub priv_data: *mut c_void,
pub read_int: fn(priv_data: *mut c_void, dest: *mut i64) -> LoadState,
pub read_double: fn(priv_data: *mut c_void, dest: *mut f64) -> LoadState,
pub read_string: fn(priv_data: *mut c_void, dest: *mut c_char, max_len: i32) -> LoadState,
pub read_string_len: fn(priv_data: *const c_void, len: *mut i32) -> LoadState,
}
pub enum LoadResult<T> {
Ok(T),
Fail,
Converted(T),
Truncated(T),
OutOfData,
}
impl<T> LoadResult<T> {
pub fn from_state(state: LoadState, val: T) -> LoadResult<T> {
match state {
LoadState::Ok => LoadResult::Ok(val),
LoadState::Converted => LoadResult::Converted(val),
LoadState::Truncated => LoadResult::Truncated(val),
LoadState::Fail => LoadResult::Fail,
LoadState::OutOfData => LoadResult::OutOfData,
}
}
}
pub struct StateLoader<'a>(&'a mut CPDLoadState);
impl<'a> StateLoader<'a> {
pub fn new(api: *mut CPDLoadState) -> StateLoader<'a> {
unsafe { StateLoader(&mut *api) }
}
pub fn read_int(&mut self) -> LoadResult<i64> {
let mut res: i64 = 0;
let state = ((*self.0).read_int)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pub fn read_f64(&mut self) -> LoadResult<f64> {
let mut res: f64 = 0.0;
let state = ((*self.0).read_double)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pub fn read_string(&mut self) -> LoadResult<String>
|
}
|
{
let mut len: i32 = 0;
let len_state = ((*self.0).read_string_len)((*self.0).priv_data, &mut len);
match len_state {
LoadState::Fail => return LoadResult::Fail,
LoadState::OutOfData => return LoadResult::OutOfData,
_ => {}
}
let mut buf = vec!(0u8; len as usize);
let state = unsafe {
((*self.0).read_string)((*self.0).priv_data, transmute(buf.as_mut_ptr()), len)
};
LoadResult::from_state(state, String::from_utf8(buf).unwrap())
}
|
identifier_body
|
io.rs
|
use std::os::raw::{c_char, c_void};
use std::mem::transmute;
use super::CFixedString;
#[repr(C)]
pub enum LoadState {
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub write_double: fn(priv_data: *mut c_void, data: f64),
pub write_string: fn(priv_data: *mut c_void, data: *const c_char),
}
pub struct StateSaver<'a>(&'a mut CPDSaveState);
impl<'a> StateSaver<'a> {
pub fn new(api: *mut CPDSaveState) -> StateSaver<'a> {
unsafe { StateSaver(&mut *api) }
}
pub fn write_int(&mut self, data: i64) {
((*self.0).write_int)((*self.0).priv_data, data)
}
pub fn write_double(&mut self, data: f64) {
((*self.0).write_double)((*self.0).priv_data, data)
}
pub fn write_str(&mut self, data: &str) {
let str = CFixedString::from_str(data);
((*self.0).write_string)((*self.0).priv_data, str.as_ptr())
}
}
#[repr(C)]
pub struct CPDLoadState {
pub priv_data: *mut c_void,
pub read_int: fn(priv_data: *mut c_void, dest: *mut i64) -> LoadState,
pub read_double: fn(priv_data: *mut c_void, dest: *mut f64) -> LoadState,
pub read_string: fn(priv_data: *mut c_void, dest: *mut c_char, max_len: i32) -> LoadState,
pub read_string_len: fn(priv_data: *const c_void, len: *mut i32) -> LoadState,
}
pub enum LoadResult<T> {
Ok(T),
Fail,
Converted(T),
Truncated(T),
OutOfData,
}
impl<T> LoadResult<T> {
pub fn from_state(state: LoadState, val: T) -> LoadResult<T> {
match state {
LoadState::Ok => LoadResult::Ok(val),
LoadState::Converted => LoadResult::Converted(val),
LoadState::Truncated => LoadResult::Truncated(val),
LoadState::Fail => LoadResult::Fail,
LoadState::OutOfData => LoadResult::OutOfData,
}
}
}
|
pub fn new(api: *mut CPDLoadState) -> StateLoader<'a> {
unsafe { StateLoader(&mut *api) }
}
pub fn read_int(&mut self) -> LoadResult<i64> {
let mut res: i64 = 0;
let state = ((*self.0).read_int)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pub fn read_f64(&mut self) -> LoadResult<f64> {
let mut res: f64 = 0.0;
let state = ((*self.0).read_double)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pub fn read_string(&mut self) -> LoadResult<String> {
let mut len: i32 = 0;
let len_state = ((*self.0).read_string_len)((*self.0).priv_data, &mut len);
match len_state {
LoadState::Fail => return LoadResult::Fail,
LoadState::OutOfData => return LoadResult::OutOfData,
_ => {}
}
let mut buf = vec!(0u8; len as usize);
let state = unsafe {
((*self.0).read_string)((*self.0).priv_data, transmute(buf.as_mut_ptr()), len)
};
LoadResult::from_state(state, String::from_utf8(buf).unwrap())
}
}
|
pub struct StateLoader<'a>(&'a mut CPDLoadState);
impl<'a> StateLoader<'a> {
|
random_line_split
|
instr_kxnorb.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 kxnorb_1() {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K4)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 70, 204], OperandSize::Dword)
}
#[test]
fn kxnorb_2()
|
{
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K2)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 237, 70, 205], OperandSize::Qword)
}
|
identifier_body
|
|
instr_kxnorb.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::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K4)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 70, 204], OperandSize::Dword)
}
#[test]
fn kxnorb_2() {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K2)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 237, 70, 205], OperandSize::Qword)
}
|
kxnorb_1
|
identifier_name
|
instr_kxnorb.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
|
#[test]
fn kxnorb_1() {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K4)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 70, 204], OperandSize::Dword)
}
#[test]
fn kxnorb_2() {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K2)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 237, 70, 205], OperandSize::Qword)
}
|
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
|
random_line_split
|
cluster.rs
|
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
|
use rand;
use std::sync::atomic::{AtomicIsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load balancing strategy
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
println!("node# {:?}", i);
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
/// Returns random number from a range
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
min + rnd * (max - min) / (u8::max_value() as usize)
}
}
/// Load balancer
///
/// #Example
///
/// ```no_run
/// use cdrs::cluster::{LoadBalancingStrategy, LoadBalancer};
/// use cdrs::transport::TransportTcp;
/// let transports = vec![TransportTcp::new("127.0.0.1:9042"), TransportTcp::new("127.0.0.1:9042")];
/// let load_balancer = LoadBalancer::new(transports, LoadBalancingStrategy::RoundRobin);
/// let node = load_balancer.next().unwrap();
/// ```
pub struct LoadBalancer<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicIsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicIsize::new(0),
}
}
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
}
next
}
}
/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync +'static
{
/// Creates a new instance of `ConnectionManager`.
/// It requires transport, authenticator and compression as inputs.
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
}
}
impl<T: Authenticator + Send + Sync +'static, X: CDRSTransport + Send + Sync +'static>
r2d2::ManageConnection for ClusterConnectionManager<T, X> {
type Connection = Session<T,X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
}
|
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
|
random_line_split
|
cluster.rs
|
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
use rand;
use std::sync::atomic::{AtomicIsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load balancing strategy
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
println!("node# {:?}", i);
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
/// Returns random number from a range
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
min + rnd * (max - min) / (u8::max_value() as usize)
}
}
/// Load balancer
///
/// #Example
///
/// ```no_run
/// use cdrs::cluster::{LoadBalancingStrategy, LoadBalancer};
/// use cdrs::transport::TransportTcp;
/// let transports = vec![TransportTcp::new("127.0.0.1:9042"), TransportTcp::new("127.0.0.1:9042")];
/// let load_balancer = LoadBalancer::new(transports, LoadBalancingStrategy::RoundRobin);
/// let node = load_balancer.next().unwrap();
/// ```
pub struct
|
<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicIsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicIsize::new(0),
}
}
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
}
next
}
}
/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync +'static
{
/// Creates a new instance of `ConnectionManager`.
/// It requires transport, authenticator and compression as inputs.
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
}
}
impl<T: Authenticator + Send + Sync +'static, X: CDRSTransport + Send + Sync +'static>
r2d2::ManageConnection for ClusterConnectionManager<T, X> {
type Connection = Session<T,X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
}
|
LoadBalancer
|
identifier_name
|
cluster.rs
|
//! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
use rand;
use std::sync::atomic::{AtomicIsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load balancing strategy
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
println!("node# {:?}", i);
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
/// Returns random number from a range
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
min + rnd * (max - min) / (u8::max_value() as usize)
}
}
/// Load balancer
///
/// #Example
///
/// ```no_run
/// use cdrs::cluster::{LoadBalancingStrategy, LoadBalancer};
/// use cdrs::transport::TransportTcp;
/// let transports = vec![TransportTcp::new("127.0.0.1:9042"), TransportTcp::new("127.0.0.1:9042")];
/// let load_balancer = LoadBalancer::new(transports, LoadBalancingStrategy::RoundRobin);
/// let node = load_balancer.next().unwrap();
/// ```
pub struct LoadBalancer<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicIsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T>
|
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
}
next
}
}
/// [r2d2](https://github.com/sfackler/r2d2) `ManageConnection`.
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync +'static
{
/// Creates a new instance of `ConnectionManager`.
/// It requires transport, authenticator and compression as inputs.
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
}
}
impl<T: Authenticator + Send + Sync +'static, X: CDRSTransport + Send + Sync +'static>
r2d2::ManageConnection for ClusterConnectionManager<T, X> {
type Connection = Session<T,X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
}
|
{
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicIsize::new(0),
}
}
|
identifier_body
|
custom_properties.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 cssparser::{Parser, ParserInput};
use servo_arc::Arc;
use style::custom_properties::{
CssEnvironment, CustomPropertiesBuilder, CustomPropertiesMap, Name, SpecifiedValue,
};
use style::properties::{CustomDeclaration, CustomDeclarationValue};
use style::stylesheets::Origin;
use test::{self, Bencher};
fn cascade(
name_and_value: &[(&str, &str)],
inherited: Option<&Arc<CustomPropertiesMap>>,
) -> Option<Arc<CustomPropertiesMap>>
|
}
#[bench]
fn cascade_custom_simple(b: &mut Bencher) {
b.iter(|| {
let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None);
test::black_box(cascade(
&[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")],
parent.as_ref(),
))
})
}
|
{
let declarations = name_and_value
.iter()
.map(|&(name, value)| {
let mut input = ParserInput::new(value);
let mut parser = Parser::new(&mut input);
let name = Name::from(name);
let value = CustomDeclarationValue::Value(SpecifiedValue::parse(&mut parser).unwrap());
CustomDeclaration { name, value }
})
.collect::<Vec<_>>();
let env = CssEnvironment;
let mut builder = CustomPropertiesBuilder::new(inherited, &env);
for declaration in &declarations {
builder.cascade(declaration, Origin::Author);
}
builder.build()
|
identifier_body
|
custom_properties.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 cssparser::{Parser, ParserInput};
use servo_arc::Arc;
use style::custom_properties::{
CssEnvironment, CustomPropertiesBuilder, CustomPropertiesMap, Name, SpecifiedValue,
};
use style::properties::{CustomDeclaration, CustomDeclarationValue};
use style::stylesheets::Origin;
use test::{self, Bencher};
fn cascade(
name_and_value: &[(&str, &str)],
inherited: Option<&Arc<CustomPropertiesMap>>,
) -> Option<Arc<CustomPropertiesMap>> {
let declarations = name_and_value
.iter()
.map(|&(name, value)| {
let mut input = ParserInput::new(value);
let mut parser = Parser::new(&mut input);
let name = Name::from(name);
let value = CustomDeclarationValue::Value(SpecifiedValue::parse(&mut parser).unwrap());
CustomDeclaration { name, value }
})
.collect::<Vec<_>>();
let env = CssEnvironment;
let mut builder = CustomPropertiesBuilder::new(inherited, &env);
for declaration in &declarations {
builder.cascade(declaration, Origin::Author);
}
builder.build()
}
#[bench]
fn cascade_custom_simple(b: &mut Bencher) {
b.iter(|| {
let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None);
test::black_box(cascade(
&[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")],
parent.as_ref(),
))
})
}
|
random_line_split
|
|
custom_properties.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 cssparser::{Parser, ParserInput};
use servo_arc::Arc;
use style::custom_properties::{
CssEnvironment, CustomPropertiesBuilder, CustomPropertiesMap, Name, SpecifiedValue,
};
use style::properties::{CustomDeclaration, CustomDeclarationValue};
use style::stylesheets::Origin;
use test::{self, Bencher};
fn cascade(
name_and_value: &[(&str, &str)],
inherited: Option<&Arc<CustomPropertiesMap>>,
) -> Option<Arc<CustomPropertiesMap>> {
let declarations = name_and_value
.iter()
.map(|&(name, value)| {
let mut input = ParserInput::new(value);
let mut parser = Parser::new(&mut input);
let name = Name::from(name);
let value = CustomDeclarationValue::Value(SpecifiedValue::parse(&mut parser).unwrap());
CustomDeclaration { name, value }
})
.collect::<Vec<_>>();
let env = CssEnvironment;
let mut builder = CustomPropertiesBuilder::new(inherited, &env);
for declaration in &declarations {
builder.cascade(declaration, Origin::Author);
}
builder.build()
}
#[bench]
fn
|
(b: &mut Bencher) {
b.iter(|| {
let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None);
test::black_box(cascade(
&[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")],
parent.as_ref(),
))
})
}
|
cascade_custom_simple
|
identifier_name
|
symbol.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An "interner" is a data structure that associates values with usize tags and
//! allows bidirectional lookup; i.e. given a value, one can easily find the
//! type, and vice versa.
use hygiene::SyntaxContext;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ident {
pub name: Symbol,
pub ctxt: SyntaxContext,
}
impl Ident {
pub fn with_empty_ctxt(name: Symbol) -> Ident {
Ident { name: name, ctxt: SyntaxContext::empty() }
}
/// Maps a string to an identifier with an empty syntax context.
pub fn from_str(string: &str) -> Ident {
Ident::with_empty_ctxt(Symbol::intern(string))
}
pub fn modern(self) -> Ident {
Ident { name: self.name, ctxt: self.ctxt.modern() }
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{:?}", self.name, self.ctxt)
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.name, f)
}
}
impl Serialize for Ident {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
if self.ctxt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'de> Deserialize<'de> for Ident {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
let string = String::deserialize(deserializer)?;
Ok(if!string.starts_with('#') {
Ident::from_str(&string)
} else { // FIXME(jseyfried) intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
})
}
}
/// A symbol is an interned or gensymed string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);
// FIXME syntex
// The interner in thread-local, so `Symbol` shouldn't move between threads.
// impl!Send for Symbol { }
impl Symbol {
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
}
pub fn interned(self) -> Self {
with_interner(|interner| interner.interned(self))
}
/// gensym's a new usize, using the current interner.
pub fn gensym(string: &str) -> Self {
with_interner(|interner| interner.gensym(string))
}
pub fn gensymed(self) -> Self {
with_interner(|interner| interner.gensymed(self))
}
pub fn as_str(self) -> InternedString {
with_interner(|interner| unsafe {
InternedString {
string: ::std::mem::transmute::<&str, &str>(interner.get(self))
}
})
}
pub fn as_u32(self) -> u32 {
self.0
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self, self.0)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.as_str(), f)
}
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.as_str())
}
|
impl<'de> Deserialize<'de> for Symbol {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
String::deserialize(deserializer).map(|s| Symbol::intern(&s))
}
}
impl<T: ::std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -> bool {
self.as_str() == other.deref()
}
}
#[derive(Default)]
pub struct Interner {
names: HashMap<Box<str>, Symbol>,
strings: Vec<Box<str>>,
gensyms: Vec<Symbol>,
}
impl Interner {
pub fn new() -> Self {
Interner::default()
}
fn prefill(init: &[&str]) -> Self {
let mut this = Interner::new();
for &string in init {
this.intern(string);
}
this
}
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol(self.strings.len() as u32);
let string = string.to_string().into_boxed_str();
self.strings.push(string.clone());
self.names.insert(string, name);
name
}
pub fn interned(&self, symbol: Symbol) -> Symbol {
if (symbol.0 as usize) < self.strings.len() {
symbol
} else {
self.interned(self.gensyms[(!0 - symbol.0) as usize])
}
}
fn gensym(&mut self, string: &str) -> Symbol {
let symbol = self.intern(string);
self.gensymed(symbol)
}
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
self.gensyms.push(symbol);
Symbol(!0 - self.gensyms.len() as u32 + 1)
}
pub fn get(&self, symbol: Symbol) -> &str {
match self.strings.get(symbol.0 as usize) {
Some(ref string) => string,
None => self.get(self.gensyms[(!0 - symbol.0) as usize]),
}
}
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero.
macro_rules! declare_keywords {(
$( ($index: expr, $konst: ident, $string: expr) )*
) => {
pub mod keywords {
use super::{Symbol, Ident};
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Keyword {
ident: Ident,
}
impl Keyword {
#[inline] pub fn ident(self) -> Ident { self.ident }
#[inline] pub fn name(self) -> Symbol { self.ident.name }
}
$(
#[allow(non_upper_case_globals)]
pub const $konst: Keyword = Keyword {
ident: Ident {
name: super::Symbol($index),
ctxt: ::NO_EXPANSION,
}
};
)*
}
impl Interner {
fn fresh() -> Self {
Interner::prefill(&[$($string,)*])
}
}
}}
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
// After modifying this list adjust `is_strict_keyword`/`is_reserved_keyword`,
// this should be rarely necessary though if the keywords are kept in alphabetic order.
declare_keywords! {
// Invalid identifier
(0, Invalid, "")
// Strict keywords used in the language.
(1, As, "as")
(2, Box, "box")
(3, Break, "break")
(4, Const, "const")
(5, Continue, "continue")
(6, Crate, "crate")
(7, Else, "else")
(8, Enum, "enum")
(9, Extern, "extern")
(10, False, "false")
(11, Fn, "fn")
(12, For, "for")
(13, If, "if")
(14, Impl, "impl")
(15, In, "in")
(16, Let, "let")
(17, Loop, "loop")
(18, Match, "match")
(19, Mod, "mod")
(20, Move, "move")
(21, Mut, "mut")
(22, Pub, "pub")
(23, Ref, "ref")
(24, Return, "return")
(25, SelfValue, "self")
(26, SelfType, "Self")
(27, Static, "static")
(28, Struct, "struct")
(29, Super, "super")
(30, Trait, "trait")
(31, True, "true")
(32, Type, "type")
(33, Unsafe, "unsafe")
(34, Use, "use")
(35, Where, "where")
(36, While, "while")
// Keywords reserved for future use.
(37, Abstract, "abstract")
(38, Alignof, "alignof")
(39, Become, "become")
(40, Do, "do")
(41, Final, "final")
(42, Macro, "macro")
(43, Offsetof, "offsetof")
(44, Override, "override")
(45, Priv, "priv")
(46, Proc, "proc")
(47, Pure, "pure")
(48, Sizeof, "sizeof")
(49, Typeof, "typeof")
(50, Unsized, "unsized")
(51, Virtual, "virtual")
(52, Yield, "yield")
// Weak keywords, have special meaning only in specific contexts.
(53, Default, "default")
(54, StaticLifetime, "'static")
(55, Union, "union")
(56, Catch, "catch")
// A virtual keyword that resolves to the crate root when used in a lexical scope.
(57, CrateRoot, "{{root}}")
}
// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
thread_local!(static INTERNER: RefCell<Interner> = {
RefCell::new(Interner::fresh())
});
INTERNER.with(|interner| f(&mut *interner.borrow_mut()))
}
/// Represents a string stored in the thread-local interner. Because the
/// interner lives for the life of the thread, this can be safely treated as an
/// immortal string, as long as it never crosses between threads.
///
/// FIXME(pcwalton): You must be careful about what you do in the destructors
/// of objects stored in TLS, because they may run after the interner is
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until thread death
/// somehow.
#[derive(Clone, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: &'static str,
}
impl<U:?Sized> ::std::convert::AsRef<U> for InternedString where str: ::std::convert::AsRef<U> {
fn as_ref(&self) -> &U {
self.string.as_ref()
}
}
impl<T: ::std::ops::Deref<Target = str>> ::std::cmp::PartialEq<T> for InternedString {
fn eq(&self, other: &T) -> bool {
self.string == other.deref()
}
}
impl ::std::cmp::PartialEq<InternedString> for str {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a str {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
impl ::std::cmp::PartialEq<InternedString> for String {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a String {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
// FIXME syntex
// impl!Send for InternedString { }
impl ::std::ops::Deref for InternedString {
type Target = str;
fn deref(&self) -> &str { self.string }
}
impl fmt::Debug for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.string, f)
}
}
impl fmt::Display for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.string, f)
}
}
impl<'de> Deserialize<'de> for InternedString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Symbol::deserialize(deserializer).map(Symbol::as_str)
}
}
impl Serialize for InternedString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(self.string)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interner_tests() {
let mut i: Interner = Interner::new();
// first one is zero:
assert_eq!(i.intern("dog"), Symbol(0));
// re-use gets the same entry:
assert_eq!(i.intern ("dog"), Symbol(0));
// different string gets a different #:
assert_eq!(i.intern("cat"), Symbol(1));
assert_eq!(i.intern("cat"), Symbol(1));
// dog is still at zero
assert_eq!(i.intern("dog"), Symbol(0));
assert_eq!(i.gensym("zebra"), Symbol(4294967295));
// gensym of same string gets new number :
assert_eq!(i.gensym("zebra"), Symbol(4294967294));
// gensym of *existing* string gets new number:
assert_eq!(i.gensym("dog"), Symbol(4294967293));
}
}
|
}
|
random_line_split
|
symbol.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An "interner" is a data structure that associates values with usize tags and
//! allows bidirectional lookup; i.e. given a value, one can easily find the
//! type, and vice versa.
use hygiene::SyntaxContext;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ident {
pub name: Symbol,
pub ctxt: SyntaxContext,
}
impl Ident {
pub fn with_empty_ctxt(name: Symbol) -> Ident {
Ident { name: name, ctxt: SyntaxContext::empty() }
}
/// Maps a string to an identifier with an empty syntax context.
pub fn from_str(string: &str) -> Ident {
Ident::with_empty_ctxt(Symbol::intern(string))
}
pub fn modern(self) -> Ident {
Ident { name: self.name, ctxt: self.ctxt.modern() }
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{:?}", self.name, self.ctxt)
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.name, f)
}
}
impl Serialize for Ident {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
if self.ctxt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'de> Deserialize<'de> for Ident {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
let string = String::deserialize(deserializer)?;
Ok(if!string.starts_with('#') {
Ident::from_str(&string)
} else { // FIXME(jseyfried) intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
})
}
}
/// A symbol is an interned or gensymed string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);
// FIXME syntex
// The interner in thread-local, so `Symbol` shouldn't move between threads.
// impl!Send for Symbol { }
impl Symbol {
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
}
pub fn interned(self) -> Self {
with_interner(|interner| interner.interned(self))
}
/// gensym's a new usize, using the current interner.
pub fn gensym(string: &str) -> Self {
with_interner(|interner| interner.gensym(string))
}
pub fn gensymed(self) -> Self {
with_interner(|interner| interner.gensymed(self))
}
pub fn as_str(self) -> InternedString {
with_interner(|interner| unsafe {
InternedString {
string: ::std::mem::transmute::<&str, &str>(interner.get(self))
}
})
}
pub fn as_u32(self) -> u32 {
self.0
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self, self.0)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.as_str(), f)
}
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.as_str())
}
}
impl<'de> Deserialize<'de> for Symbol {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
String::deserialize(deserializer).map(|s| Symbol::intern(&s))
}
}
impl<T: ::std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -> bool {
self.as_str() == other.deref()
}
}
#[derive(Default)]
pub struct Interner {
names: HashMap<Box<str>, Symbol>,
strings: Vec<Box<str>>,
gensyms: Vec<Symbol>,
}
impl Interner {
pub fn new() -> Self {
Interner::default()
}
fn prefill(init: &[&str]) -> Self {
let mut this = Interner::new();
for &string in init {
this.intern(string);
}
this
}
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol(self.strings.len() as u32);
let string = string.to_string().into_boxed_str();
self.strings.push(string.clone());
self.names.insert(string, name);
name
}
pub fn interned(&self, symbol: Symbol) -> Symbol {
if (symbol.0 as usize) < self.strings.len() {
symbol
} else {
self.interned(self.gensyms[(!0 - symbol.0) as usize])
}
}
fn gensym(&mut self, string: &str) -> Symbol {
let symbol = self.intern(string);
self.gensymed(symbol)
}
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
self.gensyms.push(symbol);
Symbol(!0 - self.gensyms.len() as u32 + 1)
}
pub fn get(&self, symbol: Symbol) -> &str {
match self.strings.get(symbol.0 as usize) {
Some(ref string) => string,
None => self.get(self.gensyms[(!0 - symbol.0) as usize]),
}
}
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero.
macro_rules! declare_keywords {(
$( ($index: expr, $konst: ident, $string: expr) )*
) => {
pub mod keywords {
use super::{Symbol, Ident};
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Keyword {
ident: Ident,
}
impl Keyword {
#[inline] pub fn ident(self) -> Ident { self.ident }
#[inline] pub fn name(self) -> Symbol { self.ident.name }
}
$(
#[allow(non_upper_case_globals)]
pub const $konst: Keyword = Keyword {
ident: Ident {
name: super::Symbol($index),
ctxt: ::NO_EXPANSION,
}
};
)*
}
impl Interner {
fn fresh() -> Self {
Interner::prefill(&[$($string,)*])
}
}
}}
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
// After modifying this list adjust `is_strict_keyword`/`is_reserved_keyword`,
// this should be rarely necessary though if the keywords are kept in alphabetic order.
declare_keywords! {
// Invalid identifier
(0, Invalid, "")
// Strict keywords used in the language.
(1, As, "as")
(2, Box, "box")
(3, Break, "break")
(4, Const, "const")
(5, Continue, "continue")
(6, Crate, "crate")
(7, Else, "else")
(8, Enum, "enum")
(9, Extern, "extern")
(10, False, "false")
(11, Fn, "fn")
(12, For, "for")
(13, If, "if")
(14, Impl, "impl")
(15, In, "in")
(16, Let, "let")
(17, Loop, "loop")
(18, Match, "match")
(19, Mod, "mod")
(20, Move, "move")
(21, Mut, "mut")
(22, Pub, "pub")
(23, Ref, "ref")
(24, Return, "return")
(25, SelfValue, "self")
(26, SelfType, "Self")
(27, Static, "static")
(28, Struct, "struct")
(29, Super, "super")
(30, Trait, "trait")
(31, True, "true")
(32, Type, "type")
(33, Unsafe, "unsafe")
(34, Use, "use")
(35, Where, "where")
(36, While, "while")
// Keywords reserved for future use.
(37, Abstract, "abstract")
(38, Alignof, "alignof")
(39, Become, "become")
(40, Do, "do")
(41, Final, "final")
(42, Macro, "macro")
(43, Offsetof, "offsetof")
(44, Override, "override")
(45, Priv, "priv")
(46, Proc, "proc")
(47, Pure, "pure")
(48, Sizeof, "sizeof")
(49, Typeof, "typeof")
(50, Unsized, "unsized")
(51, Virtual, "virtual")
(52, Yield, "yield")
// Weak keywords, have special meaning only in specific contexts.
(53, Default, "default")
(54, StaticLifetime, "'static")
(55, Union, "union")
(56, Catch, "catch")
// A virtual keyword that resolves to the crate root when used in a lexical scope.
(57, CrateRoot, "{{root}}")
}
// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.
fn
|
<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
thread_local!(static INTERNER: RefCell<Interner> = {
RefCell::new(Interner::fresh())
});
INTERNER.with(|interner| f(&mut *interner.borrow_mut()))
}
/// Represents a string stored in the thread-local interner. Because the
/// interner lives for the life of the thread, this can be safely treated as an
/// immortal string, as long as it never crosses between threads.
///
/// FIXME(pcwalton): You must be careful about what you do in the destructors
/// of objects stored in TLS, because they may run after the interner is
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until thread death
/// somehow.
#[derive(Clone, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: &'static str,
}
impl<U:?Sized> ::std::convert::AsRef<U> for InternedString where str: ::std::convert::AsRef<U> {
fn as_ref(&self) -> &U {
self.string.as_ref()
}
}
impl<T: ::std::ops::Deref<Target = str>> ::std::cmp::PartialEq<T> for InternedString {
fn eq(&self, other: &T) -> bool {
self.string == other.deref()
}
}
impl ::std::cmp::PartialEq<InternedString> for str {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a str {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
impl ::std::cmp::PartialEq<InternedString> for String {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a String {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
// FIXME syntex
// impl!Send for InternedString { }
impl ::std::ops::Deref for InternedString {
type Target = str;
fn deref(&self) -> &str { self.string }
}
impl fmt::Debug for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.string, f)
}
}
impl fmt::Display for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.string, f)
}
}
impl<'de> Deserialize<'de> for InternedString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Symbol::deserialize(deserializer).map(Symbol::as_str)
}
}
impl Serialize for InternedString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(self.string)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interner_tests() {
let mut i: Interner = Interner::new();
// first one is zero:
assert_eq!(i.intern("dog"), Symbol(0));
// re-use gets the same entry:
assert_eq!(i.intern ("dog"), Symbol(0));
// different string gets a different #:
assert_eq!(i.intern("cat"), Symbol(1));
assert_eq!(i.intern("cat"), Symbol(1));
// dog is still at zero
assert_eq!(i.intern("dog"), Symbol(0));
assert_eq!(i.gensym("zebra"), Symbol(4294967295));
// gensym of same string gets new number :
assert_eq!(i.gensym("zebra"), Symbol(4294967294));
// gensym of *existing* string gets new number:
assert_eq!(i.gensym("dog"), Symbol(4294967293));
}
}
|
with_interner
|
identifier_name
|
symbol.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An "interner" is a data structure that associates values with usize tags and
//! allows bidirectional lookup; i.e. given a value, one can easily find the
//! type, and vice versa.
use hygiene::SyntaxContext;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ident {
pub name: Symbol,
pub ctxt: SyntaxContext,
}
impl Ident {
pub fn with_empty_ctxt(name: Symbol) -> Ident {
Ident { name: name, ctxt: SyntaxContext::empty() }
}
/// Maps a string to an identifier with an empty syntax context.
pub fn from_str(string: &str) -> Ident {
Ident::with_empty_ctxt(Symbol::intern(string))
}
pub fn modern(self) -> Ident {
Ident { name: self.name, ctxt: self.ctxt.modern() }
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{:?}", self.name, self.ctxt)
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.name, f)
}
}
impl Serialize for Ident {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
if self.ctxt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'de> Deserialize<'de> for Ident {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
let string = String::deserialize(deserializer)?;
Ok(if!string.starts_with('#') {
Ident::from_str(&string)
} else { // FIXME(jseyfried) intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
})
}
}
/// A symbol is an interned or gensymed string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);
// FIXME syntex
// The interner in thread-local, so `Symbol` shouldn't move between threads.
// impl!Send for Symbol { }
impl Symbol {
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
}
pub fn interned(self) -> Self {
with_interner(|interner| interner.interned(self))
}
/// gensym's a new usize, using the current interner.
pub fn gensym(string: &str) -> Self {
with_interner(|interner| interner.gensym(string))
}
pub fn gensymed(self) -> Self {
with_interner(|interner| interner.gensymed(self))
}
pub fn as_str(self) -> InternedString {
with_interner(|interner| unsafe {
InternedString {
string: ::std::mem::transmute::<&str, &str>(interner.get(self))
}
})
}
pub fn as_u32(self) -> u32 {
self.0
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self, self.0)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.as_str(), f)
}
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.as_str())
}
}
impl<'de> Deserialize<'de> for Symbol {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
String::deserialize(deserializer).map(|s| Symbol::intern(&s))
}
}
impl<T: ::std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -> bool {
self.as_str() == other.deref()
}
}
#[derive(Default)]
pub struct Interner {
names: HashMap<Box<str>, Symbol>,
strings: Vec<Box<str>>,
gensyms: Vec<Symbol>,
}
impl Interner {
pub fn new() -> Self
|
fn prefill(init: &[&str]) -> Self {
let mut this = Interner::new();
for &string in init {
this.intern(string);
}
this
}
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol(self.strings.len() as u32);
let string = string.to_string().into_boxed_str();
self.strings.push(string.clone());
self.names.insert(string, name);
name
}
pub fn interned(&self, symbol: Symbol) -> Symbol {
if (symbol.0 as usize) < self.strings.len() {
symbol
} else {
self.interned(self.gensyms[(!0 - symbol.0) as usize])
}
}
fn gensym(&mut self, string: &str) -> Symbol {
let symbol = self.intern(string);
self.gensymed(symbol)
}
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
self.gensyms.push(symbol);
Symbol(!0 - self.gensyms.len() as u32 + 1)
}
pub fn get(&self, symbol: Symbol) -> &str {
match self.strings.get(symbol.0 as usize) {
Some(ref string) => string,
None => self.get(self.gensyms[(!0 - symbol.0) as usize]),
}
}
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero.
macro_rules! declare_keywords {(
$( ($index: expr, $konst: ident, $string: expr) )*
) => {
pub mod keywords {
use super::{Symbol, Ident};
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Keyword {
ident: Ident,
}
impl Keyword {
#[inline] pub fn ident(self) -> Ident { self.ident }
#[inline] pub fn name(self) -> Symbol { self.ident.name }
}
$(
#[allow(non_upper_case_globals)]
pub const $konst: Keyword = Keyword {
ident: Ident {
name: super::Symbol($index),
ctxt: ::NO_EXPANSION,
}
};
)*
}
impl Interner {
fn fresh() -> Self {
Interner::prefill(&[$($string,)*])
}
}
}}
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
// After modifying this list adjust `is_strict_keyword`/`is_reserved_keyword`,
// this should be rarely necessary though if the keywords are kept in alphabetic order.
declare_keywords! {
// Invalid identifier
(0, Invalid, "")
// Strict keywords used in the language.
(1, As, "as")
(2, Box, "box")
(3, Break, "break")
(4, Const, "const")
(5, Continue, "continue")
(6, Crate, "crate")
(7, Else, "else")
(8, Enum, "enum")
(9, Extern, "extern")
(10, False, "false")
(11, Fn, "fn")
(12, For, "for")
(13, If, "if")
(14, Impl, "impl")
(15, In, "in")
(16, Let, "let")
(17, Loop, "loop")
(18, Match, "match")
(19, Mod, "mod")
(20, Move, "move")
(21, Mut, "mut")
(22, Pub, "pub")
(23, Ref, "ref")
(24, Return, "return")
(25, SelfValue, "self")
(26, SelfType, "Self")
(27, Static, "static")
(28, Struct, "struct")
(29, Super, "super")
(30, Trait, "trait")
(31, True, "true")
(32, Type, "type")
(33, Unsafe, "unsafe")
(34, Use, "use")
(35, Where, "where")
(36, While, "while")
// Keywords reserved for future use.
(37, Abstract, "abstract")
(38, Alignof, "alignof")
(39, Become, "become")
(40, Do, "do")
(41, Final, "final")
(42, Macro, "macro")
(43, Offsetof, "offsetof")
(44, Override, "override")
(45, Priv, "priv")
(46, Proc, "proc")
(47, Pure, "pure")
(48, Sizeof, "sizeof")
(49, Typeof, "typeof")
(50, Unsized, "unsized")
(51, Virtual, "virtual")
(52, Yield, "yield")
// Weak keywords, have special meaning only in specific contexts.
(53, Default, "default")
(54, StaticLifetime, "'static")
(55, Union, "union")
(56, Catch, "catch")
// A virtual keyword that resolves to the crate root when used in a lexical scope.
(57, CrateRoot, "{{root}}")
}
// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
thread_local!(static INTERNER: RefCell<Interner> = {
RefCell::new(Interner::fresh())
});
INTERNER.with(|interner| f(&mut *interner.borrow_mut()))
}
/// Represents a string stored in the thread-local interner. Because the
/// interner lives for the life of the thread, this can be safely treated as an
/// immortal string, as long as it never crosses between threads.
///
/// FIXME(pcwalton): You must be careful about what you do in the destructors
/// of objects stored in TLS, because they may run after the interner is
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until thread death
/// somehow.
#[derive(Clone, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: &'static str,
}
impl<U:?Sized> ::std::convert::AsRef<U> for InternedString where str: ::std::convert::AsRef<U> {
fn as_ref(&self) -> &U {
self.string.as_ref()
}
}
impl<T: ::std::ops::Deref<Target = str>> ::std::cmp::PartialEq<T> for InternedString {
fn eq(&self, other: &T) -> bool {
self.string == other.deref()
}
}
impl ::std::cmp::PartialEq<InternedString> for str {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a str {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
impl ::std::cmp::PartialEq<InternedString> for String {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a String {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
// FIXME syntex
// impl!Send for InternedString { }
impl ::std::ops::Deref for InternedString {
type Target = str;
fn deref(&self) -> &str { self.string }
}
impl fmt::Debug for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.string, f)
}
}
impl fmt::Display for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.string, f)
}
}
impl<'de> Deserialize<'de> for InternedString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Symbol::deserialize(deserializer).map(Symbol::as_str)
}
}
impl Serialize for InternedString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(self.string)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interner_tests() {
let mut i: Interner = Interner::new();
// first one is zero:
assert_eq!(i.intern("dog"), Symbol(0));
// re-use gets the same entry:
assert_eq!(i.intern ("dog"), Symbol(0));
// different string gets a different #:
assert_eq!(i.intern("cat"), Symbol(1));
assert_eq!(i.intern("cat"), Symbol(1));
// dog is still at zero
assert_eq!(i.intern("dog"), Symbol(0));
assert_eq!(i.gensym("zebra"), Symbol(4294967295));
// gensym of same string gets new number :
assert_eq!(i.gensym("zebra"), Symbol(4294967294));
// gensym of *existing* string gets new number:
assert_eq!(i.gensym("dog"), Symbol(4294967293));
}
}
|
{
Interner::default()
}
|
identifier_body
|
symbol.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! An "interner" is a data structure that associates values with usize tags and
//! allows bidirectional lookup; i.e. given a value, one can easily find the
//! type, and vice versa.
use hygiene::SyntaxContext;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Ident {
pub name: Symbol,
pub ctxt: SyntaxContext,
}
impl Ident {
pub fn with_empty_ctxt(name: Symbol) -> Ident {
Ident { name: name, ctxt: SyntaxContext::empty() }
}
/// Maps a string to an identifier with an empty syntax context.
pub fn from_str(string: &str) -> Ident {
Ident::with_empty_ctxt(Symbol::intern(string))
}
pub fn modern(self) -> Ident {
Ident { name: self.name, ctxt: self.ctxt.modern() }
}
}
impl fmt::Debug for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{:?}", self.name, self.ctxt)
}
}
impl fmt::Display for Ident {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.name, f)
}
}
impl Serialize for Ident {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
if self.ctxt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'de> Deserialize<'de> for Ident {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
let string = String::deserialize(deserializer)?;
Ok(if!string.starts_with('#') {
Ident::from_str(&string)
} else
|
)
}
}
/// A symbol is an interned or gensymed string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);
// FIXME syntex
// The interner in thread-local, so `Symbol` shouldn't move between threads.
// impl!Send for Symbol { }
impl Symbol {
/// Maps a string to its interned representation.
pub fn intern(string: &str) -> Self {
with_interner(|interner| interner.intern(string))
}
pub fn interned(self) -> Self {
with_interner(|interner| interner.interned(self))
}
/// gensym's a new usize, using the current interner.
pub fn gensym(string: &str) -> Self {
with_interner(|interner| interner.gensym(string))
}
pub fn gensymed(self) -> Self {
with_interner(|interner| interner.gensymed(self))
}
pub fn as_str(self) -> InternedString {
with_interner(|interner| unsafe {
InternedString {
string: ::std::mem::transmute::<&str, &str>(interner.get(self))
}
})
}
pub fn as_u32(self) -> u32 {
self.0
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}({})", self, self.0)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.as_str(), f)
}
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.as_str())
}
}
impl<'de> Deserialize<'de> for Symbol {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
String::deserialize(deserializer).map(|s| Symbol::intern(&s))
}
}
impl<T: ::std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -> bool {
self.as_str() == other.deref()
}
}
#[derive(Default)]
pub struct Interner {
names: HashMap<Box<str>, Symbol>,
strings: Vec<Box<str>>,
gensyms: Vec<Symbol>,
}
impl Interner {
pub fn new() -> Self {
Interner::default()
}
fn prefill(init: &[&str]) -> Self {
let mut this = Interner::new();
for &string in init {
this.intern(string);
}
this
}
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
let name = Symbol(self.strings.len() as u32);
let string = string.to_string().into_boxed_str();
self.strings.push(string.clone());
self.names.insert(string, name);
name
}
pub fn interned(&self, symbol: Symbol) -> Symbol {
if (symbol.0 as usize) < self.strings.len() {
symbol
} else {
self.interned(self.gensyms[(!0 - symbol.0) as usize])
}
}
fn gensym(&mut self, string: &str) -> Symbol {
let symbol = self.intern(string);
self.gensymed(symbol)
}
fn gensymed(&mut self, symbol: Symbol) -> Symbol {
self.gensyms.push(symbol);
Symbol(!0 - self.gensyms.len() as u32 + 1)
}
pub fn get(&self, symbol: Symbol) -> &str {
match self.strings.get(symbol.0 as usize) {
Some(ref string) => string,
None => self.get(self.gensyms[(!0 - symbol.0) as usize]),
}
}
}
// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero.
macro_rules! declare_keywords {(
$( ($index: expr, $konst: ident, $string: expr) )*
) => {
pub mod keywords {
use super::{Symbol, Ident};
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Keyword {
ident: Ident,
}
impl Keyword {
#[inline] pub fn ident(self) -> Ident { self.ident }
#[inline] pub fn name(self) -> Symbol { self.ident.name }
}
$(
#[allow(non_upper_case_globals)]
pub const $konst: Keyword = Keyword {
ident: Ident {
name: super::Symbol($index),
ctxt: ::NO_EXPANSION,
}
};
)*
}
impl Interner {
fn fresh() -> Self {
Interner::prefill(&[$($string,)*])
}
}
}}
// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".
// After modifying this list adjust `is_strict_keyword`/`is_reserved_keyword`,
// this should be rarely necessary though if the keywords are kept in alphabetic order.
declare_keywords! {
// Invalid identifier
(0, Invalid, "")
// Strict keywords used in the language.
(1, As, "as")
(2, Box, "box")
(3, Break, "break")
(4, Const, "const")
(5, Continue, "continue")
(6, Crate, "crate")
(7, Else, "else")
(8, Enum, "enum")
(9, Extern, "extern")
(10, False, "false")
(11, Fn, "fn")
(12, For, "for")
(13, If, "if")
(14, Impl, "impl")
(15, In, "in")
(16, Let, "let")
(17, Loop, "loop")
(18, Match, "match")
(19, Mod, "mod")
(20, Move, "move")
(21, Mut, "mut")
(22, Pub, "pub")
(23, Ref, "ref")
(24, Return, "return")
(25, SelfValue, "self")
(26, SelfType, "Self")
(27, Static, "static")
(28, Struct, "struct")
(29, Super, "super")
(30, Trait, "trait")
(31, True, "true")
(32, Type, "type")
(33, Unsafe, "unsafe")
(34, Use, "use")
(35, Where, "where")
(36, While, "while")
// Keywords reserved for future use.
(37, Abstract, "abstract")
(38, Alignof, "alignof")
(39, Become, "become")
(40, Do, "do")
(41, Final, "final")
(42, Macro, "macro")
(43, Offsetof, "offsetof")
(44, Override, "override")
(45, Priv, "priv")
(46, Proc, "proc")
(47, Pure, "pure")
(48, Sizeof, "sizeof")
(49, Typeof, "typeof")
(50, Unsized, "unsized")
(51, Virtual, "virtual")
(52, Yield, "yield")
// Weak keywords, have special meaning only in specific contexts.
(53, Default, "default")
(54, StaticLifetime, "'static")
(55, Union, "union")
(56, Catch, "catch")
// A virtual keyword that resolves to the crate root when used in a lexical scope.
(57, CrateRoot, "{{root}}")
}
// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
thread_local!(static INTERNER: RefCell<Interner> = {
RefCell::new(Interner::fresh())
});
INTERNER.with(|interner| f(&mut *interner.borrow_mut()))
}
/// Represents a string stored in the thread-local interner. Because the
/// interner lives for the life of the thread, this can be safely treated as an
/// immortal string, as long as it never crosses between threads.
///
/// FIXME(pcwalton): You must be careful about what you do in the destructors
/// of objects stored in TLS, because they may run after the interner is
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until thread death
/// somehow.
#[derive(Clone, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
string: &'static str,
}
impl<U:?Sized> ::std::convert::AsRef<U> for InternedString where str: ::std::convert::AsRef<U> {
fn as_ref(&self) -> &U {
self.string.as_ref()
}
}
impl<T: ::std::ops::Deref<Target = str>> ::std::cmp::PartialEq<T> for InternedString {
fn eq(&self, other: &T) -> bool {
self.string == other.deref()
}
}
impl ::std::cmp::PartialEq<InternedString> for str {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a str {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
impl ::std::cmp::PartialEq<InternedString> for String {
fn eq(&self, other: &InternedString) -> bool {
self == other.string
}
}
impl<'a> ::std::cmp::PartialEq<InternedString> for &'a String {
fn eq(&self, other: &InternedString) -> bool {
*self == other.string
}
}
// FIXME syntex
// impl!Send for InternedString { }
impl ::std::ops::Deref for InternedString {
type Target = str;
fn deref(&self) -> &str { self.string }
}
impl fmt::Debug for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.string, f)
}
}
impl fmt::Display for InternedString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.string, f)
}
}
impl<'de> Deserialize<'de> for InternedString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
Symbol::deserialize(deserializer).map(Symbol::as_str)
}
}
impl Serialize for InternedString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(self.string)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interner_tests() {
let mut i: Interner = Interner::new();
// first one is zero:
assert_eq!(i.intern("dog"), Symbol(0));
// re-use gets the same entry:
assert_eq!(i.intern ("dog"), Symbol(0));
// different string gets a different #:
assert_eq!(i.intern("cat"), Symbol(1));
assert_eq!(i.intern("cat"), Symbol(1));
// dog is still at zero
assert_eq!(i.intern("dog"), Symbol(0));
assert_eq!(i.gensym("zebra"), Symbol(4294967295));
// gensym of same string gets new number :
assert_eq!(i.gensym("zebra"), Symbol(4294967294));
// gensym of *existing* string gets new number:
assert_eq!(i.gensym("dog"), Symbol(4294967293));
}
}
|
{ // FIXME(jseyfried) intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
}
|
conditional_block
|
knight_tour.rs
|
extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool;
fn printSolution(&self);
fn solveKT(&mut self);
}
impl<S> ChessFunc for DMatrix<S>
where
S: Scalar + Display + FromPrimitive,
{
fn solveKT(&mut self) {
let moves = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
].to_vec(); //knight movement
if self.solveKTUtil(0, 0, 1, &moves) {
self.printSolution();
} else {
println!("Solution does not exist");
}
}
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool {
if movei == N * N {
true
} else {
let mut result = false;
for cnt in 0..moves.len() {
let next_x: isize = x + moves[cnt].0;
let next_y: isize = y + moves[cnt].1;
if self.isSafe(next_x, next_y) {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_usize(movei).unwrap();
}
if self.solveKTUtil(next_x, next_y, movei + 1, moves) {
result = true;
break;
} else {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_isize(-1).unwrap();
}
}
}
}
result
}
}
fn printSolution(&self)
|
fn isSafe(&self, x: isize, y: isize) -> bool {
let mut result = false;
//println!("({},{})", x, y);
match ((x + 1) as usize, (y + 1) as usize) {
(1...N, 1...N) => {
match self.iter().nth((y * N as isize + x) as usize) {
Some(sc) => {
let temp: S = FromPrimitive::from_isize(-1).unwrap();
if temp == *sc {
result = true;
}
}
None => {}
};
}
_ => {}
}
//println!("({})", result);
result
}
}
fn main() {
let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension
let mut chessmap = DMatrix::from_fn_generic(DimN, DimN, |r, c| match (r, c) {
(0, 0) => 0,
_ => -1,
}); //initialize matrix (0,0) set 0 and the others set -1
//chessmap.printSolution();
chessmap.solveKT(); //solve problum
}
|
{
for (idx, item) in self.iter().enumerate() {
print!("{position:>3}", position = item);
if idx % N == (N - 1) {
println!();
}
}
}
|
identifier_body
|
knight_tour.rs
|
extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool;
fn printSolution(&self);
fn solveKT(&mut self);
}
impl<S> ChessFunc for DMatrix<S>
where
S: Scalar + Display + FromPrimitive,
{
fn solveKT(&mut self) {
let moves = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
].to_vec(); //knight movement
if self.solveKTUtil(0, 0, 1, &moves) {
self.printSolution();
} else {
println!("Solution does not exist");
}
}
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool {
if movei == N * N {
true
} else {
let mut result = false;
for cnt in 0..moves.len() {
let next_x: isize = x + moves[cnt].0;
let next_y: isize = y + moves[cnt].1;
|
}
if self.solveKTUtil(next_x, next_y, movei + 1, moves) {
result = true;
break;
} else {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_isize(-1).unwrap();
}
}
}
}
result
}
}
fn printSolution(&self) {
for (idx, item) in self.iter().enumerate() {
print!("{position:>3}", position = item);
if idx % N == (N - 1) {
println!();
}
}
}
fn isSafe(&self, x: isize, y: isize) -> bool {
let mut result = false;
//println!("({},{})", x, y);
match ((x + 1) as usize, (y + 1) as usize) {
(1...N, 1...N) => {
match self.iter().nth((y * N as isize + x) as usize) {
Some(sc) => {
let temp: S = FromPrimitive::from_isize(-1).unwrap();
if temp == *sc {
result = true;
}
}
None => {}
};
}
_ => {}
}
//println!("({})", result);
result
}
}
fn main() {
let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension
let mut chessmap = DMatrix::from_fn_generic(DimN, DimN, |r, c| match (r, c) {
(0, 0) => 0,
_ => -1,
}); //initialize matrix (0,0) set 0 and the others set -1
//chessmap.printSolution();
chessmap.solveKT(); //solve problum
}
|
if self.isSafe(next_x, next_y) {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_usize(movei).unwrap();
|
random_line_split
|
knight_tour.rs
|
extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool;
fn printSolution(&self);
fn solveKT(&mut self);
}
impl<S> ChessFunc for DMatrix<S>
where
S: Scalar + Display + FromPrimitive,
{
fn solveKT(&mut self) {
let moves = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
].to_vec(); //knight movement
if self.solveKTUtil(0, 0, 1, &moves) {
self.printSolution();
} else {
println!("Solution does not exist");
}
}
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool {
if movei == N * N {
true
} else {
let mut result = false;
for cnt in 0..moves.len() {
let next_x: isize = x + moves[cnt].0;
let next_y: isize = y + moves[cnt].1;
if self.isSafe(next_x, next_y) {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_usize(movei).unwrap();
}
if self.solveKTUtil(next_x, next_y, movei + 1, moves) {
result = true;
break;
} else {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_isize(-1).unwrap();
}
}
}
}
result
}
}
fn printSolution(&self) {
for (idx, item) in self.iter().enumerate() {
print!("{position:>3}", position = item);
if idx % N == (N - 1) {
println!();
}
}
}
fn isSafe(&self, x: isize, y: isize) -> bool {
let mut result = false;
//println!("({},{})", x, y);
match ((x + 1) as usize, (y + 1) as usize) {
(1...N, 1...N) => {
match self.iter().nth((y * N as isize + x) as usize) {
Some(sc) => {
let temp: S = FromPrimitive::from_isize(-1).unwrap();
if temp == *sc
|
}
None => {}
};
}
_ => {}
}
//println!("({})", result);
result
}
}
fn main() {
let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension
let mut chessmap = DMatrix::from_fn_generic(DimN, DimN, |r, c| match (r, c) {
(0, 0) => 0,
_ => -1,
}); //initialize matrix (0,0) set 0 and the others set -1
//chessmap.printSolution();
chessmap.solveKT(); //solve problum
}
|
{
result = true;
}
|
conditional_block
|
knight_tour.rs
|
extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool;
fn printSolution(&self);
fn solveKT(&mut self);
}
impl<S> ChessFunc for DMatrix<S>
where
S: Scalar + Display + FromPrimitive,
{
fn solveKT(&mut self) {
let moves = [
(2, 1),
(1, 2),
(-1, 2),
(-2, 1),
(-2, -1),
(-1, -2),
(1, -2),
(2, -1),
].to_vec(); //knight movement
if self.solveKTUtil(0, 0, 1, &moves) {
self.printSolution();
} else {
println!("Solution does not exist");
}
}
fn solveKTUtil(
&mut self,
x: isize,
y: isize,
movei: usize,
moves: &Vec<(isize, isize)>,
) -> bool {
if movei == N * N {
true
} else {
let mut result = false;
for cnt in 0..moves.len() {
let next_x: isize = x + moves[cnt].0;
let next_y: isize = y + moves[cnt].1;
if self.isSafe(next_x, next_y) {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_usize(movei).unwrap();
}
if self.solveKTUtil(next_x, next_y, movei + 1, moves) {
result = true;
break;
} else {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_isize(-1).unwrap();
}
}
}
}
result
}
}
fn printSolution(&self) {
for (idx, item) in self.iter().enumerate() {
print!("{position:>3}", position = item);
if idx % N == (N - 1) {
println!();
}
}
}
fn isSafe(&self, x: isize, y: isize) -> bool {
let mut result = false;
//println!("({},{})", x, y);
match ((x + 1) as usize, (y + 1) as usize) {
(1...N, 1...N) => {
match self.iter().nth((y * N as isize + x) as usize) {
Some(sc) => {
let temp: S = FromPrimitive::from_isize(-1).unwrap();
if temp == *sc {
result = true;
}
}
None => {}
};
}
_ => {}
}
//println!("({})", result);
result
}
}
fn
|
() {
let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension
let mut chessmap = DMatrix::from_fn_generic(DimN, DimN, |r, c| match (r, c) {
(0, 0) => 0,
_ => -1,
}); //initialize matrix (0,0) set 0 and the others set -1
//chessmap.printSolution();
chessmap.solveKT(); //solve problum
}
|
main
|
identifier_name
|
apr.rs
|
#![allow(non_camel_case_types)]
use std::ffi::CString;
use std::marker::PhantomData;
use ffi;
use wrapper::{Wrapper, from_char_ptr, WrappedType, FromRaw};
pub enum HookOrder {
REALLY_FIRST, // run this hook first, before ANYTHING
FIRST, // run this hook first
MIDDLE, // run this hook somewhere
LAST, // run this hook after every other hook which is defined
REALLY_LAST // run this hook last, after EVERYTHING
}
impl Into<::libc::c_int> for HookOrder {
fn into(self) -> ::libc::c_int {
match self {
HookOrder::REALLY_FIRST => ffi::APR_HOOK_REALLY_FIRST,
HookOrder::FIRST => ffi::APR_HOOK_FIRST,
HookOrder::MIDDLE => ffi::APR_HOOK_MIDDLE,
HookOrder::LAST => ffi::APR_HOOK_LAST,
HookOrder::REALLY_LAST => ffi::APR_HOOK_REALLY_LAST
}
}
}
pub type Table = Wrapper<ffi::apr_table_t>;
impl Table {
pub fn get<'a, T: Into<Vec<u8>>>(&self, key: T) -> Option<&'a str> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return None
};
from_char_ptr(
unsafe { ffi::apr_table_get(self.ptr, key.as_ptr()) }
)
}
pub fn set<T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
ffi::apr_table_set(
self.ptr,
key.as_ptr(),
val.as_ptr()
)
};
Ok(())
}
pub fn add<T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
ffi::apr_table_add(
self.ptr,
key.as_ptr(),
val.as_ptr()
)
};
Ok(())
}
pub fn iter(&self) -> TableIter {
let ptr = unsafe { ffi::apr_table_elts(self.ptr) };
let raw: &ffi::apr_array_header_t = unsafe { &*ptr };
TableIter {
array_header: raw,
next_idx: 0
}
}
}
pub type Pool = Wrapper<ffi::apr_pool_t>;
pub struct TableIter<'a> {
pub array_header: &'a ffi::apr_array_header_t,
pub next_idx: usize,
}
impl<'a> Iterator for TableIter<'a> {
type Item = (&'a str, Option<&'a str>);
fn next(&mut self) -> Option<(&'a str, Option<&'a str>)> {
if self.next_idx!= self.array_header.nelts as usize {
let mut elts = self.array_header.elts as *const ffi::apr_table_entry_t;
elts = unsafe { elts.offset(self.next_idx as isize) };
self.next_idx += 1;
let key = from_char_ptr(unsafe { (*elts).key }).unwrap();
let val_result = from_char_ptr(unsafe { (*elts).val });
Some((key, val_result))
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.array_header.nelts as usize - self.next_idx;
(rem, Some(rem))
}
}
pub struct ArrayHeaderIter<T> {
pub phantom: PhantomData<T>,
pub array_header: *mut ffi::apr_array_header_t,
pub next_idx: usize,
}
impl<T: Copy + WrappedType + FromRaw<*mut <T as WrappedType>::wrapped_type>> Iterator for ArrayHeaderIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.array_header.is_null() {
return None;
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
if self.next_idx!= array_header.nelts as usize {
let mut elt = array_header.elts as *const T::wrapped_type;
elt = unsafe { elt.offset(self.next_idx as isize)};
self.next_idx += 1;
T::from_raw(elt as *mut <T as WrappedType>::wrapped_type)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.array_header.is_null() {
return (0, None);
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
let rem = array_header.nelts as usize - self.next_idx;
(rem, Some(rem))
}
}
pub fn apr_version_string<'a>() -> Option<&'a str> {
from_char_ptr(
unsafe { ffi::apr_version_string() }
)
}
pub fn apu_version_string<'a>() -> Option<&'a str> {
from_char_ptr(
unsafe { ffi::apu_version_string() }
)
}
pub fn time_now() -> i64
|
{
unsafe {
ffi::apr_time_now()
}
}
|
identifier_body
|
|
apr.rs
|
#![allow(non_camel_case_types)]
use std::ffi::CString;
use std::marker::PhantomData;
use ffi;
use wrapper::{Wrapper, from_char_ptr, WrappedType, FromRaw};
pub enum HookOrder {
REALLY_FIRST, // run this hook first, before ANYTHING
FIRST, // run this hook first
MIDDLE, // run this hook somewhere
LAST, // run this hook after every other hook which is defined
REALLY_LAST // run this hook last, after EVERYTHING
}
impl Into<::libc::c_int> for HookOrder {
fn into(self) -> ::libc::c_int {
match self {
HookOrder::REALLY_FIRST => ffi::APR_HOOK_REALLY_FIRST,
HookOrder::FIRST => ffi::APR_HOOK_FIRST,
HookOrder::MIDDLE => ffi::APR_HOOK_MIDDLE,
HookOrder::LAST => ffi::APR_HOOK_LAST,
HookOrder::REALLY_LAST => ffi::APR_HOOK_REALLY_LAST
}
}
}
pub type Table = Wrapper<ffi::apr_table_t>;
impl Table {
pub fn get<'a, T: Into<Vec<u8>>>(&self, key: T) -> Option<&'a str> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return None
};
from_char_ptr(
unsafe { ffi::apr_table_get(self.ptr, key.as_ptr()) }
)
}
pub fn
|
<T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
ffi::apr_table_set(
self.ptr,
key.as_ptr(),
val.as_ptr()
)
};
Ok(())
}
pub fn add<T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
ffi::apr_table_add(
self.ptr,
key.as_ptr(),
val.as_ptr()
)
};
Ok(())
}
pub fn iter(&self) -> TableIter {
let ptr = unsafe { ffi::apr_table_elts(self.ptr) };
let raw: &ffi::apr_array_header_t = unsafe { &*ptr };
TableIter {
array_header: raw,
next_idx: 0
}
}
}
pub type Pool = Wrapper<ffi::apr_pool_t>;
pub struct TableIter<'a> {
pub array_header: &'a ffi::apr_array_header_t,
pub next_idx: usize,
}
impl<'a> Iterator for TableIter<'a> {
type Item = (&'a str, Option<&'a str>);
fn next(&mut self) -> Option<(&'a str, Option<&'a str>)> {
if self.next_idx!= self.array_header.nelts as usize {
let mut elts = self.array_header.elts as *const ffi::apr_table_entry_t;
elts = unsafe { elts.offset(self.next_idx as isize) };
self.next_idx += 1;
let key = from_char_ptr(unsafe { (*elts).key }).unwrap();
let val_result = from_char_ptr(unsafe { (*elts).val });
Some((key, val_result))
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.array_header.nelts as usize - self.next_idx;
(rem, Some(rem))
}
}
pub struct ArrayHeaderIter<T> {
pub phantom: PhantomData<T>,
pub array_header: *mut ffi::apr_array_header_t,
pub next_idx: usize,
}
impl<T: Copy + WrappedType + FromRaw<*mut <T as WrappedType>::wrapped_type>> Iterator for ArrayHeaderIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.array_header.is_null() {
return None;
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
if self.next_idx!= array_header.nelts as usize {
let mut elt = array_header.elts as *const T::wrapped_type;
elt = unsafe { elt.offset(self.next_idx as isize)};
self.next_idx += 1;
T::from_raw(elt as *mut <T as WrappedType>::wrapped_type)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.array_header.is_null() {
return (0, None);
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
let rem = array_header.nelts as usize - self.next_idx;
(rem, Some(rem))
}
}
pub fn apr_version_string<'a>() -> Option<&'a str> {
from_char_ptr(
unsafe { ffi::apr_version_string() }
)
}
pub fn apu_version_string<'a>() -> Option<&'a str> {
from_char_ptr(
unsafe { ffi::apu_version_string() }
)
}
pub fn time_now() -> i64 {
unsafe {
ffi::apr_time_now()
}
}
|
set
|
identifier_name
|
apr.rs
|
#![allow(non_camel_case_types)]
use std::ffi::CString;
use std::marker::PhantomData;
use ffi;
use wrapper::{Wrapper, from_char_ptr, WrappedType, FromRaw};
pub enum HookOrder {
REALLY_FIRST, // run this hook first, before ANYTHING
FIRST, // run this hook first
MIDDLE, // run this hook somewhere
LAST, // run this hook after every other hook which is defined
REALLY_LAST // run this hook last, after EVERYTHING
}
impl Into<::libc::c_int> for HookOrder {
fn into(self) -> ::libc::c_int {
match self {
HookOrder::REALLY_FIRST => ffi::APR_HOOK_REALLY_FIRST,
HookOrder::FIRST => ffi::APR_HOOK_FIRST,
HookOrder::MIDDLE => ffi::APR_HOOK_MIDDLE,
HookOrder::LAST => ffi::APR_HOOK_LAST,
HookOrder::REALLY_LAST => ffi::APR_HOOK_REALLY_LAST
}
}
}
pub type Table = Wrapper<ffi::apr_table_t>;
impl Table {
pub fn get<'a, T: Into<Vec<u8>>>(&self, key: T) -> Option<&'a str> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return None
};
from_char_ptr(
unsafe { ffi::apr_table_get(self.ptr, key.as_ptr()) }
)
}
pub fn set<T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
ffi::apr_table_set(
self.ptr,
key.as_ptr(),
val.as_ptr()
)
};
Ok(())
}
pub fn add<T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
ffi::apr_table_add(
self.ptr,
key.as_ptr(),
val.as_ptr()
)
};
Ok(())
}
pub fn iter(&self) -> TableIter {
let ptr = unsafe { ffi::apr_table_elts(self.ptr) };
let raw: &ffi::apr_array_header_t = unsafe { &*ptr };
TableIter {
array_header: raw,
next_idx: 0
}
}
}
pub type Pool = Wrapper<ffi::apr_pool_t>;
pub struct TableIter<'a> {
pub array_header: &'a ffi::apr_array_header_t,
pub next_idx: usize,
}
impl<'a> Iterator for TableIter<'a> {
type Item = (&'a str, Option<&'a str>);
fn next(&mut self) -> Option<(&'a str, Option<&'a str>)> {
if self.next_idx!= self.array_header.nelts as usize {
let mut elts = self.array_header.elts as *const ffi::apr_table_entry_t;
elts = unsafe { elts.offset(self.next_idx as isize) };
self.next_idx += 1;
let key = from_char_ptr(unsafe { (*elts).key }).unwrap();
let val_result = from_char_ptr(unsafe { (*elts).val });
Some((key, val_result))
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let rem = self.array_header.nelts as usize - self.next_idx;
(rem, Some(rem))
}
}
pub struct ArrayHeaderIter<T> {
pub phantom: PhantomData<T>,
pub array_header: *mut ffi::apr_array_header_t,
pub next_idx: usize,
}
impl<T: Copy + WrappedType + FromRaw<*mut <T as WrappedType>::wrapped_type>> Iterator for ArrayHeaderIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.array_header.is_null() {
return None;
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
if self.next_idx!= array_header.nelts as usize {
let mut elt = array_header.elts as *const T::wrapped_type;
elt = unsafe { elt.offset(self.next_idx as isize)};
self.next_idx += 1;
|
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.array_header.is_null() {
return (0, None);
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
let rem = array_header.nelts as usize - self.next_idx;
(rem, Some(rem))
}
}
pub fn apr_version_string<'a>() -> Option<&'a str> {
from_char_ptr(
unsafe { ffi::apr_version_string() }
)
}
pub fn apu_version_string<'a>() -> Option<&'a str> {
from_char_ptr(
unsafe { ffi::apu_version_string() }
)
}
pub fn time_now() -> i64 {
unsafe {
ffi::apr_time_now()
}
}
|
T::from_raw(elt as *mut <T as WrappedType>::wrapped_type)
|
random_line_split
|
16835_H2.rs
|
Per(s)PSA @ damp 02% PSA @ damp 05% PSA @ damp 07% PSA @ damp 10% PSA @ damp 20% PSA @ damp 30% (m/s/s)
0.000 1.4743128E+000 1.4743128E+000 1.4743128E+000 1.4743128E+000 1.4743128E+000 1.4743128E+000
0.010 1.4791120E+000 1.4787466E+000 1.4785237E+000 1.4781326E+000 1.4764196E+000 1.4751683E+000
0.020 1.5104053E+000 1.4821162E+000 1.4854322E+000 1.4938033E+000 1.4992797E+000 1.4957132E+000
0.030 2.0300949E+000 1.8057411E+000 1.7141063E+000 1.6167605E+000 1.5549145E+000 1.5309305E+000
0.040 2.5082750E+000 1.9498655E+000 1.8391980E+000 1.7319697E+000 1.5800686E+000 1.5644211E+000
0.050 4.8461270E+000 3.4471936E+000 2.8746629E+000 2.3277245E+000 1.8197466E+000 1.6667596E+000
0.075 6.9321809E+000 4.1750355E+000 3.6423223E+000 3.1330619E+000 2.3033800E+000 1.8765230E+000
0.100 5.8347020E+000 4.0264606E+000 3.6516285E+000 3.3645494E+000 2.4336464E+000 1.8784761E+000
0.110 6.8800373E+000 5.2080259E+000 4.4664397E+000 3.7068100E+000 2.4952366E+000 1.9546239E+000
0.120 7.5511932E+000 5.9672294E+000 5.1670566E+000 4.2600856E+000 2.6474896E+000 1.9577156E+000
0.130 7.2483773E+000 5.8144927E+000 4.9852977E+000 4.1228681E+000 2.5400107E+000 1.8703634E+000
0.140 9.2777138E+000 6.1754375E+000 5.0717311E+000 4.0340133E+000 2.5089262E+000 1.9307493E+000
0.150 5.5462456E+000 4.2757444E+000 3.9557984E+000 3.5143046E+000 2.5010145E+000 1.9527456E+000
0.160 4.7255850E+000 3.3132939E+000 3.1817744E+000 3.0361302E+000 2.4035537E+000 1.9198170E+000
0.170 6.4875460E+000 3.9002388E+000 3.1392715E+000 2.8508184E+000 2.2941956E+000 1.8586155E+000
0.180 5.4046626E+000 3.7528958E+000 3.1303315E+000 2.7469754E+000 2.1882258E+000 1.7847651E+000
0.190 4.3958736E+000 2.9758863E+000 2.6868181E+000 2.5421121E+000 2.0857878E+000 1.7060608E+000
|
0.280 4.0103836E+000 2.8828108E+000 2.3853471E+000 1.8648334E+000 1.2753470E+000 1.0055252E+000
0.300 2.8487566E+000 2.2245429E+000 1.9282485E+000 1.5859742E+000 1.0897597E+000 8.9366448E-001
0.320 2.0230498E+000 1.5607424E+000 1.4466788E+000 1.2987298E+000 9.3179417E-001 8.1396568E-001
0.340 1.5434318E+000 1.3516218E+000 1.2678304E+000 1.1435379E+000 9.1418099E-001 8.1401366E-001
0.360 1.6197417E+000 1.2766441E+000 1.1647146E+000 1.0412244E+000 9.1291434E-001 8.0921459E-001
0.380 2.1351445E+000 1.3414153E+000 1.0929837E+000 1.0243293E+000 9.0772921E-001 8.0161196E-001
0.400 2.4073822E+000 1.4509511E+000 1.1619300E+000 1.0171230E+000 9.0257490E-001 7.9341346E-001
0.420 1.5019743E+000 1.0988272E+000 1.0563077E+000 1.0217791E+000 8.9994162E-001 7.8675127E-001
0.440 1.2533405E+000 1.1050407E+000 1.0762311E+000 1.0340325E+000 9.0094405E-001 7.8387702E-001
0.460 1.3831853E+000 1.1328344E+000 1.0983303E+000 1.0496888E+000 9.0524000E-001 7.8254128E-001
0.480 1.2186533E+000 1.1572502E+000 1.1193244E+000 1.0658578E+000 9.0963733E-001 7.8011674E-001
0.500 1.2423385E+000 1.1780050E+000 1.1375464E+000 1.0798609E+000 9.1233033E-001 7.7583003E-001
0.550 1.3254666E+000 1.2183512E+000 1.1700618E+000 1.1018404E+000 9.0795618E-001 7.5661606E-001
0.600 1.5539391E+000 1.3214510E+000 1.2103878E+000 1.1078017E+000 8.9475304E-001 7.3920852E-001
0.650 1.8162208E+000 1.4987989E+000 1.3261404E+000 1.1643020E+000 9.0324318E-001 7.5938755E-001
0.700 1.8461072E+000 1.4961747E+000 1.3444467E+000 1.1742499E+000 9.3000489E-001 7.6964641E-001
0.750 2.1112227E+000 1.4190209E+000 1.2855110E+000 1.1710912E+000 9.3050897E-001 7.6092941E-001
0.800 1.9626719E+000 1.4452434E+000 1.3123235E+000 1.1526074E+000 9.0919733E-001 7.3777688E-001
0.850 1.6712633E+000 1.4395746E+000 1.3079906E+000 1.1385000E+000 8.7737238E-001 7.0773762E-001
0.900 1.5820955E+000 1.3648593E+000 1.2408338E+000 1.0817774E+000 8.4640551E-001 6.8055594E-001
0.950 1.4297174E+000 1.2343804E+000 1.1331412E+000 1.0453233E+000 8.1489825E-001 6.5273100E-001
1.000 1.2654948E+000 1.1537976E+000 1.0923116E+000 1.0082440E+000 7.8691655E-001 6.3014054E-001
1.100 1.1265328E+000 1.0375419E+000 9.8371464E-001 9.0973252E-001 7.1306300E-001 5.7234973E-001
1.200 9.7965991E-001 9.0319633E-001 8.5702091E-001 7.9368961E-001 6.2536055E-001 5.0450939E-001
1.300 8.9621854E-001 7.7885020E-001 7.3318434E-001 6.7476881E-001 5.3475833E-001 4.3463489E-001
1.400 8.5393077E-001 6.8195105E-001 6.4306241E-001 5.9019750E-001 4.5046195E-001 3.6755455E-001
1.500 6.5240300E-001 5.8339238E-001 5.5011833E-001 5.0592983E-001 3.9108130E-001 3.2101819E-001
1.600 5.6587386E-001 5.1109087E-001 4.7818339E-001 4.3346316E-001 3.4328637E-001 3.0174962E-001
1.700 4.8711962E-001 4.4270831E-001 4.1594651E-001 3.7935179E-001 3.2167101E-001 2.8283659E-001
1.800 4.0831387E-001 3.7456813E-001 3.6292779E-001 3.4656391E-001 3.0061692E-001 2.6462480E-001
1.900 3.6895099E-001 3.4807315E-001 3.3739716E-001 3.2253146E-001 2.8039324E-001 2.4722293E-001
2.000 3.3760357E-001 3.2226712E-001 3.1268153E-001 2.9926187E-001 2.6104486E-001 2.3075765E-001
2.200 2.8630957E-001 2.7425823E-001 2.6669079E-001 2.5606927E-001 2.2542880E-001 2.0067218E-001
2.400 2.4205402E-001 2.3234786E-001 2.2648415E-001 2.1820822E-001 1.9413969E-001 1.7433445E-001
2.600 2.0583928E-001 1.9782871E-001 1.9281517E-001 1.8597580E-001 1.6723998E-001 1.5154393E-001
2.800 1.7739289E-001 1.6915064E-001 1.6523111E-001 1.5965641E-001 1.4436261E-001 1.3201414E-001
3.000 1.7278691E-001 1.4506641E-001 1.4204361E-001 1.3770631E-001 1.2504922E-001 1.1535587E-001
3.200 1.3849485E-001 1.2493035E-001 1.2258517E-001 1.1923940E-001 1.0910797E-001 1.0117164E-001
3.400 1.1899579E-001 1.0828649E-001 1.0631829E-001 1.0369612E-001 9.5763710E-002 8.9099170E-002
3.600 1.0711869E-001 9.4356310E-002 9.2820900E-002 9.0626190E-002 8.4419910E-002 7.8826930E-002
3.800 9.2348810E-002 8.4503140E-002 8.1430990E-002 7.9698930E-002 7.4739100E-002 7.0254120E-002
4.000 8.6996990E-002 7.4908910E-002 7.1776260E-002 7.0438390E-002 6.6453370E-002 6.2876810E-002
4.200 7.4932020E-002 6.5488150E-002 6.3556800E-002 6.2533620E-002 5.9340350E-002 5.6497090E-002
4.400 6.6791380E-002 5.8505680E-002 5.6537020E-002 5.5761600E-002 5.3207100E-002 5.0953270E-002
4.600 5.7294090E-002 5.1143870E-002 5.0513240E-002 4.9933210E-002 4.7901560E-002 4.6115170E-002
4.800 4.7525730E-002 4.5595450E-002 4.5328130E-002 4.4903290E-002 4.3314110E-002 4.1885610E-002
5.000 4.1269730E-002 4.1030050E-002 4.0845880E-002 4.0539440E-002 3.9326380E-002 3.8166360E-002
5.500 3.2121350E-002 3.2073520E-002 3.2022380E-002 3.1910040E-002 3.1344030E-002 3.0665110E-002
6.000 2.5598220E-002 2.5647890E-002 2.5663590E-002 2.5658400E-002 2.5458150E-002 2.5077150E-002
6.500 2.0824120E-002 2.0920780E-002 2.0969310E-002 2.1020040E-002 2.1025590E-002 2.0847270E-002
7.000 1.7248240E-002 1.7363130E-002 1.7426760E-002 1.7503920E-002 1.7621200E-002 1.7576880E-002
7.500 1.4511930E-002 1.4630040E-002 1.4698730E-002 1.4786390E-002 1.4961530E-002 1.4998520E-002
8.000 1.2376400E-002 1.2491180E-002 1.2559270E-002 1.2648470E-002 1.2850160E-002 1.2933230E-002
8.500 1.0680150E-002 1.0788260E-002 1.0852870E-002 1.0939400E-002 1.1149060E-002 1.1257690E-002
9.000 9.3111200E-003 9.4114600E-003 9.4716000E-003 9.5533700E-003 9.7605100E-003 9.8824300E-003
9.500 8.1911800E-003 8.2834000E-003 8.3386100E-003 8.4146200E-003 8.6137400E-003 8.7405000E-003
10.00 7.2630500E-003 7.3477600E-003 7.3981900E-003 7.4683800E-003 7.6565000E-003 7.7829400E-003
-1 1.1024949E-001 1.1024949E-001 1.1024949E-001 1.1024949E-001 1.1024949E-001 1.1024949E-001
|
0.200 4.6951294E+000 3.5387561E+000 2.9914527E+000 2.4170172E+000 1.9933550E+000 1.6257334E+000
0.220 5.5433970E+000 3.4664059E+000 2.8443663E+000 2.3755868E+000 1.8310739E+000 1.4639518E+000
0.240 4.2906198E+000 2.8333371E+000 2.5657334E+000 2.2435493E+000 1.6571624E+000 1.3000077E+000
0.260 3.8741798E+000 2.8604641E+000 2.4451344E+000 2.1105673E+000 1.4678906E+000 1.1419977E+000
|
random_line_split
|
main.rs
|
// main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections, env, io};
extern crate konane;
use konane::{Game, Occupancy};
use konane::Position as Pos;
extern crate uuid;
use uuid::*;
#[macro_use]
extern crate error_chain;
extern crate image as piston_image;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate piston_window;
extern crate sprite;
extern crate drag_controller;
use piston_image::GenericImage;
use gfx_device_gl::{Factory as GLFactory, Resources as GLResources};
use piston_window::*;
use sprite::*;
use drag_controller::*;
#[macro_use]
extern crate clap;
extern crate rand;
use rand::{Rng, StdRng};
const TILE_SIZE: u32 = 75;
const WHITE_PIECE_DATA: &'static [u8] = include_bytes!("../resources/white_piece.png");
const BLACK_PIECE_DATA: &'static [u8] = include_bytes!("../resources/black_piece.png");
const EMPTY_PIECE_DATA: &'static [u8] = include_bytes!("../resources/empty_piece.png");
fn main() {
let mut clap_app = clap::App::new("kōnane")
.version(crate_version!())
.author(crate_authors!())
.about("The ancient polynesian game of kōnane")
.arg(clap::Arg::with_name("generate bash completions")
.short("G")
.long("gen-bash-completions")
.help("Generate a bash completion file to standard output"))
.setting(clap::AppSettings::ColoredHelp);
let matches = clap_app.clone().get_matches();
if matches.is_present("generate bash completions") {
clap_app.gen_completions_to(env::args().nth(0).expect("no executable name found"),
clap::Shell::Bash,
&mut io::stdout());
} else {
setup(matches).expect("kōnane encountered an error");
}
}
mod errors {
error_chain! {
types {
Error, ErrorKind, ChainErr, Result;
}
links {
::konane::errors::Error, ::konane::errors::ErrorKind, Game;
}
foreign_links {
::clap::Error, Clap, "clap error";
::uuid::ParseError, UUIDParse, "UUID parse error";
::std::io::Error, IO, "I/O error";
::piston_image::ImageError, PistonImage, "Piston engine image error";
::gfx_core::factory::CombinedError, GFXCombined, "GFX engine combined error";
}
errors {
PistonGlyph(inner: ::piston_window::GlyphError) {
description("Piston engine glyph error")
display("Piston engine glyph error: {:?}", inner)
}
}
}
impl From<::piston_window::GlyphError> for Error {
fn from(inner: ::piston_window::GlyphError) -> Error { ErrorKind::PistonGlyph(inner).into() }
}
}
struct Gam
|
> {
args: clap::ArgMatches<'a>,
textures: SpriteTextures,
window: &'a mut PistonWindow,
drag_ctrl: &'a mut DragController,
scene: &'a mut Scene<Texture<GLResources>>,
sprite_map: &'a mut collections::HashMap<Pos, Uuid>,
game: &'a mut Game,
rng: &'a mut StdRng,
}
struct SpriteTextures {
white_piece: Texture<GLResources>,
black_piece: Texture<GLResources>,
empty_piece: Texture<GLResources>,
}
fn setup(matches: clap::ArgMatches) -> errors::Result<()> {
let mut window: PistonWindow =
try!(WindowSettings::new("kōnane", [TILE_SIZE * 10, TILE_SIZE * 10]).exit_on_esc(true).build());
let textures = SpriteTextures {
white_piece: try!(load_texture(WHITE_PIECE_DATA, &mut window.factory)),
black_piece: try!(load_texture(BLACK_PIECE_DATA, &mut window.factory)),
empty_piece: try!(load_texture(EMPTY_PIECE_DATA, &mut window.factory)),
};
let mut rng = try!(StdRng::new());
let cxt = GameContext {
args: matches,
textures: textures,
window: &mut window,
drag_ctrl: &mut DragController::new(),
scene: &mut Scene::new(),
sprite_map: &mut collections::HashMap::new(),
game: &mut if rng.gen() { Game::new_white() } else { Game::new_black() },
rng: &mut rng,
};
setup_scene(cxt).and_then(run)
}
fn load_texture(texture_data: &[u8], factory: &mut GLFactory) -> errors::Result<Texture<GLResources>> {
let texture_image = try!(piston_image::load_from_memory_with_format(texture_data,
piston_image::ImageFormat::PNG))
.resize(TILE_SIZE, TILE_SIZE, piston_image::Nearest);
let texture_buffer = texture_image.as_rgba8().cloned().unwrap_or_else(|| texture_image.to_rgba());
Ok(try!(Texture::from_image(factory, &texture_buffer, &TextureSettings::new())))
}
fn setup_scene(cxt: GameContext) -> errors::Result<GameContext> {
for x in 0..10u8 {
for y in 0..10u8 {
if (x + y) % 2 == 0 {
} else {
}
}
}
Ok(cxt)
}
fn run(cxt: GameContext) -> errors::Result<()> {
let mut events = cxt.window.events();
while let Some(event) = events.next(cxt.window) {
cxt.scene.event(&event);
}
Ok(())
}
|
eContext<'a
|
identifier_name
|
main.rs
|
// main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections, env, io};
extern crate konane;
use konane::{Game, Occupancy};
use konane::Position as Pos;
extern crate uuid;
use uuid::*;
#[macro_use]
extern crate error_chain;
extern crate image as piston_image;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate piston_window;
extern crate sprite;
extern crate drag_controller;
use piston_image::GenericImage;
use gfx_device_gl::{Factory as GLFactory, Resources as GLResources};
use piston_window::*;
use sprite::*;
use drag_controller::*;
#[macro_use]
extern crate clap;
extern crate rand;
use rand::{Rng, StdRng};
const TILE_SIZE: u32 = 75;
const WHITE_PIECE_DATA: &'static [u8] = include_bytes!("../resources/white_piece.png");
const BLACK_PIECE_DATA: &'static [u8] = include_bytes!("../resources/black_piece.png");
const EMPTY_PIECE_DATA: &'static [u8] = include_bytes!("../resources/empty_piece.png");
fn main() {
let mut clap_app = clap::App::new("kōnane")
.version(crate_version!())
.author(crate_authors!())
.about("The ancient polynesian game of kōnane")
.arg(clap::Arg::with_name("generate bash completions")
.short("G")
.long("gen-bash-completions")
.help("Generate a bash completion file to standard output"))
.setting(clap::AppSettings::ColoredHelp);
let matches = clap_app.clone().get_matches();
if matches.is_present("generate bash completions") {
clap_app.gen_completions_to(env::args().nth(0).expect("no executable name found"),
clap::Shell::Bash,
&mut io::stdout());
} else {
setup(matches).expect("kōnane encountered an error");
}
}
mod errors {
error_chain! {
types {
Error, ErrorKind, ChainErr, Result;
}
links {
::konane::errors::Error, ::konane::errors::ErrorKind, Game;
}
foreign_links {
::clap::Error, Clap, "clap error";
::uuid::ParseError, UUIDParse, "UUID parse error";
::std::io::Error, IO, "I/O error";
::piston_image::ImageError, PistonImage, "Piston engine image error";
::gfx_core::factory::CombinedError, GFXCombined, "GFX engine combined error";
}
errors {
PistonGlyph(inner: ::piston_window::GlyphError) {
description("Piston engine glyph error")
display("Piston engine glyph error: {:?}", inner)
}
}
}
impl From<::piston_window::GlyphError> for Error {
fn from(inner: ::piston_window::GlyphError) -> Error { ErrorKind::PistonGlyph(inner).into() }
}
}
struct GameContext<'a> {
args: clap::ArgMatches<'a>,
textures: SpriteTextures,
window: &'a mut PistonWindow,
drag_ctrl: &'a mut DragController,
scene: &'a mut Scene<Texture<GLResources>>,
sprite_map: &'a mut collections::HashMap<Pos, Uuid>,
game: &'a mut Game,
rng: &'a mut StdRng,
}
struct SpriteTextures {
white_piece: Texture<GLResources>,
black_piece: Texture<GLResources>,
empty_piece: Texture<GLResources>,
}
fn setup(matches: clap::ArgMatches) -> errors::Result<()> {
|
fn
load_texture(texture_data: &[u8], factory: &mut GLFactory) -> errors::Result<Texture<GLResources>> {
let texture_image = try!(piston_image::load_from_memory_with_format(texture_data,
piston_image::ImageFormat::PNG))
.resize(TILE_SIZE, TILE_SIZE, piston_image::Nearest);
let texture_buffer = texture_image.as_rgba8().cloned().unwrap_or_else(|| texture_image.to_rgba());
Ok(try!(Texture::from_image(factory, &texture_buffer, &TextureSettings::new())))
}
fn setup_scene(cxt: GameContext) -> errors::Result<GameContext> {
for x in 0..10u8 {
for y in 0..10u8 {
if (x + y) % 2 == 0 {
} else {
}
}
}
Ok(cxt)
}
fn run(cxt: GameContext) -> errors::Result<()> {
let mut events = cxt.window.events();
while let Some(event) = events.next(cxt.window) {
cxt.scene.event(&event);
}
Ok(())
}
|
let mut window: PistonWindow =
try!(WindowSettings::new("kōnane", [TILE_SIZE * 10, TILE_SIZE * 10]).exit_on_esc(true).build());
let textures = SpriteTextures {
white_piece: try!(load_texture(WHITE_PIECE_DATA, &mut window.factory)),
black_piece: try!(load_texture(BLACK_PIECE_DATA, &mut window.factory)),
empty_piece: try!(load_texture(EMPTY_PIECE_DATA, &mut window.factory)),
};
let mut rng = try!(StdRng::new());
let cxt = GameContext {
args: matches,
textures: textures,
window: &mut window,
drag_ctrl: &mut DragController::new(),
scene: &mut Scene::new(),
sprite_map: &mut collections::HashMap::new(),
game: &mut if rng.gen() { Game::new_white() } else { Game::new_black() },
rng: &mut rng,
};
setup_scene(cxt).and_then(run)
}
|
identifier_body
|
main.rs
|
// main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections, env, io};
extern crate konane;
use konane::{Game, Occupancy};
use konane::Position as Pos;
extern crate uuid;
use uuid::*;
#[macro_use]
extern crate error_chain;
extern crate image as piston_image;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate piston_window;
extern crate sprite;
extern crate drag_controller;
use piston_image::GenericImage;
use gfx_device_gl::{Factory as GLFactory, Resources as GLResources};
use piston_window::*;
use sprite::*;
use drag_controller::*;
#[macro_use]
extern crate clap;
extern crate rand;
use rand::{Rng, StdRng};
const TILE_SIZE: u32 = 75;
const WHITE_PIECE_DATA: &'static [u8] = include_bytes!("../resources/white_piece.png");
const BLACK_PIECE_DATA: &'static [u8] = include_bytes!("../resources/black_piece.png");
const EMPTY_PIECE_DATA: &'static [u8] = include_bytes!("../resources/empty_piece.png");
fn main() {
let mut clap_app = clap::App::new("kōnane")
.version(crate_version!())
.author(crate_authors!())
.about("The ancient polynesian game of kōnane")
.arg(clap::Arg::with_name("generate bash completions")
.short("G")
.long("gen-bash-completions")
.help("Generate a bash completion file to standard output"))
.setting(clap::AppSettings::ColoredHelp);
let matches = clap_app.clone().get_matches();
if matches.is_present("generate bash completions") {
clap_app.gen_completions_to(env::args().nth(0).expect("no executable name found"),
clap::Shell::Bash,
&mut io::stdout());
} else {
setup(matches).expect("kōnane encountered an error");
}
}
mod errors {
error_chain! {
types {
Error, ErrorKind, ChainErr, Result;
}
links {
::konane::errors::Error, ::konane::errors::ErrorKind, Game;
}
foreign_links {
::clap::Error, Clap, "clap error";
::uuid::ParseError, UUIDParse, "UUID parse error";
::std::io::Error, IO, "I/O error";
::piston_image::ImageError, PistonImage, "Piston engine image error";
::gfx_core::factory::CombinedError, GFXCombined, "GFX engine combined error";
}
errors {
PistonGlyph(inner: ::piston_window::GlyphError) {
description("Piston engine glyph error")
display("Piston engine glyph error: {:?}", inner)
}
}
}
impl From<::piston_window::GlyphError> for Error {
fn from(inner: ::piston_window::GlyphError) -> Error { ErrorKind::PistonGlyph(inner).into() }
}
}
struct GameContext<'a> {
args: clap::ArgMatches<'a>,
textures: SpriteTextures,
window: &'a mut PistonWindow,
drag_ctrl: &'a mut DragController,
scene: &'a mut Scene<Texture<GLResources>>,
sprite_map: &'a mut collections::HashMap<Pos, Uuid>,
game: &'a mut Game,
rng: &'a mut StdRng,
}
struct SpriteTextures {
white_piece: Texture<GLResources>,
black_piece: Texture<GLResources>,
empty_piece: Texture<GLResources>,
}
fn setup(matches: clap::ArgMatches) -> errors::Result<()> {
let mut window: PistonWindow =
try!(WindowSettings::new("kōnane", [TILE_SIZE * 10, TILE_SIZE * 10]).exit_on_esc(true).build());
let textures = SpriteTextures {
white_piece: try!(load_texture(WHITE_PIECE_DATA, &mut window.factory)),
black_piece: try!(load_texture(BLACK_PIECE_DATA, &mut window.factory)),
empty_piece: try!(load_texture(EMPTY_PIECE_DATA, &mut window.factory)),
};
let mut rng = try!(StdRng::new());
let cxt = GameContext {
args: matches,
textures: textures,
window: &mut window,
drag_ctrl: &mut DragController::new(),
scene: &mut Scene::new(),
sprite_map: &mut collections::HashMap::new(),
game: &mut if rng.gen() { Game::new_white() } else { Game::new_black() },
rng: &mut rng,
};
setup_scene(cxt).and_then(run)
}
fn load_texture(texture_data: &[u8], factory: &mut GLFactory) -> errors::Result<Texture<GLResources>> {
let texture_image = try!(piston_image::load_from_memory_with_format(texture_data,
piston_image::ImageFormat::PNG))
.resize(TILE_SIZE, TILE_SIZE, piston_image::Nearest);
let texture_buffer = texture_image.as_rgba8().cloned().unwrap_or_else(|| texture_image.to_rgba());
Ok(try!(Texture::from_image(factory, &texture_buffer, &TextureSettings::new())))
}
fn setup_scene(cxt: GameContext) -> errors::Result<GameContext> {
for x in 0..10u8 {
for y in 0..10u8 {
if (x + y) % 2 == 0 {
|
e {
}
}
}
Ok(cxt)
}
fn run(cxt: GameContext) -> errors::Result<()> {
let mut events = cxt.window.events();
while let Some(event) = events.next(cxt.window) {
cxt.scene.event(&event);
}
Ok(())
}
|
} els
|
conditional_block
|
main.rs
|
// main.rs
// Copyright 2016 Alexander Altman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections, env, io};
extern crate konane;
use konane::{Game, Occupancy};
use konane::Position as Pos;
extern crate uuid;
use uuid::*;
#[macro_use]
extern crate error_chain;
extern crate image as piston_image;
extern crate gfx_core;
extern crate gfx_device_gl;
extern crate piston_window;
extern crate sprite;
extern crate drag_controller;
|
use drag_controller::*;
#[macro_use]
extern crate clap;
extern crate rand;
use rand::{Rng, StdRng};
const TILE_SIZE: u32 = 75;
const WHITE_PIECE_DATA: &'static [u8] = include_bytes!("../resources/white_piece.png");
const BLACK_PIECE_DATA: &'static [u8] = include_bytes!("../resources/black_piece.png");
const EMPTY_PIECE_DATA: &'static [u8] = include_bytes!("../resources/empty_piece.png");
fn main() {
let mut clap_app = clap::App::new("kōnane")
.version(crate_version!())
.author(crate_authors!())
.about("The ancient polynesian game of kōnane")
.arg(clap::Arg::with_name("generate bash completions")
.short("G")
.long("gen-bash-completions")
.help("Generate a bash completion file to standard output"))
.setting(clap::AppSettings::ColoredHelp);
let matches = clap_app.clone().get_matches();
if matches.is_present("generate bash completions") {
clap_app.gen_completions_to(env::args().nth(0).expect("no executable name found"),
clap::Shell::Bash,
&mut io::stdout());
} else {
setup(matches).expect("kōnane encountered an error");
}
}
mod errors {
error_chain! {
types {
Error, ErrorKind, ChainErr, Result;
}
links {
::konane::errors::Error, ::konane::errors::ErrorKind, Game;
}
foreign_links {
::clap::Error, Clap, "clap error";
::uuid::ParseError, UUIDParse, "UUID parse error";
::std::io::Error, IO, "I/O error";
::piston_image::ImageError, PistonImage, "Piston engine image error";
::gfx_core::factory::CombinedError, GFXCombined, "GFX engine combined error";
}
errors {
PistonGlyph(inner: ::piston_window::GlyphError) {
description("Piston engine glyph error")
display("Piston engine glyph error: {:?}", inner)
}
}
}
impl From<::piston_window::GlyphError> for Error {
fn from(inner: ::piston_window::GlyphError) -> Error { ErrorKind::PistonGlyph(inner).into() }
}
}
struct GameContext<'a> {
args: clap::ArgMatches<'a>,
textures: SpriteTextures,
window: &'a mut PistonWindow,
drag_ctrl: &'a mut DragController,
scene: &'a mut Scene<Texture<GLResources>>,
sprite_map: &'a mut collections::HashMap<Pos, Uuid>,
game: &'a mut Game,
rng: &'a mut StdRng,
}
struct SpriteTextures {
white_piece: Texture<GLResources>,
black_piece: Texture<GLResources>,
empty_piece: Texture<GLResources>,
}
fn setup(matches: clap::ArgMatches) -> errors::Result<()> {
let mut window: PistonWindow =
try!(WindowSettings::new("kōnane", [TILE_SIZE * 10, TILE_SIZE * 10]).exit_on_esc(true).build());
let textures = SpriteTextures {
white_piece: try!(load_texture(WHITE_PIECE_DATA, &mut window.factory)),
black_piece: try!(load_texture(BLACK_PIECE_DATA, &mut window.factory)),
empty_piece: try!(load_texture(EMPTY_PIECE_DATA, &mut window.factory)),
};
let mut rng = try!(StdRng::new());
let cxt = GameContext {
args: matches,
textures: textures,
window: &mut window,
drag_ctrl: &mut DragController::new(),
scene: &mut Scene::new(),
sprite_map: &mut collections::HashMap::new(),
game: &mut if rng.gen() { Game::new_white() } else { Game::new_black() },
rng: &mut rng,
};
setup_scene(cxt).and_then(run)
}
fn load_texture(texture_data: &[u8], factory: &mut GLFactory) -> errors::Result<Texture<GLResources>> {
let texture_image = try!(piston_image::load_from_memory_with_format(texture_data,
piston_image::ImageFormat::PNG))
.resize(TILE_SIZE, TILE_SIZE, piston_image::Nearest);
let texture_buffer = texture_image.as_rgba8().cloned().unwrap_or_else(|| texture_image.to_rgba());
Ok(try!(Texture::from_image(factory, &texture_buffer, &TextureSettings::new())))
}
fn setup_scene(cxt: GameContext) -> errors::Result<GameContext> {
for x in 0..10u8 {
for y in 0..10u8 {
if (x + y) % 2 == 0 {
} else {
}
}
}
Ok(cxt)
}
fn run(cxt: GameContext) -> errors::Result<()> {
let mut events = cxt.window.events();
while let Some(event) = events.next(cxt.window) {
cxt.scene.event(&event);
}
Ok(())
}
|
use piston_image::GenericImage;
use gfx_device_gl::{Factory as GLFactory, Resources as GLResources};
use piston_window::*;
use sprite::*;
|
random_line_split
|
event.rs
|
use std::list::*;
use core::cmp::Eq;
use core::option::*;
use transaction::*;
type Listen<A> = @fn(@fn(A)) -> @fn();
struct Event<P,A> {
part : Option<Partition<P>>,
listener : Listen<A>
}
pub impl<P,A : Copy> Event<P,A> {
pub fn never() -> Event<P,A> {
Event {
part : None,
listener : |_| { || {} }
}
}
pub fn new(part : Partition<P>) -> (Event<P,A>, @fn(A))
|
pub fn listen(&self, handler : @fn(A)) -> @fn() {
return (self.listener)(handler);
}
}
fn delete<A: Eq + Copy,B: Copy>(l : &List<(A,B)>, key : &A) -> @List<(A,B)>
{
match l {
&Nil => @Nil,
&Cons((k, v), t) => {
if k == *key { delete(t, key) }
else { @Cons((k, v), delete(t, key)) }
}
}
}
struct EventState<A> {
handlers : @List<(int, @fn(A))>,
nextIx : int
}
|
{
let state = @mut EventState{ handlers : @Nil, nextIx : 0 };
(
Event {
part : Some(part),
listener : |handler| {
let ix = state.nextIx;
state.handlers = @Cons((ix, handler), state.handlers);
state.nextIx = state.nextIx + 1;
|| { state.handlers = delete(state.handlers, &ix) }
}
},
|a| {
for each(state.handlers) |&(_,h)| { h(a) };
}
)
}
|
identifier_body
|
event.rs
|
use std::list::*;
use core::cmp::Eq;
use core::option::*;
use transaction::*;
type Listen<A> = @fn(@fn(A)) -> @fn();
struct Event<P,A> {
part : Option<Partition<P>>,
listener : Listen<A>
}
pub impl<P,A : Copy> Event<P,A> {
pub fn never() -> Event<P,A> {
Event {
part : None,
listener : |_| { || {} }
}
}
pub fn new(part : Partition<P>) -> (Event<P,A>, @fn(A)) {
let state = @mut EventState{ handlers : @Nil, nextIx : 0 };
(
Event {
part : Some(part),
listener : |handler| {
let ix = state.nextIx;
state.handlers = @Cons((ix, handler), state.handlers);
state.nextIx = state.nextIx + 1;
|| { state.handlers = delete(state.handlers, &ix) }
}
},
|a| {
for each(state.handlers) |&(_,h)| { h(a) };
}
)
}
pub fn listen(&self, handler : @fn(A)) -> @fn() {
return (self.listener)(handler);
}
}
|
{
match l {
&Nil => @Nil,
&Cons((k, v), t) => {
if k == *key { delete(t, key) }
else { @Cons((k, v), delete(t, key)) }
}
}
}
struct EventState<A> {
handlers : @List<(int, @fn(A))>,
nextIx : int
}
|
fn delete<A: Eq + Copy,B: Copy>(l : &List<(A,B)>, key : &A) -> @List<(A,B)>
|
random_line_split
|
event.rs
|
use std::list::*;
use core::cmp::Eq;
use core::option::*;
use transaction::*;
type Listen<A> = @fn(@fn(A)) -> @fn();
struct Event<P,A> {
part : Option<Partition<P>>,
listener : Listen<A>
}
pub impl<P,A : Copy> Event<P,A> {
pub fn never() -> Event<P,A> {
Event {
part : None,
listener : |_| { || {} }
}
}
pub fn new(part : Partition<P>) -> (Event<P,A>, @fn(A)) {
let state = @mut EventState{ handlers : @Nil, nextIx : 0 };
(
Event {
part : Some(part),
listener : |handler| {
let ix = state.nextIx;
state.handlers = @Cons((ix, handler), state.handlers);
state.nextIx = state.nextIx + 1;
|| { state.handlers = delete(state.handlers, &ix) }
}
},
|a| {
for each(state.handlers) |&(_,h)| { h(a) };
}
)
}
pub fn
|
(&self, handler : @fn(A)) -> @fn() {
return (self.listener)(handler);
}
}
fn delete<A: Eq + Copy,B: Copy>(l : &List<(A,B)>, key : &A) -> @List<(A,B)>
{
match l {
&Nil => @Nil,
&Cons((k, v), t) => {
if k == *key { delete(t, key) }
else { @Cons((k, v), delete(t, key)) }
}
}
}
struct EventState<A> {
handlers : @List<(int, @fn(A))>,
nextIx : int
}
|
listen
|
identifier_name
|
global_asm_include.rs
|
// ignore-aarch64
// ignore-aarch64_be
// ignore-arm
// ignore-armeb
// ignore-avr
// ignore-bpfel
// ignore-bpfeb
// ignore-hexagon
// ignore-mips
// ignore-mips64
// ignore-msp430
// ignore-powerpc64
// ignore-powerpc64le
// ignore-powerpc
// ignore-r600
// ignore-amdgcn
// ignore-sparc
// ignore-sparcv9
// ignore-sparcel
// ignore-s390x
// ignore-tce
|
// ignore-xcore
// ignore-nvptx
// ignore-nvptx64
// ignore-le32
// ignore-le64
// ignore-amdil
// ignore-amdil64
// ignore-hsail
// ignore-hsail64
// ignore-spir
// ignore-spir64
// ignore-kalimba
// ignore-shave
// ignore-wasm32
// ignore-wasm64
// ignore-emscripten
// compile-flags: -C no-prepopulate-passes
#![feature(global_asm)]
#![crate_type = "lib"]
// CHECK-LABEL: foo
// CHECK: module asm
// CHECK: module asm "{{[[:space:]]+}}jmp baz"
global_asm!(include_str!("foo.s"));
extern "C" {
fn foo();
}
// CHECK-LABEL: @baz
#[no_mangle]
pub unsafe extern "C" fn baz() {}
|
// ignore-thumb
// ignore-thumbeb
|
random_line_split
|
global_asm_include.rs
|
// ignore-aarch64
// ignore-aarch64_be
// ignore-arm
// ignore-armeb
// ignore-avr
// ignore-bpfel
// ignore-bpfeb
// ignore-hexagon
// ignore-mips
// ignore-mips64
// ignore-msp430
// ignore-powerpc64
// ignore-powerpc64le
// ignore-powerpc
// ignore-r600
// ignore-amdgcn
// ignore-sparc
// ignore-sparcv9
// ignore-sparcel
// ignore-s390x
// ignore-tce
// ignore-thumb
// ignore-thumbeb
// ignore-xcore
// ignore-nvptx
// ignore-nvptx64
// ignore-le32
// ignore-le64
// ignore-amdil
// ignore-amdil64
// ignore-hsail
// ignore-hsail64
// ignore-spir
// ignore-spir64
// ignore-kalimba
// ignore-shave
// ignore-wasm32
// ignore-wasm64
// ignore-emscripten
// compile-flags: -C no-prepopulate-passes
#![feature(global_asm)]
#![crate_type = "lib"]
// CHECK-LABEL: foo
// CHECK: module asm
// CHECK: module asm "{{[[:space:]]+}}jmp baz"
global_asm!(include_str!("foo.s"));
extern "C" {
fn foo();
}
// CHECK-LABEL: @baz
#[no_mangle]
pub unsafe extern "C" fn baz()
|
{}
|
identifier_body
|
|
global_asm_include.rs
|
// ignore-aarch64
// ignore-aarch64_be
// ignore-arm
// ignore-armeb
// ignore-avr
// ignore-bpfel
// ignore-bpfeb
// ignore-hexagon
// ignore-mips
// ignore-mips64
// ignore-msp430
// ignore-powerpc64
// ignore-powerpc64le
// ignore-powerpc
// ignore-r600
// ignore-amdgcn
// ignore-sparc
// ignore-sparcv9
// ignore-sparcel
// ignore-s390x
// ignore-tce
// ignore-thumb
// ignore-thumbeb
// ignore-xcore
// ignore-nvptx
// ignore-nvptx64
// ignore-le32
// ignore-le64
// ignore-amdil
// ignore-amdil64
// ignore-hsail
// ignore-hsail64
// ignore-spir
// ignore-spir64
// ignore-kalimba
// ignore-shave
// ignore-wasm32
// ignore-wasm64
// ignore-emscripten
// compile-flags: -C no-prepopulate-passes
#![feature(global_asm)]
#![crate_type = "lib"]
// CHECK-LABEL: foo
// CHECK: module asm
// CHECK: module asm "{{[[:space:]]+}}jmp baz"
global_asm!(include_str!("foo.s"));
extern "C" {
fn foo();
}
// CHECK-LABEL: @baz
#[no_mangle]
pub unsafe extern "C" fn
|
() {}
|
baz
|
identifier_name
|
error.rs
|
use std::error::Error as StdError;
use std::fmt::{self, Display};
/// An error that occurred while attempting to deal with the gateway.
///
/// Note that - from a user standpoint - there should be no situation in which
/// you manually handle these.
#[derive(Clone, Debug)]
pub enum
|
{
/// There was an error building a URL.
BuildingUrl,
/// The connection closed, potentially uncleanly.
Closed(Option<u16>, String),
/// Expected a Hello during a handshake
ExpectedHello,
/// Expected a Ready or an InvalidateSession
InvalidHandshake,
/// An indicator that an unknown opcode was received from the gateway.
InvalidOpCode,
/// When a session Id was expected (for resuming), but was not present.
NoSessionId,
/// Failed to reconnect after a number of attempts.
ReconnectFailure,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
impl StdError for Error {
fn description(&self) -> &str {
match *self {
Error::BuildingUrl => "Error building url",
Error::Closed(_, _) => "Connection closed",
Error::ExpectedHello => "Expected a Hello",
Error::InvalidHandshake => "Expected a valid Handshake",
Error::InvalidOpCode => "Invalid OpCode",
Error::NoSessionId => "No Session Id present when required",
Error::ReconnectFailure => "Failed to Reconnect",
}
}
}
|
Error
|
identifier_name
|
error.rs
|
use std::error::Error as StdError;
use std::fmt::{self, Display};
/// An error that occurred while attempting to deal with the gateway.
///
/// Note that - from a user standpoint - there should be no situation in which
/// you manually handle these.
#[derive(Clone, Debug)]
pub enum Error {
/// There was an error building a URL.
BuildingUrl,
/// The connection closed, potentially uncleanly.
Closed(Option<u16>, String),
/// Expected a Hello during a handshake
ExpectedHello,
/// Expected a Ready or an InvalidateSession
InvalidHandshake,
/// An indicator that an unknown opcode was received from the gateway.
InvalidOpCode,
/// When a session Id was expected (for resuming), but was not present.
NoSessionId,
/// Failed to reconnect after a number of attempts.
ReconnectFailure,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
impl StdError for Error {
fn description(&self) -> &str
|
}
|
{
match *self {
Error::BuildingUrl => "Error building url",
Error::Closed(_, _) => "Connection closed",
Error::ExpectedHello => "Expected a Hello",
Error::InvalidHandshake => "Expected a valid Handshake",
Error::InvalidOpCode => "Invalid OpCode",
Error::NoSessionId => "No Session Id present when required",
Error::ReconnectFailure => "Failed to Reconnect",
}
}
|
identifier_body
|
error.rs
|
use std::error::Error as StdError;
use std::fmt::{self, Display};
/// An error that occurred while attempting to deal with the gateway.
///
/// Note that - from a user standpoint - there should be no situation in which
/// you manually handle these.
#[derive(Clone, Debug)]
pub enum Error {
/// There was an error building a URL.
BuildingUrl,
/// The connection closed, potentially uncleanly.
Closed(Option<u16>, String),
/// Expected a Hello during a handshake
ExpectedHello,
/// Expected a Ready or an InvalidateSession
InvalidHandshake,
/// An indicator that an unknown opcode was received from the gateway.
InvalidOpCode,
/// When a session Id was expected (for resuming), but was not present.
NoSessionId,
/// Failed to reconnect after a number of attempts.
ReconnectFailure,
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
|
match *self {
Error::BuildingUrl => "Error building url",
Error::Closed(_, _) => "Connection closed",
Error::ExpectedHello => "Expected a Hello",
Error::InvalidHandshake => "Expected a valid Handshake",
Error::InvalidOpCode => "Invalid OpCode",
Error::NoSessionId => "No Session Id present when required",
Error::ReconnectFailure => "Failed to Reconnect",
}
}
}
|
impl StdError for Error {
fn description(&self) -> &str {
|
random_line_split
|
os.rs
|
// Copyright 2018 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 ffi::CStr;
use libc::{self, c_int};
use str;
pub use sys::cloudabi::shims::os::*;
pub fn errno() -> i32 {
extern "C" {
#[thread_local]
static errno: c_int;
}
unsafe { errno as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String
|
pub fn exit(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
}
|
{
// cloudlibc's strerror() is guaranteed to be thread-safe. There is
// thus no need to use strerror_r().
str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes())
.unwrap()
.to_owned()
}
|
identifier_body
|
os.rs
|
// Copyright 2018 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 ffi::CStr;
use libc::{self, c_int};
use str;
pub use sys::cloudabi::shims::os::*;
pub fn errno() -> i32 {
extern "C" {
#[thread_local]
static errno: c_int;
}
unsafe { errno as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
// cloudlibc's strerror() is guaranteed to be thread-safe. There is
// thus no need to use strerror_r().
str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes())
.unwrap()
.to_owned()
}
pub fn
|
(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
}
|
exit
|
identifier_name
|
os.rs
|
// Copyright 2018 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 ffi::CStr;
|
use libc::{self, c_int};
use str;
pub use sys::cloudabi::shims::os::*;
pub fn errno() -> i32 {
extern "C" {
#[thread_local]
static errno: c_int;
}
unsafe { errno as i32 }
}
/// Gets a detailed string description for the given error number.
pub fn error_string(errno: i32) -> String {
// cloudlibc's strerror() is guaranteed to be thread-safe. There is
// thus no need to use strerror_r().
str::from_utf8(unsafe { CStr::from_ptr(libc::strerror(errno)) }.to_bytes())
.unwrap()
.to_owned()
}
pub fn exit(code: i32) ->! {
unsafe { libc::exit(code as c_int) }
}
|
random_line_split
|
|
error.rs
|
use crate::codec::{CodecError, Message, ZmtpVersion};
use crate::endpoint::Endpoint;
use crate::endpoint::EndpointError;
use crate::task_handle::TaskError;
use crate::ZmqMessage;
use thiserror::Error;
pub type ZmqResult<T> = Result<T, ZmqError>;
#[derive(Error, Debug)]
pub enum ZmqError {
#[error("Endpoint Error: {0}")]
Endpoint(#[from] EndpointError),
#[error("Network Error: {0}")]
Network(#[from] std::io::Error),
#[error("Socket bind doesn't exist: {0}")]
NoSuchBind(Endpoint),
|
Codec(#[from] CodecError),
#[error("Socket Error: {0}")]
Socket(&'static str),
#[error("{0}")]
BufferFull(&'static str),
#[error("Failed to deliver message cause of {reason}")]
ReturnToSender {
reason: &'static str,
message: ZmqMessage,
},
// TODO refactor this.
// Most likely Message enum should be part of public API.
// In such case we'll be able to use this enum to return both message and multipart message in
// same type
#[error("Failed to deliver messages cause of {reason}")]
ReturnToSenderMultipart {
reason: &'static str,
messages: Vec<ZmqMessage>,
},
#[error("Task Error: {0}")]
Task(#[from] TaskError),
#[error("{0}")]
Other(&'static str),
#[error("No message received")]
NoMessage,
#[error("Unsupported ZMTP version")]
UnsupportedVersion(ZmtpVersion),
}
impl From<futures::channel::mpsc::TrySendError<Message>> for ZmqError {
fn from(_: futures::channel::mpsc::TrySendError<Message>) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
impl From<futures::channel::mpsc::SendError> for ZmqError {
fn from(_: futures::channel::mpsc::SendError) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
|
#[error("Codec Error: {0}")]
|
random_line_split
|
error.rs
|
use crate::codec::{CodecError, Message, ZmtpVersion};
use crate::endpoint::Endpoint;
use crate::endpoint::EndpointError;
use crate::task_handle::TaskError;
use crate::ZmqMessage;
use thiserror::Error;
pub type ZmqResult<T> = Result<T, ZmqError>;
#[derive(Error, Debug)]
pub enum ZmqError {
#[error("Endpoint Error: {0}")]
Endpoint(#[from] EndpointError),
#[error("Network Error: {0}")]
Network(#[from] std::io::Error),
#[error("Socket bind doesn't exist: {0}")]
NoSuchBind(Endpoint),
#[error("Codec Error: {0}")]
Codec(#[from] CodecError),
#[error("Socket Error: {0}")]
Socket(&'static str),
#[error("{0}")]
BufferFull(&'static str),
#[error("Failed to deliver message cause of {reason}")]
ReturnToSender {
reason: &'static str,
message: ZmqMessage,
},
// TODO refactor this.
// Most likely Message enum should be part of public API.
// In such case we'll be able to use this enum to return both message and multipart message in
// same type
#[error("Failed to deliver messages cause of {reason}")]
ReturnToSenderMultipart {
reason: &'static str,
messages: Vec<ZmqMessage>,
},
#[error("Task Error: {0}")]
Task(#[from] TaskError),
#[error("{0}")]
Other(&'static str),
#[error("No message received")]
NoMessage,
#[error("Unsupported ZMTP version")]
UnsupportedVersion(ZmtpVersion),
}
impl From<futures::channel::mpsc::TrySendError<Message>> for ZmqError {
fn from(_: futures::channel::mpsc::TrySendError<Message>) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
impl From<futures::channel::mpsc::SendError> for ZmqError {
fn
|
(_: futures::channel::mpsc::SendError) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
|
from
|
identifier_name
|
error.rs
|
use crate::codec::{CodecError, Message, ZmtpVersion};
use crate::endpoint::Endpoint;
use crate::endpoint::EndpointError;
use crate::task_handle::TaskError;
use crate::ZmqMessage;
use thiserror::Error;
pub type ZmqResult<T> = Result<T, ZmqError>;
#[derive(Error, Debug)]
pub enum ZmqError {
#[error("Endpoint Error: {0}")]
Endpoint(#[from] EndpointError),
#[error("Network Error: {0}")]
Network(#[from] std::io::Error),
#[error("Socket bind doesn't exist: {0}")]
NoSuchBind(Endpoint),
#[error("Codec Error: {0}")]
Codec(#[from] CodecError),
#[error("Socket Error: {0}")]
Socket(&'static str),
#[error("{0}")]
BufferFull(&'static str),
#[error("Failed to deliver message cause of {reason}")]
ReturnToSender {
reason: &'static str,
message: ZmqMessage,
},
// TODO refactor this.
// Most likely Message enum should be part of public API.
// In such case we'll be able to use this enum to return both message and multipart message in
// same type
#[error("Failed to deliver messages cause of {reason}")]
ReturnToSenderMultipart {
reason: &'static str,
messages: Vec<ZmqMessage>,
},
#[error("Task Error: {0}")]
Task(#[from] TaskError),
#[error("{0}")]
Other(&'static str),
#[error("No message received")]
NoMessage,
#[error("Unsupported ZMTP version")]
UnsupportedVersion(ZmtpVersion),
}
impl From<futures::channel::mpsc::TrySendError<Message>> for ZmqError {
fn from(_: futures::channel::mpsc::TrySendError<Message>) -> Self
|
}
impl From<futures::channel::mpsc::SendError> for ZmqError {
fn from(_: futures::channel::mpsc::SendError) -> Self {
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
}
|
{
ZmqError::BufferFull("Failed to send message. Send queue full/broken")
}
|
identifier_body
|
mod.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
/// Export the ethash module.
pub mod ethash;
/// Export the denominations module.
pub mod denominations;
pub use self::ethash::Ethash;
pub use self::denominations::*;
use super::spec::*;
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/olympic.json"))
}
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier.json"))
}
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_test.json"))
}
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/homestead_test.json"))
}
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_mainnet_like() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_like_test.json"))
}
|
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/morden.json"))
}
#[cfg(test)]
mod tests {
use common::*;
use state::*;
use engine::*;
use super::*;
use tests::helpers::*;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header();
let mut db_result = get_temp_journal_db();
let mut db = db_result.take();
spec.ensure_db_good(db.as_hashdb_mut());
let s = State::from_existing(db, genesis_header.state_root.clone(), engine.account_start_nonce());
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000001")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000002")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000003")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000004")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c")), U256::from(1u64) << 200);
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000000")), U256::from(0u64));
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
let _ = morden.engine;
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap());
let _ = frontier.engine;
}
}
|
random_line_split
|
|
mod.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
/// Export the ethash module.
pub mod ethash;
/// Export the denominations module.
pub mod denominations;
pub use self::ethash::Ethash;
pub use self::denominations::*;
use super::spec::*;
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/olympic.json"))
}
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier.json"))
}
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_test.json"))
}
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/homestead_test.json"))
}
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_mainnet_like() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_like_test.json"))
}
/// Create a new Morden chain spec.
pub fn
|
() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/morden.json"))
}
#[cfg(test)]
mod tests {
use common::*;
use state::*;
use engine::*;
use super::*;
use tests::helpers::*;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header();
let mut db_result = get_temp_journal_db();
let mut db = db_result.take();
spec.ensure_db_good(db.as_hashdb_mut());
let s = State::from_existing(db, genesis_header.state_root.clone(), engine.account_start_nonce());
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000001")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000002")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000003")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000004")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c")), U256::from(1u64) << 200);
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000000")), U256::from(0u64));
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
let _ = morden.engine;
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap());
let _ = frontier.engine;
}
}
|
new_morden
|
identifier_name
|
mod.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Ethereum protocol module.
//!
//! Contains all Ethereum network specific stuff, such as denominations and
//! consensus specifications.
/// Export the ethash module.
pub mod ethash;
/// Export the denominations module.
pub mod denominations;
pub use self::ethash::Ethash;
pub use self::denominations::*;
use super::spec::*;
/// Create a new Olympic chain spec.
pub fn new_olympic() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/olympic.json"))
}
/// Create a new Frontier mainnet chain spec.
pub fn new_frontier() -> Spec
|
/// Create a new Frontier chain spec as though it never changes to Homestead.
pub fn new_frontier_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_test.json"))
}
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/homestead_test.json"))
}
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_mainnet_like() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/frontier_like_test.json"))
}
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec {
Spec::load(include_bytes!("../../res/ethereum/morden.json"))
}
#[cfg(test)]
mod tests {
use common::*;
use state::*;
use engine::*;
use super::*;
use tests::helpers::*;
#[test]
fn ensure_db_good() {
let spec = new_morden();
let engine = &spec.engine;
let genesis_header = spec.genesis_header();
let mut db_result = get_temp_journal_db();
let mut db = db_result.take();
spec.ensure_db_good(db.as_hashdb_mut());
let s = State::from_existing(db, genesis_header.state_root.clone(), engine.account_start_nonce());
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000001")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000002")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000003")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000004")), U256::from(1u64));
assert_eq!(s.balance(&address_from_hex("102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c")), U256::from(1u64) << 200);
assert_eq!(s.balance(&address_from_hex("0000000000000000000000000000000000000000")), U256::from(0u64));
}
#[test]
fn morden() {
let morden = new_morden();
assert_eq!(morden.state_root(), H256::from_str("f3f4696bbf3b3b07775128eb7a3763279a394e382130f27c21e70233e04946a9").unwrap());
let genesis = morden.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("0cd786a2425d16f152c658316c423e6ce1181e15c3295826d7c9904cba9ce303").unwrap());
let _ = morden.engine;
}
#[test]
fn frontier() {
let frontier = new_frontier();
assert_eq!(frontier.state_root(), H256::from_str("d7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544").unwrap());
let genesis = frontier.genesis_block();
assert_eq!(BlockView::new(&genesis).header_view().sha3(), H256::from_str("d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3").unwrap());
let _ = frontier.engine;
}
}
|
{
Spec::load(include_bytes!("../../res/ethereum/frontier.json"))
}
|
identifier_body
|
lib.rs
|
#![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(alloc, collections)]
#![no_std]
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86;
extern crate hole_list_allocator;
extern crate alloc;
#[macro_use]
extern crate collections;
#[macro_use]
extern crate once;
#[macro_use]
mod vga_buffer;
mod memory;
#[no_mangle]
pub extern "C" fn rust_main(multiboot_information_address: usize) {
// ATTENTION: we have a very small stack and no guard page
vga_buffer::clear_screen();
println!("Hello World{}", "!");
let boot_info = unsafe { multiboot2::load(multiboot_information_address) };
enable_nxe_bit();
enable_write_protect_bit();
// set up guard page and map the heap pages
memory::init(boot_info);
use alloc::boxed::Box;
let mut heap_test = Box::new(42);
*heap_test -= 15;
let heap_test2 = Box::new("hello");
println!("{:?} {:?}", heap_test, heap_test2);
let mut vec_test = vec![1, 2, 3, 4, 5, 6, 7];
vec_test[3] = 42;
for i in &vec_test {
print!("{} ", i);
}
println!("It did not crash!");
loop {}
}
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
#[lang = "panic_fmt"]
extern "C" fn panic_fmt(fmt: core::fmt::Arguments, file: &str, line: u32) ->! {
println!("\n\nPANIC in {} at line {}:", file, line);
println!(" {}", fmt);
loop {}
}
fn enable_nxe_bit()
|
fn enable_write_protect_bit() {
use x86::controlregs::{cr0, cr0_write};
let wp_bit = 1 << 16;
unsafe { cr0_write(cr0() | wp_bit) };
}
|
{
use x86::msr::{IA32_EFER, rdmsr, wrmsr};
let nxe_bit = 1 << 11;
unsafe {
let efer = rdmsr(IA32_EFER);
wrmsr(IA32_EFER, efer | nxe_bit);
}
}
|
identifier_body
|
lib.rs
|
#![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(alloc, collections)]
#![no_std]
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86;
extern crate hole_list_allocator;
extern crate alloc;
#[macro_use]
extern crate collections;
#[macro_use]
extern crate once;
#[macro_use]
mod vga_buffer;
mod memory;
#[no_mangle]
pub extern "C" fn rust_main(multiboot_information_address: usize) {
// ATTENTION: we have a very small stack and no guard page
vga_buffer::clear_screen();
println!("Hello World{}", "!");
let boot_info = unsafe { multiboot2::load(multiboot_information_address) };
enable_nxe_bit();
enable_write_protect_bit();
// set up guard page and map the heap pages
memory::init(boot_info);
use alloc::boxed::Box;
let mut heap_test = Box::new(42);
*heap_test -= 15;
let heap_test2 = Box::new("hello");
println!("{:?} {:?}", heap_test, heap_test2);
let mut vec_test = vec![1, 2, 3, 4, 5, 6, 7];
vec_test[3] = 42;
for i in &vec_test {
print!("{} ", i);
}
println!("It did not crash!");
loop {}
}
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
#[lang = "panic_fmt"]
extern "C" fn panic_fmt(fmt: core::fmt::Arguments, file: &str, line: u32) ->! {
println!("\n\nPANIC in {} at line {}:", file, line);
println!(" {}", fmt);
loop {}
}
fn enable_nxe_bit() {
use x86::msr::{IA32_EFER, rdmsr, wrmsr};
let nxe_bit = 1 << 11;
unsafe {
let efer = rdmsr(IA32_EFER);
wrmsr(IA32_EFER, efer | nxe_bit);
}
}
fn
|
() {
use x86::controlregs::{cr0, cr0_write};
let wp_bit = 1 << 16;
unsafe { cr0_write(cr0() | wp_bit) };
}
|
enable_write_protect_bit
|
identifier_name
|
lib.rs
|
#![feature(lang_items)]
#![feature(const_fn)]
#![feature(unique)]
#![feature(alloc, collections)]
#![no_std]
extern crate rlibc;
extern crate spin;
extern crate multiboot2;
#[macro_use]
extern crate bitflags;
extern crate x86;
extern crate hole_list_allocator;
extern crate alloc;
#[macro_use]
extern crate collections;
#[macro_use]
extern crate once;
#[macro_use]
mod vga_buffer;
mod memory;
#[no_mangle]
pub extern "C" fn rust_main(multiboot_information_address: usize) {
// ATTENTION: we have a very small stack and no guard page
vga_buffer::clear_screen();
println!("Hello World{}", "!");
let boot_info = unsafe { multiboot2::load(multiboot_information_address) };
enable_nxe_bit();
enable_write_protect_bit();
// set up guard page and map the heap pages
memory::init(boot_info);
use alloc::boxed::Box;
let mut heap_test = Box::new(42);
*heap_test -= 15;
let heap_test2 = Box::new("hello");
println!("{:?} {:?}", heap_test, heap_test2);
let mut vec_test = vec![1, 2, 3, 4, 5, 6, 7];
vec_test[3] = 42;
for i in &vec_test {
print!("{} ", i);
}
println!("It did not crash!");
loop {}
|
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}
#[lang = "panic_fmt"]
extern "C" fn panic_fmt(fmt: core::fmt::Arguments, file: &str, line: u32) ->! {
println!("\n\nPANIC in {} at line {}:", file, line);
println!(" {}", fmt);
loop {}
}
fn enable_nxe_bit() {
use x86::msr::{IA32_EFER, rdmsr, wrmsr};
let nxe_bit = 1 << 11;
unsafe {
let efer = rdmsr(IA32_EFER);
wrmsr(IA32_EFER, efer | nxe_bit);
}
}
fn enable_write_protect_bit() {
use x86::controlregs::{cr0, cr0_write};
let wp_bit = 1 << 16;
unsafe { cr0_write(cr0() | wp_bit) };
}
|
}
|
random_line_split
|
static-methods-crate.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.
#[link(name = "static_methods_crate",
vers = "0.1")];
#[crate_type = "lib"];
use std::int;
pub trait read {
fn readMaybe(s: ~str) -> Option<Self>;
}
impl read for int {
fn readMaybe(s: ~str) -> Option<int> {
from_str::<int>(s)
}
}
impl read for bool {
fn readMaybe(s: ~str) -> Option<bool> {
match s {
~"true" => Some(true),
~"false" => Some(false),
_ => None
}
}
}
pub fn read<T:read>(s: ~str) -> T {
match read::readMaybe(s) {
|
}
|
Some(x) => x,
_ => fail2!("read failed!")
}
|
random_line_split
|
static-methods-crate.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.
#[link(name = "static_methods_crate",
vers = "0.1")];
#[crate_type = "lib"];
use std::int;
pub trait read {
fn readMaybe(s: ~str) -> Option<Self>;
}
impl read for int {
fn readMaybe(s: ~str) -> Option<int> {
from_str::<int>(s)
}
}
impl read for bool {
fn readMaybe(s: ~str) -> Option<bool> {
match s {
~"true" => Some(true),
~"false" => Some(false),
_ => None
}
}
}
pub fn read<T:read>(s: ~str) -> T
|
{
match read::readMaybe(s) {
Some(x) => x,
_ => fail2!("read failed!")
}
}
|
identifier_body
|
|
static-methods-crate.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.
#[link(name = "static_methods_crate",
vers = "0.1")];
#[crate_type = "lib"];
use std::int;
pub trait read {
fn readMaybe(s: ~str) -> Option<Self>;
}
impl read for int {
fn readMaybe(s: ~str) -> Option<int> {
from_str::<int>(s)
}
}
impl read for bool {
fn readMaybe(s: ~str) -> Option<bool> {
match s {
~"true" => Some(true),
~"false" => Some(false),
_ => None
}
}
}
pub fn
|
<T:read>(s: ~str) -> T {
match read::readMaybe(s) {
Some(x) => x,
_ => fail2!("read failed!")
}
}
|
read
|
identifier_name
|
objects-owned-object-owned-method.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test invoked `&self` methods on owned objects where the values
// closed over contain managed values. This implies that the boxes
// will have headers that must be skipped over.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait FooTrait {
fn foo(self: Box<Self>) -> usize;
}
struct BarStruct {
x: usize
}
|
impl FooTrait for BarStruct {
fn foo(self: Box<BarStruct>) -> usize {
self.x
}
}
pub fn main() {
let foo = box BarStruct{ x: 22 } as Box<FooTrait>;
assert_eq!(22, foo.foo());
}
|
random_line_split
|
|
objects-owned-object-owned-method.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test invoked `&self` methods on owned objects where the values
// closed over contain managed values. This implies that the boxes
// will have headers that must be skipped over.
#![allow(unknown_features)]
#![feature(box_syntax)]
trait FooTrait {
fn foo(self: Box<Self>) -> usize;
}
struct
|
{
x: usize
}
impl FooTrait for BarStruct {
fn foo(self: Box<BarStruct>) -> usize {
self.x
}
}
pub fn main() {
let foo = box BarStruct{ x: 22 } as Box<FooTrait>;
assert_eq!(22, foo.foo());
}
|
BarStruct
|
identifier_name
|
error.rs
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
error_chain! {
types {
ViewError, ViewErrorKind, ResultExt, Result;
}
errors {
Unknown {
description("Unknown view error")
display("Unknown view error")
}
GlobError {
description("Error while glob()ing")
display("Error while glob()ing")
}
PatternError {
description("Error in glob() pattern")
display("Error in glob() pattern")
}
PatternBuildingError {
description("Could not build glob() pattern")
display("Could not build glob() pattern")
}
ViewError {
description("Failed to start viewer")
|
}
}
|
display("Failed to start viewer")
}
|
random_line_split
|
hello.rs
|
// Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#![feature(core, exit_status)]
#[macro_use]
extern crate log;
extern crate winapi;
#[macro_use]
extern crate rust_windows as windows;
use std::ptr;
use std::cell::RefCell;
use std::default::Default;
use std::env;
use winapi::{UINT, HBRUSH, CREATESTRUCTW};
use winapi::{DWORD, WORD, LPARAM, WPARAM, LRESULT};
use winapi::{WM_COMMAND, WM_DESTROY};
use winapi::minwindef::LOWORD;
use windows::main_window_loop;
use windows::instance::Instance;
use windows::resource::*;
use windows::window::{WindowImpl, Window, WndClass, WindowParams};
use windows::window::{OnCreate, OnSize, OnDestroy, OnPaint, OnFocus, OnMessage};
use windows::window;
use windows::gdi::PaintDc;
use windows::font::Font;
use windows::font;
use windows::dialog::DialogUtil;
// TODO duplicate of hello.rc
const IDI_ICON: isize = 0x101;
const MENU_MAIN: isize = 0x201;
const MENU_NEW: WORD = 0x202;
const MENU_EXIT: WORD = 0x203;
struct MainFrame {
win: Window,
title: String,
text_height: isize,
edit: RefCell<Option<Window>>,
font: RefCell<Option<Font>>,
}
wnd_proc!(MainFrame, win, WM_CREATE, WM_DESTROY, WM_SIZE, WM_SETFOCUS, WM_PAINT, ANY);
impl OnCreate for MainFrame {
fn on_create(&self, _cs: &CREATESTRUCTW) -> bool {
let rect = self.win.client_rect().unwrap();
let params = WindowParams {
window_name: "Hello World".to_string(),
style: window::WS_CHILD | window::WS_VISIBLE | window::WS_BORDER | window::WS_VSCROLL |
window::ES_AUTOVSCROLL | window::ES_MULTILINE | window::ES_NOHIDESEL,
x: 0,
y: self.text_height,
width: rect.right as isize,
height: rect.bottom as isize - self.text_height,
parent: self.win,
menu: ptr::null_mut(),
ex_style: 0,
};
let edit = Window::new(Instance::main_instance(), None, "EDIT", ¶ms);
match edit {
None => false,
Some(e) => {
let font_attr = Default::default();
let font = font::Font::new(&font_attr);
match font {
None => false,
Some(f) => {
static WM_SETFONT: UINT = 0x0030;
unsafe {
e.send_message(WM_SETFONT, std::mem::transmute(f.font), 0);
}
*self.edit.borrow_mut() = Some(e);
*self.font.borrow_mut() = Some(f);
true
}
}
}
}
}
}
impl OnSize for MainFrame {
fn on_size(&self, width: isize, height: isize) {
// SWP_NOOWNERZORDER | SWP_NOZORDER
let h = self.text_height;
self.edit.borrow().expect("edit is empty")
.set_window_pos(0, h, width, height - h, 0x200 | 0x4);
}
}
impl OnDestroy for MainFrame {}
impl OnPaint for MainFrame {
fn on_paint(&self) {
let font = self.font.borrow();
let pdc = PaintDc::new(self).expect("Paint DC");
pdc.dc.select_font(&font.expect("font is empty"));
pdc.dc.text_out(0, 0, self.title.as_ref());
}
}
impl OnFocus for MainFrame {
fn on_focus(&self, _w: Window) {
self.edit.borrow().expect("edit is empty").set_focus();
}
}
impl OnMessage for MainFrame {
fn on_message(&self, _message: UINT, _wparam: WPARAM, _lparam: LPARAM) -> Option<LRESULT> {
match _message {
WM_COMMAND => {
let menu = LOWORD( _wparam as DWORD );
match menu {
MENU_NEW => {
self.win.message_box( "New document.", "New..." );
self.edit.borrow().expect("edit is empty")
.set_window_text( "Hello World" );
},
MENU_EXIT => {
self.win.send_message( WM_DESTROY, 0, 0 );
},
_ => {}
}
},
_ => { /* Other messages. */ }
}
None
}
}
impl MainFrame {
fn new(instance: Instance, title: String, text_height: isize) -> Option<Window> {
let icon = Image::load_resource(instance, IDI_ICON, ImageType::IMAGE_ICON, 0, 0);
let wnd_class = WndClass {
classname: "MainFrame".to_string(),
style: 0x0001 | 0x0002, // CS_HREDRAW | CS_VREDRAW
icon: icon,
icon_small: None,
cursor: Image::load_cursor_resource(32514), // hourglass
background: (5 + 1) as HBRUSH,
menu: MenuResource::MenuId(MENU_MAIN),
cls_extra: 0,
wnd_extra: 0,
};
let res = wnd_class.register(instance);
if!res {
return None;
}
|
font: RefCell::new(None),
});
let win_params = WindowParams {
window_name: title,
style: window::WS_OVERLAPPEDWINDOW,
x: 0,
y: 0,
width: 400,
height: 400,
parent: Window::null(),
menu: ptr::null_mut(),
ex_style: 0,
};
Window::new(instance, Some(wproc as Box<WindowImpl +'static>),
wnd_class.classname.as_ref(), &win_params)
}
}
fn main() {
let instance = Instance::main_instance();
let main = MainFrame::new(instance, "Hello Rust".to_string(), 20);
let main = main.unwrap();
main.show(1);
main.update();
let exit_code = main_window_loop();
//env::set_exit_status(exit_code as i32);
}
|
let wproc = Box::new(MainFrame {
win: Window::null(),
title: title.clone(),
text_height: text_height,
edit: RefCell::new(None),
|
random_line_split
|
hello.rs
|
// Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#![feature(core, exit_status)]
#[macro_use]
extern crate log;
extern crate winapi;
#[macro_use]
extern crate rust_windows as windows;
use std::ptr;
use std::cell::RefCell;
use std::default::Default;
use std::env;
use winapi::{UINT, HBRUSH, CREATESTRUCTW};
use winapi::{DWORD, WORD, LPARAM, WPARAM, LRESULT};
use winapi::{WM_COMMAND, WM_DESTROY};
use winapi::minwindef::LOWORD;
use windows::main_window_loop;
use windows::instance::Instance;
use windows::resource::*;
use windows::window::{WindowImpl, Window, WndClass, WindowParams};
use windows::window::{OnCreate, OnSize, OnDestroy, OnPaint, OnFocus, OnMessage};
use windows::window;
use windows::gdi::PaintDc;
use windows::font::Font;
use windows::font;
use windows::dialog::DialogUtil;
// TODO duplicate of hello.rc
const IDI_ICON: isize = 0x101;
const MENU_MAIN: isize = 0x201;
const MENU_NEW: WORD = 0x202;
const MENU_EXIT: WORD = 0x203;
struct MainFrame {
win: Window,
title: String,
text_height: isize,
edit: RefCell<Option<Window>>,
font: RefCell<Option<Font>>,
}
wnd_proc!(MainFrame, win, WM_CREATE, WM_DESTROY, WM_SIZE, WM_SETFOCUS, WM_PAINT, ANY);
impl OnCreate for MainFrame {
fn on_create(&self, _cs: &CREATESTRUCTW) -> bool {
let rect = self.win.client_rect().unwrap();
let params = WindowParams {
window_name: "Hello World".to_string(),
style: window::WS_CHILD | window::WS_VISIBLE | window::WS_BORDER | window::WS_VSCROLL |
window::ES_AUTOVSCROLL | window::ES_MULTILINE | window::ES_NOHIDESEL,
x: 0,
y: self.text_height,
width: rect.right as isize,
height: rect.bottom as isize - self.text_height,
parent: self.win,
menu: ptr::null_mut(),
ex_style: 0,
};
let edit = Window::new(Instance::main_instance(), None, "EDIT", ¶ms);
match edit {
None => false,
Some(e) => {
let font_attr = Default::default();
let font = font::Font::new(&font_attr);
match font {
None => false,
Some(f) => {
static WM_SETFONT: UINT = 0x0030;
unsafe {
e.send_message(WM_SETFONT, std::mem::transmute(f.font), 0);
}
*self.edit.borrow_mut() = Some(e);
*self.font.borrow_mut() = Some(f);
true
}
}
}
}
}
}
impl OnSize for MainFrame {
fn on_size(&self, width: isize, height: isize) {
// SWP_NOOWNERZORDER | SWP_NOZORDER
let h = self.text_height;
self.edit.borrow().expect("edit is empty")
.set_window_pos(0, h, width, height - h, 0x200 | 0x4);
}
}
impl OnDestroy for MainFrame {}
impl OnPaint for MainFrame {
fn on_paint(&self)
|
}
impl OnFocus for MainFrame {
fn on_focus(&self, _w: Window) {
self.edit.borrow().expect("edit is empty").set_focus();
}
}
impl OnMessage for MainFrame {
fn on_message(&self, _message: UINT, _wparam: WPARAM, _lparam: LPARAM) -> Option<LRESULT> {
match _message {
WM_COMMAND => {
let menu = LOWORD( _wparam as DWORD );
match menu {
MENU_NEW => {
self.win.message_box( "New document.", "New..." );
self.edit.borrow().expect("edit is empty")
.set_window_text( "Hello World" );
},
MENU_EXIT => {
self.win.send_message( WM_DESTROY, 0, 0 );
},
_ => {}
}
},
_ => { /* Other messages. */ }
}
None
}
}
impl MainFrame {
fn new(instance: Instance, title: String, text_height: isize) -> Option<Window> {
let icon = Image::load_resource(instance, IDI_ICON, ImageType::IMAGE_ICON, 0, 0);
let wnd_class = WndClass {
classname: "MainFrame".to_string(),
style: 0x0001 | 0x0002, // CS_HREDRAW | CS_VREDRAW
icon: icon,
icon_small: None,
cursor: Image::load_cursor_resource(32514), // hourglass
background: (5 + 1) as HBRUSH,
menu: MenuResource::MenuId(MENU_MAIN),
cls_extra: 0,
wnd_extra: 0,
};
let res = wnd_class.register(instance);
if!res {
return None;
}
let wproc = Box::new(MainFrame {
win: Window::null(),
title: title.clone(),
text_height: text_height,
edit: RefCell::new(None),
font: RefCell::new(None),
});
let win_params = WindowParams {
window_name: title,
style: window::WS_OVERLAPPEDWINDOW,
x: 0,
y: 0,
width: 400,
height: 400,
parent: Window::null(),
menu: ptr::null_mut(),
ex_style: 0,
};
Window::new(instance, Some(wproc as Box<WindowImpl +'static>),
wnd_class.classname.as_ref(), &win_params)
}
}
fn main() {
let instance = Instance::main_instance();
let main = MainFrame::new(instance, "Hello Rust".to_string(), 20);
let main = main.unwrap();
main.show(1);
main.update();
let exit_code = main_window_loop();
//env::set_exit_status(exit_code as i32);
}
|
{
let font = self.font.borrow();
let pdc = PaintDc::new(self).expect("Paint DC");
pdc.dc.select_font(&font.expect("font is empty"));
pdc.dc.text_out(0, 0, self.title.as_ref());
}
|
identifier_body
|
hello.rs
|
// Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#![feature(core, exit_status)]
#[macro_use]
extern crate log;
extern crate winapi;
#[macro_use]
extern crate rust_windows as windows;
use std::ptr;
use std::cell::RefCell;
use std::default::Default;
use std::env;
use winapi::{UINT, HBRUSH, CREATESTRUCTW};
use winapi::{DWORD, WORD, LPARAM, WPARAM, LRESULT};
use winapi::{WM_COMMAND, WM_DESTROY};
use winapi::minwindef::LOWORD;
use windows::main_window_loop;
use windows::instance::Instance;
use windows::resource::*;
use windows::window::{WindowImpl, Window, WndClass, WindowParams};
use windows::window::{OnCreate, OnSize, OnDestroy, OnPaint, OnFocus, OnMessage};
use windows::window;
use windows::gdi::PaintDc;
use windows::font::Font;
use windows::font;
use windows::dialog::DialogUtil;
// TODO duplicate of hello.rc
const IDI_ICON: isize = 0x101;
const MENU_MAIN: isize = 0x201;
const MENU_NEW: WORD = 0x202;
const MENU_EXIT: WORD = 0x203;
struct MainFrame {
win: Window,
title: String,
text_height: isize,
edit: RefCell<Option<Window>>,
font: RefCell<Option<Font>>,
}
wnd_proc!(MainFrame, win, WM_CREATE, WM_DESTROY, WM_SIZE, WM_SETFOCUS, WM_PAINT, ANY);
impl OnCreate for MainFrame {
fn on_create(&self, _cs: &CREATESTRUCTW) -> bool {
let rect = self.win.client_rect().unwrap();
let params = WindowParams {
window_name: "Hello World".to_string(),
style: window::WS_CHILD | window::WS_VISIBLE | window::WS_BORDER | window::WS_VSCROLL |
window::ES_AUTOVSCROLL | window::ES_MULTILINE | window::ES_NOHIDESEL,
x: 0,
y: self.text_height,
width: rect.right as isize,
height: rect.bottom as isize - self.text_height,
parent: self.win,
menu: ptr::null_mut(),
ex_style: 0,
};
let edit = Window::new(Instance::main_instance(), None, "EDIT", ¶ms);
match edit {
None => false,
Some(e) => {
let font_attr = Default::default();
let font = font::Font::new(&font_attr);
match font {
None => false,
Some(f) => {
static WM_SETFONT: UINT = 0x0030;
unsafe {
e.send_message(WM_SETFONT, std::mem::transmute(f.font), 0);
}
*self.edit.borrow_mut() = Some(e);
*self.font.borrow_mut() = Some(f);
true
}
}
}
}
}
}
impl OnSize for MainFrame {
fn on_size(&self, width: isize, height: isize) {
// SWP_NOOWNERZORDER | SWP_NOZORDER
let h = self.text_height;
self.edit.borrow().expect("edit is empty")
.set_window_pos(0, h, width, height - h, 0x200 | 0x4);
}
}
impl OnDestroy for MainFrame {}
impl OnPaint for MainFrame {
fn on_paint(&self) {
let font = self.font.borrow();
let pdc = PaintDc::new(self).expect("Paint DC");
pdc.dc.select_font(&font.expect("font is empty"));
pdc.dc.text_out(0, 0, self.title.as_ref());
}
}
impl OnFocus for MainFrame {
fn on_focus(&self, _w: Window) {
self.edit.borrow().expect("edit is empty").set_focus();
}
}
impl OnMessage for MainFrame {
fn on_message(&self, _message: UINT, _wparam: WPARAM, _lparam: LPARAM) -> Option<LRESULT> {
match _message {
WM_COMMAND => {
let menu = LOWORD( _wparam as DWORD );
match menu {
MENU_NEW => {
self.win.message_box( "New document.", "New..." );
self.edit.borrow().expect("edit is empty")
.set_window_text( "Hello World" );
},
MENU_EXIT => {
self.win.send_message( WM_DESTROY, 0, 0 );
},
_ =>
|
}
},
_ => { /* Other messages. */ }
}
None
}
}
impl MainFrame {
fn new(instance: Instance, title: String, text_height: isize) -> Option<Window> {
let icon = Image::load_resource(instance, IDI_ICON, ImageType::IMAGE_ICON, 0, 0);
let wnd_class = WndClass {
classname: "MainFrame".to_string(),
style: 0x0001 | 0x0002, // CS_HREDRAW | CS_VREDRAW
icon: icon,
icon_small: None,
cursor: Image::load_cursor_resource(32514), // hourglass
background: (5 + 1) as HBRUSH,
menu: MenuResource::MenuId(MENU_MAIN),
cls_extra: 0,
wnd_extra: 0,
};
let res = wnd_class.register(instance);
if!res {
return None;
}
let wproc = Box::new(MainFrame {
win: Window::null(),
title: title.clone(),
text_height: text_height,
edit: RefCell::new(None),
font: RefCell::new(None),
});
let win_params = WindowParams {
window_name: title,
style: window::WS_OVERLAPPEDWINDOW,
x: 0,
y: 0,
width: 400,
height: 400,
parent: Window::null(),
menu: ptr::null_mut(),
ex_style: 0,
};
Window::new(instance, Some(wproc as Box<WindowImpl +'static>),
wnd_class.classname.as_ref(), &win_params)
}
}
fn main() {
let instance = Instance::main_instance();
let main = MainFrame::new(instance, "Hello Rust".to_string(), 20);
let main = main.unwrap();
main.show(1);
main.update();
let exit_code = main_window_loop();
//env::set_exit_status(exit_code as i32);
}
|
{}
|
conditional_block
|
hello.rs
|
// Copyright 2015 The Rust-Windows Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#![feature(core, exit_status)]
#[macro_use]
extern crate log;
extern crate winapi;
#[macro_use]
extern crate rust_windows as windows;
use std::ptr;
use std::cell::RefCell;
use std::default::Default;
use std::env;
use winapi::{UINT, HBRUSH, CREATESTRUCTW};
use winapi::{DWORD, WORD, LPARAM, WPARAM, LRESULT};
use winapi::{WM_COMMAND, WM_DESTROY};
use winapi::minwindef::LOWORD;
use windows::main_window_loop;
use windows::instance::Instance;
use windows::resource::*;
use windows::window::{WindowImpl, Window, WndClass, WindowParams};
use windows::window::{OnCreate, OnSize, OnDestroy, OnPaint, OnFocus, OnMessage};
use windows::window;
use windows::gdi::PaintDc;
use windows::font::Font;
use windows::font;
use windows::dialog::DialogUtil;
// TODO duplicate of hello.rc
const IDI_ICON: isize = 0x101;
const MENU_MAIN: isize = 0x201;
const MENU_NEW: WORD = 0x202;
const MENU_EXIT: WORD = 0x203;
struct
|
{
win: Window,
title: String,
text_height: isize,
edit: RefCell<Option<Window>>,
font: RefCell<Option<Font>>,
}
wnd_proc!(MainFrame, win, WM_CREATE, WM_DESTROY, WM_SIZE, WM_SETFOCUS, WM_PAINT, ANY);
impl OnCreate for MainFrame {
fn on_create(&self, _cs: &CREATESTRUCTW) -> bool {
let rect = self.win.client_rect().unwrap();
let params = WindowParams {
window_name: "Hello World".to_string(),
style: window::WS_CHILD | window::WS_VISIBLE | window::WS_BORDER | window::WS_VSCROLL |
window::ES_AUTOVSCROLL | window::ES_MULTILINE | window::ES_NOHIDESEL,
x: 0,
y: self.text_height,
width: rect.right as isize,
height: rect.bottom as isize - self.text_height,
parent: self.win,
menu: ptr::null_mut(),
ex_style: 0,
};
let edit = Window::new(Instance::main_instance(), None, "EDIT", ¶ms);
match edit {
None => false,
Some(e) => {
let font_attr = Default::default();
let font = font::Font::new(&font_attr);
match font {
None => false,
Some(f) => {
static WM_SETFONT: UINT = 0x0030;
unsafe {
e.send_message(WM_SETFONT, std::mem::transmute(f.font), 0);
}
*self.edit.borrow_mut() = Some(e);
*self.font.borrow_mut() = Some(f);
true
}
}
}
}
}
}
impl OnSize for MainFrame {
fn on_size(&self, width: isize, height: isize) {
// SWP_NOOWNERZORDER | SWP_NOZORDER
let h = self.text_height;
self.edit.borrow().expect("edit is empty")
.set_window_pos(0, h, width, height - h, 0x200 | 0x4);
}
}
impl OnDestroy for MainFrame {}
impl OnPaint for MainFrame {
fn on_paint(&self) {
let font = self.font.borrow();
let pdc = PaintDc::new(self).expect("Paint DC");
pdc.dc.select_font(&font.expect("font is empty"));
pdc.dc.text_out(0, 0, self.title.as_ref());
}
}
impl OnFocus for MainFrame {
fn on_focus(&self, _w: Window) {
self.edit.borrow().expect("edit is empty").set_focus();
}
}
impl OnMessage for MainFrame {
fn on_message(&self, _message: UINT, _wparam: WPARAM, _lparam: LPARAM) -> Option<LRESULT> {
match _message {
WM_COMMAND => {
let menu = LOWORD( _wparam as DWORD );
match menu {
MENU_NEW => {
self.win.message_box( "New document.", "New..." );
self.edit.borrow().expect("edit is empty")
.set_window_text( "Hello World" );
},
MENU_EXIT => {
self.win.send_message( WM_DESTROY, 0, 0 );
},
_ => {}
}
},
_ => { /* Other messages. */ }
}
None
}
}
impl MainFrame {
fn new(instance: Instance, title: String, text_height: isize) -> Option<Window> {
let icon = Image::load_resource(instance, IDI_ICON, ImageType::IMAGE_ICON, 0, 0);
let wnd_class = WndClass {
classname: "MainFrame".to_string(),
style: 0x0001 | 0x0002, // CS_HREDRAW | CS_VREDRAW
icon: icon,
icon_small: None,
cursor: Image::load_cursor_resource(32514), // hourglass
background: (5 + 1) as HBRUSH,
menu: MenuResource::MenuId(MENU_MAIN),
cls_extra: 0,
wnd_extra: 0,
};
let res = wnd_class.register(instance);
if!res {
return None;
}
let wproc = Box::new(MainFrame {
win: Window::null(),
title: title.clone(),
text_height: text_height,
edit: RefCell::new(None),
font: RefCell::new(None),
});
let win_params = WindowParams {
window_name: title,
style: window::WS_OVERLAPPEDWINDOW,
x: 0,
y: 0,
width: 400,
height: 400,
parent: Window::null(),
menu: ptr::null_mut(),
ex_style: 0,
};
Window::new(instance, Some(wproc as Box<WindowImpl +'static>),
wnd_class.classname.as_ref(), &win_params)
}
}
fn main() {
let instance = Instance::main_instance();
let main = MainFrame::new(instance, "Hello Rust".to_string(), 20);
let main = main.unwrap();
main.show(1);
main.update();
let exit_code = main_window_loop();
//env::set_exit_status(exit_code as i32);
}
|
MainFrame
|
identifier_name
|
socket_event.rs
|
use td_rp::Buffer;
|
client_ip: String,
server_port: u16,
buffer: Buffer,
out_cache: Buffer,
online: bool,
websocket: bool,
}
impl SocketEvent {
pub fn new(socket_fd: i32, client_ip: String, server_port: u16) -> SocketEvent {
SocketEvent {
socket_fd: socket_fd,
cookie: 0,
client_ip: client_ip,
server_port: server_port,
buffer: Buffer::new(),
out_cache: Buffer::new(),
online: true,
websocket: false,
}
}
pub fn get_socket_fd(&self) -> i32 {
self.socket_fd
}
pub fn get_client_ip(&self) -> String {
self.client_ip.clone()
}
pub fn get_server_port(&self) -> u16 {
self.server_port
}
pub fn get_cookie(&self) -> u32 {
self.cookie
}
pub fn set_cookie(&mut self, cookie: u32) {
self.cookie = cookie;
}
pub fn get_buffer(&mut self) -> &mut Buffer {
&mut self.buffer
}
pub fn get_out_cache(&mut self) -> &mut Buffer {
&mut self.out_cache
}
pub fn set_online(&mut self, online: bool) {
self.online = online;
}
pub fn is_online(&self) -> bool {
self.online
}
pub fn set_websocket(&mut self, websocket: bool) {
self.websocket = websocket;
}
pub fn is_websocket(&self) -> bool {
self.websocket
}
}
|
#[derive(Debug)]
pub struct SocketEvent {
socket_fd: i32,
cookie: u32,
|
random_line_split
|
socket_event.rs
|
use td_rp::Buffer;
#[derive(Debug)]
pub struct SocketEvent {
socket_fd: i32,
cookie: u32,
client_ip: String,
server_port: u16,
buffer: Buffer,
out_cache: Buffer,
online: bool,
websocket: bool,
}
impl SocketEvent {
pub fn new(socket_fd: i32, client_ip: String, server_port: u16) -> SocketEvent {
SocketEvent {
socket_fd: socket_fd,
cookie: 0,
client_ip: client_ip,
server_port: server_port,
buffer: Buffer::new(),
out_cache: Buffer::new(),
online: true,
websocket: false,
}
}
pub fn get_socket_fd(&self) -> i32 {
self.socket_fd
}
pub fn get_client_ip(&self) -> String {
self.client_ip.clone()
}
pub fn get_server_port(&self) -> u16 {
self.server_port
}
pub fn get_cookie(&self) -> u32 {
self.cookie
}
pub fn set_cookie(&mut self, cookie: u32) {
self.cookie = cookie;
}
pub fn get_buffer(&mut self) -> &mut Buffer {
&mut self.buffer
}
pub fn get_out_cache(&mut self) -> &mut Buffer {
&mut self.out_cache
}
pub fn
|
(&mut self, online: bool) {
self.online = online;
}
pub fn is_online(&self) -> bool {
self.online
}
pub fn set_websocket(&mut self, websocket: bool) {
self.websocket = websocket;
}
pub fn is_websocket(&self) -> bool {
self.websocket
}
}
|
set_online
|
identifier_name
|
socket_event.rs
|
use td_rp::Buffer;
#[derive(Debug)]
pub struct SocketEvent {
socket_fd: i32,
cookie: u32,
client_ip: String,
server_port: u16,
buffer: Buffer,
out_cache: Buffer,
online: bool,
websocket: bool,
}
impl SocketEvent {
pub fn new(socket_fd: i32, client_ip: String, server_port: u16) -> SocketEvent {
SocketEvent {
socket_fd: socket_fd,
cookie: 0,
client_ip: client_ip,
server_port: server_port,
buffer: Buffer::new(),
out_cache: Buffer::new(),
online: true,
websocket: false,
}
}
pub fn get_socket_fd(&self) -> i32 {
self.socket_fd
}
pub fn get_client_ip(&self) -> String {
self.client_ip.clone()
}
pub fn get_server_port(&self) -> u16 {
self.server_port
}
pub fn get_cookie(&self) -> u32 {
self.cookie
}
pub fn set_cookie(&mut self, cookie: u32) {
self.cookie = cookie;
}
pub fn get_buffer(&mut self) -> &mut Buffer {
&mut self.buffer
}
pub fn get_out_cache(&mut self) -> &mut Buffer {
&mut self.out_cache
}
pub fn set_online(&mut self, online: bool) {
self.online = online;
}
pub fn is_online(&self) -> bool
|
pub fn set_websocket(&mut self, websocket: bool) {
self.websocket = websocket;
}
pub fn is_websocket(&self) -> bool {
self.websocket
}
}
|
{
self.online
}
|
identifier_body
|
set_cookie.rs
|
use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<CookiePair>);
__hyper__deref!(SetCookie => Vec<CookiePair>);
impl Header for SetCookie {
fn header_name() -> &'static str {
static NAME: &'static str = "Set-Cookie";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&"foo=bar; HttpOnly".into());
let mut c1 = CookiePair::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt()
|
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
jar.add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.find("foo"), new_jar.find("foo"));
assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>());
}
|
{
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux\r\n");
}
|
identifier_body
|
set_cookie.rs
|
use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<CookiePair>);
__hyper__deref!(SetCookie => Vec<CookiePair>);
impl Header for SetCookie {
fn header_name() -> &'static str {
static NAME: &'static str = "Set-Cookie";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0
|
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&"foo=bar; HttpOnly".into());
let mut c1 = CookiePair::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
jar.add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.find("foo"), new_jar.find("foo"));
assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>());
}
|
{
try!(f.write_str("\r\nSet-Cookie: "));
}
|
conditional_block
|
set_cookie.rs
|
use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<CookiePair>);
__hyper__deref!(SetCookie => Vec<CookiePair>);
impl Header for SetCookie {
fn header_name() -> &'static str {
static NAME: &'static str = "Set-Cookie";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
|
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&"foo=bar; HttpOnly".into());
let mut c1 = CookiePair::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn test_fmt() {
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
jar.add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.find("foo"), new_jar.find("foo"));
assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>());
}
|
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i != 0 {
|
random_line_split
|
set_cookie.rs
|
use header::{Header, Raw, CookiePair, CookieJar};
use std::fmt::{self, Display};
use std::str::from_utf8;
/// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1)
///
/// The Set-Cookie HTTP response header is used to send cookies from the
/// server to the user agent.
///
/// Informally, the Set-Cookie response header contains the header name
/// "Set-Cookie" followed by a ":" and a cookie. Each cookie begins with
/// a name-value-pair, followed by zero or more attribute-value pairs.
///
/// # ABNF
/// ```plain
/// set-cookie-header = "Set-Cookie:" SP set-cookie-string
/// set-cookie-string = cookie-pair *( ";" SP cookie-av )
/// cookie-pair = cookie-name "=" cookie-value
/// cookie-name = token
/// cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
/// cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
/// ; US-ASCII characters excluding CTLs,
/// ; whitespace DQUOTE, comma, semicolon,
/// ; and backslash
/// token = <token, defined in [RFC2616], Section 2.2>
///
/// cookie-av = expires-av / max-age-av / domain-av /
/// path-av / secure-av / httponly-av /
/// extension-av
/// expires-av = "Expires=" sane-cookie-date
/// sane-cookie-date = <rfc1123-date, defined in [RFC2616], Section 3.3.1>
/// max-age-av = "Max-Age=" non-zero-digit *DIGIT
/// ; In practice, both expires-av and max-age-av
/// ; are limited to dates representable by the
/// ; user agent.
/// non-zero-digit = %x31-39
/// ; digits 1 through 9
/// domain-av = "Domain=" domain-value
/// domain-value = <subdomain>
/// ; defined in [RFC1034], Section 3.5, as
/// ; enhanced by [RFC1123], Section 2.1
/// path-av = "Path=" path-value
/// path-value = <any CHAR except CTLs or ";">
/// secure-av = "Secure"
/// httponly-av = "HttpOnly"
/// extension-av = <any CHAR except CTLs or ";">
/// ```
///
/// # Example values
/// * `SID=31d4d96e407aad42`
/// * `lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT`
/// * `lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT`
/// * `lang=en-US; Path=/; Domain=example.com`
///
/// # Example
/// ```
/// # extern crate hyper;
/// # extern crate cookie;
/// # fn main() {
/// // extern crate cookie;
///
/// use hyper::header::{Headers, SetCookie};
/// use cookie::Cookie as CookiePair;
///
/// let mut headers = Headers::new();
/// let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
///
/// cookie.path = Some("/path".to_owned());
/// cookie.domain = Some("example.com".to_owned());
///
/// headers.set(
/// SetCookie(vec![
/// cookie,
/// CookiePair::new("baz".to_owned(), "quux".to_owned()),
/// ])
/// );
/// # }
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct SetCookie(pub Vec<CookiePair>);
__hyper__deref!(SetCookie => Vec<CookiePair>);
impl Header for SetCookie {
fn header_name() -> &'static str {
static NAME: &'static str = "Set-Cookie";
NAME
}
fn parse_header(raw: &Raw) -> ::Result<SetCookie> {
let mut set_cookies = Vec::with_capacity(raw.len());
for set_cookies_raw in raw {
if let Ok(s) = from_utf8(&set_cookies_raw[..]) {
if let Ok(cookie) = s.parse() {
set_cookies.push(cookie);
}
}
}
if!set_cookies.is_empty() {
Ok(SetCookie(set_cookies))
} else {
Err(::Error::Header)
}
}
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, cookie) in self.0.iter().enumerate() {
if i!= 0 {
try!(f.write_str("\r\nSet-Cookie: "));
}
try!(Display::fmt(cookie, f));
}
Ok(())
}
}
impl SetCookie {
/// Use this to create SetCookie header from CookieJar using
/// calculated delta.
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
SetCookie(jar.delta())
}
/// Use this on client to apply changes from SetCookie to CookieJar.
/// Note that this will `panic!` if `CookieJar` is not root.
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
for cookie in self.iter() {
jar.add_original(cookie.clone())
}
}
}
#[test]
fn test_parse() {
let h = Header::parse_header(&"foo=bar; HttpOnly".into());
let mut c1 = CookiePair::new("foo".to_owned(), "bar".to_owned());
c1.httponly = true;
assert_eq!(h.ok(), Some(SetCookie(vec![c1])));
}
#[test]
fn
|
() {
use header::Headers;
let mut cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
cookie.httponly = true;
cookie.path = Some("/p".to_owned());
let cookies = SetCookie(vec![cookie, CookiePair::new("baz".to_owned(), "quux".to_owned())]);
let mut headers = Headers::new();
headers.set(cookies);
assert_eq!(
&headers.to_string()[..],
"Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux\r\n");
}
#[test]
fn cookie_jar() {
let jar = CookieJar::new(b"secret");
let cookie = CookiePair::new("foo".to_owned(), "bar".to_owned());
jar.add(cookie);
let cookies = SetCookie::from_cookie_jar(&jar);
let mut new_jar = CookieJar::new(b"secret");
cookies.apply_to_cookie_jar(&mut new_jar);
assert_eq!(jar.find("foo"), new_jar.find("foo"));
assert_eq!(jar.iter().collect::<Vec<CookiePair>>(), new_jar.iter().collect::<Vec<CookiePair>>());
}
|
test_fmt
|
identifier_name
|
erase_regions.rs
|
use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty,..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
// N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx }).into_ok()
}
impl<'tcx> TyCtxt<'tcx> {
/// Returns an equivalent value with all free regions removed (note
/// that late-bound regions remain, because they are important for
/// subtyping, but they are anonymized and normalized as well)..
pub fn erase_regions<T>(self, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
// If there's nothing to erase avoid performing the query at all
if!value
.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND | TypeFlags::HAS_POTENTIAL_FREE_REGIONS)
{
return value;
}
debug!("erase_regions({:?})", value);
let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self }).into_ok();
debug!("erase_regions = {:?}", value1);
value1
}
}
struct RegionEraserVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
|
impl TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
if ty.needs_infer() { ty.super_fold_with(self) } else { Ok(self.tcx.erase_regions_ty(ty)) }
}
fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> Result<ty::Binder<'tcx, T>, Self::Error>
where
T: TypeFoldable<'tcx>,
{
let u = self.tcx.anonymize_late_bound_regions(t);
u.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
// because late-bound regions affect subtyping, we can't
// erase the bound/free distinction, but we can replace
// all free regions with 'erased.
//
// Note that we *CAN* replace early-bound regions -- the
// type system never "sees" those, they get substituted
// away. In codegen, they will always be erased to 'erased
// whenever a substitution occurs.
match *r {
ty::ReLateBound(..) => Ok(r),
_ => Ok(self.tcx.lifetimes.re_erased),
}
}
fn fold_mir_const(
&mut self,
c: mir::ConstantKind<'tcx>,
) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
c.super_fold_with(self)
}
}
|
random_line_split
|
|
erase_regions.rs
|
use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty,..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
// N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx }).into_ok()
}
impl<'tcx> TyCtxt<'tcx> {
/// Returns an equivalent value with all free regions removed (note
/// that late-bound regions remain, because they are important for
/// subtyping, but they are anonymized and normalized as well)..
pub fn erase_regions<T>(self, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
// If there's nothing to erase avoid performing the query at all
if!value
.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND | TypeFlags::HAS_POTENTIAL_FREE_REGIONS)
{
return value;
}
debug!("erase_regions({:?})", value);
let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self }).into_ok();
debug!("erase_regions = {:?}", value1);
value1
}
}
struct RegionEraserVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
if ty.needs_infer() { ty.super_fold_with(self) } else
|
}
fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> Result<ty::Binder<'tcx, T>, Self::Error>
where
T: TypeFoldable<'tcx>,
{
let u = self.tcx.anonymize_late_bound_regions(t);
u.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
// because late-bound regions affect subtyping, we can't
// erase the bound/free distinction, but we can replace
// all free regions with 'erased.
//
// Note that we *CAN* replace early-bound regions -- the
// type system never "sees" those, they get substituted
// away. In codegen, they will always be erased to 'erased
// whenever a substitution occurs.
match *r {
ty::ReLateBound(..) => Ok(r),
_ => Ok(self.tcx.lifetimes.re_erased),
}
}
fn fold_mir_const(
&mut self,
c: mir::ConstantKind<'tcx>,
) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
c.super_fold_with(self)
}
}
|
{ Ok(self.tcx.erase_regions_ty(ty)) }
|
conditional_block
|
erase_regions.rs
|
use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty,..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
// N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx }).into_ok()
}
impl<'tcx> TyCtxt<'tcx> {
/// Returns an equivalent value with all free regions removed (note
/// that late-bound regions remain, because they are important for
/// subtyping, but they are anonymized and normalized as well)..
pub fn erase_regions<T>(self, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
// If there's nothing to erase avoid performing the query at all
if!value
.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND | TypeFlags::HAS_POTENTIAL_FREE_REGIONS)
{
return value;
}
debug!("erase_regions({:?})", value);
let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self }).into_ok();
debug!("erase_regions = {:?}", value1);
value1
}
}
struct RegionEraserVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
if ty.needs_infer() { ty.super_fold_with(self) } else { Ok(self.tcx.erase_regions_ty(ty)) }
}
fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> Result<ty::Binder<'tcx, T>, Self::Error>
where
T: TypeFoldable<'tcx>,
{
let u = self.tcx.anonymize_late_bound_regions(t);
u.super_fold_with(self)
}
fn
|
(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
// because late-bound regions affect subtyping, we can't
// erase the bound/free distinction, but we can replace
// all free regions with 'erased.
//
// Note that we *CAN* replace early-bound regions -- the
// type system never "sees" those, they get substituted
// away. In codegen, they will always be erased to 'erased
// whenever a substitution occurs.
match *r {
ty::ReLateBound(..) => Ok(r),
_ => Ok(self.tcx.lifetimes.re_erased),
}
}
fn fold_mir_const(
&mut self,
c: mir::ConstantKind<'tcx>,
) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
c.super_fold_with(self)
}
}
|
fold_region
|
identifier_name
|
erase_regions.rs
|
use crate::mir;
use crate::ty::fold::{TypeFoldable, TypeFolder};
use crate::ty::{self, Ty, TyCtxt, TypeFlags};
pub(super) fn provide(providers: &mut ty::query::Providers) {
*providers = ty::query::Providers { erase_regions_ty,..*providers };
}
fn erase_regions_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx>
|
impl<'tcx> TyCtxt<'tcx> {
/// Returns an equivalent value with all free regions removed (note
/// that late-bound regions remain, because they are important for
/// subtyping, but they are anonymized and normalized as well)..
pub fn erase_regions<T>(self, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
// If there's nothing to erase avoid performing the query at all
if!value
.has_type_flags(TypeFlags::HAS_RE_LATE_BOUND | TypeFlags::HAS_POTENTIAL_FREE_REGIONS)
{
return value;
}
debug!("erase_regions({:?})", value);
let value1 = value.fold_with(&mut RegionEraserVisitor { tcx: self }).into_ok();
debug!("erase_regions = {:?}", value1);
value1
}
}
struct RegionEraserVisitor<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl TypeFolder<'tcx> for RegionEraserVisitor<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
if ty.needs_infer() { ty.super_fold_with(self) } else { Ok(self.tcx.erase_regions_ty(ty)) }
}
fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> Result<ty::Binder<'tcx, T>, Self::Error>
where
T: TypeFoldable<'tcx>,
{
let u = self.tcx.anonymize_late_bound_regions(t);
u.super_fold_with(self)
}
fn fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
// because late-bound regions affect subtyping, we can't
// erase the bound/free distinction, but we can replace
// all free regions with 'erased.
//
// Note that we *CAN* replace early-bound regions -- the
// type system never "sees" those, they get substituted
// away. In codegen, they will always be erased to 'erased
// whenever a substitution occurs.
match *r {
ty::ReLateBound(..) => Ok(r),
_ => Ok(self.tcx.lifetimes.re_erased),
}
}
fn fold_mir_const(
&mut self,
c: mir::ConstantKind<'tcx>,
) -> Result<mir::ConstantKind<'tcx>, Self::Error> {
c.super_fold_with(self)
}
}
|
{
// N.B., use `super_fold_with` here. If we used `fold_with`, it
// could invoke the `erase_regions_ty` query recursively.
ty.super_fold_with(&mut RegionEraserVisitor { tcx }).into_ok()
}
|
identifier_body
|
classify.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.
/*
Predicates on exprs and stmts that the pretty-printer and parser use
*/
use ast;
// does this expression require a semicolon to be treated
// as a statement? The negation of this: 'can this expression
// be used as a statement without a semicolon' -- is used
// as an early-bail-out in the parser so that, for instance,
// 'if true {...} else {...}
// |x| 5 '
// isn't parsed as (if true {...} else {...} | x) | 5
pub fn expr_requires_semi_to_be_stmt(e: @ast::Expr) -> bool
|
pub fn expr_is_simple_block(e: @ast::Expr) -> bool {
match e.node {
ast::ExprBlock(block) => block.rules == ast::DefaultBlock,
_ => false
}
}
// this statement requires a semicolon after it.
// note that in one case (stmt_semi), we've already
// seen the semicolon, and thus don't need another.
pub fn stmt_ends_with_semi(stmt: &ast::Stmt) -> bool {
return match stmt.node {
ast::StmtDecl(d, _) => {
match d.node {
ast::DeclLocal(_) => true,
ast::DeclItem(_) => false
}
}
ast::StmtExpr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::StmtSemi(..) => { false }
ast::StmtMac(..) => { false }
}
}
|
{
match e.node {
ast::ExprIf(..)
| ast::ExprMatch(..)
| ast::ExprBlock(_)
| ast::ExprWhile(..)
| ast::ExprLoop(..)
| ast::ExprForLoop(..)
| ast::ExprCall(_, _, ast::DoSugar)
| ast::ExprCall(_, _, ast::ForSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::DoSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::ForSugar) => false,
_ => true
}
}
|
identifier_body
|
classify.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.
/*
Predicates on exprs and stmts that the pretty-printer and parser use
*/
use ast;
// does this expression require a semicolon to be treated
// as a statement? The negation of this: 'can this expression
// be used as a statement without a semicolon' -- is used
// as an early-bail-out in the parser so that, for instance,
// 'if true {...} else {...}
// |x| 5 '
// isn't parsed as (if true {...} else {...} | x) | 5
pub fn expr_requires_semi_to_be_stmt(e: @ast::Expr) -> bool {
match e.node {
ast::ExprIf(..)
| ast::ExprMatch(..)
| ast::ExprBlock(_)
| ast::ExprWhile(..)
| ast::ExprLoop(..)
| ast::ExprForLoop(..)
| ast::ExprCall(_, _, ast::DoSugar)
| ast::ExprCall(_, _, ast::ForSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::DoSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::ForSugar) => false,
_ => true
}
}
pub fn expr_is_simple_block(e: @ast::Expr) -> bool {
match e.node {
ast::ExprBlock(block) => block.rules == ast::DefaultBlock,
_ => false
}
}
// this statement requires a semicolon after it.
// note that in one case (stmt_semi), we've already
// seen the semicolon, and thus don't need another.
pub fn stmt_ends_with_semi(stmt: &ast::Stmt) -> bool {
return match stmt.node {
ast::StmtDecl(d, _) => {
match d.node {
ast::DeclLocal(_) => true,
ast::DeclItem(_) => false
}
}
ast::StmtExpr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::StmtSemi(..) => { false }
|
ast::StmtMac(..) => { false }
}
}
|
random_line_split
|
|
classify.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.
/*
Predicates on exprs and stmts that the pretty-printer and parser use
*/
use ast;
// does this expression require a semicolon to be treated
// as a statement? The negation of this: 'can this expression
// be used as a statement without a semicolon' -- is used
// as an early-bail-out in the parser so that, for instance,
// 'if true {...} else {...}
// |x| 5 '
// isn't parsed as (if true {...} else {...} | x) | 5
pub fn expr_requires_semi_to_be_stmt(e: @ast::Expr) -> bool {
match e.node {
ast::ExprIf(..)
| ast::ExprMatch(..)
| ast::ExprBlock(_)
| ast::ExprWhile(..)
| ast::ExprLoop(..)
| ast::ExprForLoop(..)
| ast::ExprCall(_, _, ast::DoSugar)
| ast::ExprCall(_, _, ast::ForSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::DoSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::ForSugar) => false,
_ => true
}
}
pub fn expr_is_simple_block(e: @ast::Expr) -> bool {
match e.node {
ast::ExprBlock(block) => block.rules == ast::DefaultBlock,
_ => false
}
}
// this statement requires a semicolon after it.
// note that in one case (stmt_semi), we've already
// seen the semicolon, and thus don't need another.
pub fn stmt_ends_with_semi(stmt: &ast::Stmt) -> bool {
return match stmt.node {
ast::StmtDecl(d, _) => {
match d.node {
ast::DeclLocal(_) => true,
ast::DeclItem(_) => false
}
}
ast::StmtExpr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::StmtSemi(..) => { false }
ast::StmtMac(..) =>
|
}
}
|
{ false }
|
conditional_block
|
classify.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.
/*
Predicates on exprs and stmts that the pretty-printer and parser use
*/
use ast;
// does this expression require a semicolon to be treated
// as a statement? The negation of this: 'can this expression
// be used as a statement without a semicolon' -- is used
// as an early-bail-out in the parser so that, for instance,
// 'if true {...} else {...}
// |x| 5 '
// isn't parsed as (if true {...} else {...} | x) | 5
pub fn expr_requires_semi_to_be_stmt(e: @ast::Expr) -> bool {
match e.node {
ast::ExprIf(..)
| ast::ExprMatch(..)
| ast::ExprBlock(_)
| ast::ExprWhile(..)
| ast::ExprLoop(..)
| ast::ExprForLoop(..)
| ast::ExprCall(_, _, ast::DoSugar)
| ast::ExprCall(_, _, ast::ForSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::DoSugar)
| ast::ExprMethodCall(_, _, _, _, _, ast::ForSugar) => false,
_ => true
}
}
pub fn expr_is_simple_block(e: @ast::Expr) -> bool {
match e.node {
ast::ExprBlock(block) => block.rules == ast::DefaultBlock,
_ => false
}
}
// this statement requires a semicolon after it.
// note that in one case (stmt_semi), we've already
// seen the semicolon, and thus don't need another.
pub fn
|
(stmt: &ast::Stmt) -> bool {
return match stmt.node {
ast::StmtDecl(d, _) => {
match d.node {
ast::DeclLocal(_) => true,
ast::DeclItem(_) => false
}
}
ast::StmtExpr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::StmtSemi(..) => { false }
ast::StmtMac(..) => { false }
}
}
|
stmt_ends_with_semi
|
identifier_name
|
default.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn expand_deriving_default(cx: &ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@Item])
-> ~[@Item] {
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new(~["std", "default", "Default"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: ~[],
ret_ty: Self,
inline: true,
const_nonmatching: false,
combine_substructure: default_substructure
},
]
};
trait_def.expand(mitem, in_items)
}
fn default_substructure(cx: &ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
let default_ident = ~[
cx.ident_of("std"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
];
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), ~[]);
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(span, substr.type_ident)
} else {
let exprs = fields.map(|sp| default_call(*sp));
cx.expr_call_ident(span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
});
cx.expr_struct_ident(span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
|
cx.span_fatal(span, "`Default` cannot be derived for enums, \
only structs")
}
_ => cx.bug("Non-static method in `deriving(Default)`")
};
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.