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 |
---|---|---|---|---|
memory.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::{U256, Uint};
pub trait Memory {
/// Retrieve current size of the memory
fn size(&self) -> usize;
/// Resize (shrink or expand) the memory to specified size (fills 0)
fn resize(&mut self, new_size: usize);
/// Resize the memory only if its smaller
fn expand(&mut self, new_size: usize);
/// Write single byte to memory
fn write_byte(&mut self, offset: U256, value: U256);
/// Write a word to memory. Does not resize memory!
fn write(&mut self, offset: U256, value: U256);
/// Read a word from memory
fn read(&self, offset: U256) -> U256;
/// Write slice of bytes to memory. Does not resize memory!
fn write_slice(&mut self, offset: U256, &[u8]);
/// Retrieve part of the memory between offset and offset + size
fn read_slice(&self, offset: U256, size: U256) -> &[u8];
/// Retrieve writeable part of memory
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut[u8];
fn dump(&self);
}
/// Checks whether offset and size is valid memory range
fn is_valid_range(off: usize, size: usize) -> bool {
// When size is zero we haven't actually expanded the memory
let overflow = off.overflowing_add(size).1;
size > 0 &&!overflow
}
impl Memory for Vec<u8> {
fn dump(&self) {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
}
fn size(&self) -> usize {
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) {
&self[0..0]
} else {
&self[off..off+size]
}
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off+32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_range(off, s) {
&mut self[0..0]
} else {
&mut self[off..off+s]
}
}
fn write_slice(&mut self, offset: U256, slice: &[u8]) {
let off = offset.low_u64() as usize;
// TODO [todr] Optimize?
for pos in off..off+slice.len() {
self[pos] = slice[pos - off];
}
}
fn write(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
value.to_big_endian(&mut self[off..off+32]);
}
fn write_byte(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
let val = value.low_u64() as u64;
self[off] = val as u8;
}
fn resize(&mut self, new_size: usize) {
self.resize(new_size, 0);
}
fn expand(&mut self, size: usize) {
if size > self.len() {
Memory::resize(self, size)
}
}
}
#[test]
fn test_memory_read_and_write() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(0x80 + 32);
// when
mem.write(U256::from(0x80), U256::from(0xabcdef));
// then
assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef));
}
#[test]
fn
|
() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(32);
// when
mem.write_byte(U256::from(0x1d), U256::from(0xab));
mem.write_byte(U256::from(0x1e), U256::from(0xcd));
mem.write_byte(U256::from(0x1f), U256::from(0xef));
// then
assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef));
}
|
test_memory_read_and_write_byte
|
identifier_name
|
memory.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::{U256, Uint};
pub trait Memory {
/// Retrieve current size of the memory
fn size(&self) -> usize;
/// Resize (shrink or expand) the memory to specified size (fills 0)
fn resize(&mut self, new_size: usize);
/// Resize the memory only if its smaller
fn expand(&mut self, new_size: usize);
/// Write single byte to memory
fn write_byte(&mut self, offset: U256, value: U256);
/// Write a word to memory. Does not resize memory!
fn write(&mut self, offset: U256, value: U256);
/// Read a word from memory
fn read(&self, offset: U256) -> U256;
/// Write slice of bytes to memory. Does not resize memory!
fn write_slice(&mut self, offset: U256, &[u8]);
/// Retrieve part of the memory between offset and offset + size
fn read_slice(&self, offset: U256, size: U256) -> &[u8];
/// Retrieve writeable part of memory
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut[u8];
fn dump(&self);
}
/// Checks whether offset and size is valid memory range
fn is_valid_range(off: usize, size: usize) -> bool {
// When size is zero we haven't actually expanded the memory
let overflow = off.overflowing_add(size).1;
size > 0 &&!overflow
}
impl Memory for Vec<u8> {
fn dump(&self) {
println!("MemoryDump:");
for i in self.iter() {
println!("{:02x} ", i);
}
println!("");
}
fn size(&self) -> usize {
self.len()
}
fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] {
let off = init_off_u.low_u64() as usize;
let size = init_size_u.low_u64() as usize;
if!is_valid_range(off, size) {
&self[0..0]
} else {
&self[off..off+size]
}
}
fn read(&self, offset: U256) -> U256 {
let off = offset.low_u64() as usize;
U256::from(&self[off..off+32])
}
fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] {
let off = offset.low_u64() as usize;
let s = size.low_u64() as usize;
if!is_valid_range(off, s) {
&mut self[0..0]
} else {
&mut self[off..off+s]
}
}
fn write_slice(&mut self, offset: U256, slice: &[u8]) {
let off = offset.low_u64() as usize;
// TODO [todr] Optimize?
for pos in off..off+slice.len() {
self[pos] = slice[pos - off];
}
}
fn write(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
value.to_big_endian(&mut self[off..off+32]);
}
fn write_byte(&mut self, offset: U256, value: U256) {
let off = offset.low_u64() as usize;
let val = value.low_u64() as u64;
self[off] = val as u8;
}
fn resize(&mut self, new_size: usize) {
self.resize(new_size, 0);
}
fn expand(&mut self, size: usize) {
if size > self.len() {
Memory::resize(self, size)
}
}
}
#[test]
fn test_memory_read_and_write() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(0x80 + 32);
// when
mem.write(U256::from(0x80), U256::from(0xabcdef));
// then
assert_eq!(mem.read(U256::from(0x80)), U256::from(0xabcdef));
}
#[test]
fn test_memory_read_and_write_byte() {
// given
let mem: &mut Memory = &mut vec![];
mem.resize(32);
// when
mem.write_byte(U256::from(0x1d), U256::from(0xab));
mem.write_byte(U256::from(0x1e), U256::from(0xcd));
mem.write_byte(U256::from(0x1f), U256::from(0xef));
// then
assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef));
}
|
random_line_split
|
|
match-in-macro.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(macro_rules, struct_variant)]
enum Foo {
B { b1: int, bb1: int},
}
macro_rules! match_inside_expansion(
() => (
match B { b1:29, bb1: 100} {
B { b1:b2, bb1:bb2 } => b2+bb2
}
)
)
|
}
|
pub fn main() {
assert_eq!(match_inside_expansion!(),129);
|
random_line_split
|
match-in-macro.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(macro_rules, struct_variant)]
enum
|
{
B { b1: int, bb1: int},
}
macro_rules! match_inside_expansion(
() => (
match B { b1:29, bb1: 100} {
B { b1:b2, bb1:bb2 } => b2+bb2
}
)
)
pub fn main() {
assert_eq!(match_inside_expansion!(),129);
}
|
Foo
|
identifier_name
|
match-in-macro.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(macro_rules, struct_variant)]
enum Foo {
B { b1: int, bb1: int},
}
macro_rules! match_inside_expansion(
() => (
match B { b1:29, bb1: 100} {
B { b1:b2, bb1:bb2 } => b2+bb2
}
)
)
pub fn main()
|
{
assert_eq!(match_inside_expansion!(),129);
}
|
identifier_body
|
|
deb.rs
|
use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn installed_packages() -> Result<Vec<Package>, Error> {
Command::new("dpkg-query").arg("-f='${Package} ${Version}\n'").arg("-W")
.output()
.map_err(|e| Error::Package(format!("Error fetching packages: {}", e)))
.and_then(|c| {
String::from_utf8(c.stdout)
.map_err(|e| Error::Parse(format!("Error parsing package: {}", e)))
.map(|s| s.lines().map(String::from).collect::<Vec<String>>())
})
.and_then(|lines| {
lines.iter()
.map(|line| parse_package(line))
.filter(|pkg| pkg.is_ok())
.collect::<Result<Vec<Package>, _>>()
})
}
/// Installs a new DEB package.
pub fn install_package(path: &str) -> Result<InstallOutcome, InstallOutcome>
|
}
}
|
{
let output = try!(Command::new("dpkg").arg("-E").arg("-i").arg(path)
.output()
.map_err(|e| (UpdateResultCode::GENERAL_ERROR, format!("{:?}", e))));
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
match output.status.code() {
Some(0) => {
if (&stdout).contains("already installed") {
Ok((UpdateResultCode::ALREADY_PROCESSED, stdout))
} else {
Ok((UpdateResultCode::OK, stdout))
}
}
_ => {
let out = format!("stdout: {}\nstderr: {}", stdout, stderr);
Err((UpdateResultCode::INSTALL_FAILED, out))
}
|
identifier_body
|
deb.rs
|
use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn installed_packages() -> Result<Vec<Package>, Error> {
Command::new("dpkg-query").arg("-f='${Package} ${Version}\n'").arg("-W")
.output()
.map_err(|e| Error::Package(format!("Error fetching packages: {}", e)))
.and_then(|c| {
String::from_utf8(c.stdout)
.map_err(|e| Error::Parse(format!("Error parsing package: {}", e)))
.map(|s| s.lines().map(String::from).collect::<Vec<String>>())
})
.and_then(|lines| {
lines.iter()
.map(|line| parse_package(line))
.filter(|pkg| pkg.is_ok())
.collect::<Result<Vec<Package>, _>>()
})
}
/// Installs a new DEB package.
pub fn install_package(path: &str) -> Result<InstallOutcome, InstallOutcome> {
let output = try!(Command::new("dpkg").arg("-E").arg("-i").arg(path)
.output()
.map_err(|e| (UpdateResultCode::GENERAL_ERROR, format!("{:?}", e))));
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
|
Ok((UpdateResultCode::ALREADY_PROCESSED, stdout))
} else {
Ok((UpdateResultCode::OK, stdout))
}
}
_ => {
let out = format!("stdout: {}\nstderr: {}", stdout, stderr);
Err((UpdateResultCode::INSTALL_FAILED, out))
}
}
}
|
match output.status.code() {
Some(0) => {
if (&stdout).contains("already installed") {
|
random_line_split
|
deb.rs
|
use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn installed_packages() -> Result<Vec<Package>, Error> {
Command::new("dpkg-query").arg("-f='${Package} ${Version}\n'").arg("-W")
.output()
.map_err(|e| Error::Package(format!("Error fetching packages: {}", e)))
.and_then(|c| {
String::from_utf8(c.stdout)
.map_err(|e| Error::Parse(format!("Error parsing package: {}", e)))
.map(|s| s.lines().map(String::from).collect::<Vec<String>>())
})
.and_then(|lines| {
lines.iter()
.map(|line| parse_package(line))
.filter(|pkg| pkg.is_ok())
.collect::<Result<Vec<Package>, _>>()
})
}
/// Installs a new DEB package.
pub fn install_package(path: &str) -> Result<InstallOutcome, InstallOutcome> {
let output = try!(Command::new("dpkg").arg("-E").arg("-i").arg(path)
.output()
.map_err(|e| (UpdateResultCode::GENERAL_ERROR, format!("{:?}", e))));
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
match output.status.code() {
Some(0) =>
|
_ => {
let out = format!("stdout: {}\nstderr: {}", stdout, stderr);
Err((UpdateResultCode::INSTALL_FAILED, out))
}
}
}
|
{
if (&stdout).contains("already installed") {
Ok((UpdateResultCode::ALREADY_PROCESSED, stdout))
} else {
Ok((UpdateResultCode::OK, stdout))
}
}
|
conditional_block
|
deb.rs
|
use std::process::Command;
use datatype::{Error, Package, UpdateResultCode};
use package_manager::package_manager::{InstallOutcome, parse_package};
/// Returns a list of installed DEB packages with
/// `dpkg-query -f='${Package} ${Version}\n' -W`.
pub fn
|
() -> Result<Vec<Package>, Error> {
Command::new("dpkg-query").arg("-f='${Package} ${Version}\n'").arg("-W")
.output()
.map_err(|e| Error::Package(format!("Error fetching packages: {}", e)))
.and_then(|c| {
String::from_utf8(c.stdout)
.map_err(|e| Error::Parse(format!("Error parsing package: {}", e)))
.map(|s| s.lines().map(String::from).collect::<Vec<String>>())
})
.and_then(|lines| {
lines.iter()
.map(|line| parse_package(line))
.filter(|pkg| pkg.is_ok())
.collect::<Result<Vec<Package>, _>>()
})
}
/// Installs a new DEB package.
pub fn install_package(path: &str) -> Result<InstallOutcome, InstallOutcome> {
let output = try!(Command::new("dpkg").arg("-E").arg("-i").arg(path)
.output()
.map_err(|e| (UpdateResultCode::GENERAL_ERROR, format!("{:?}", e))));
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
match output.status.code() {
Some(0) => {
if (&stdout).contains("already installed") {
Ok((UpdateResultCode::ALREADY_PROCESSED, stdout))
} else {
Ok((UpdateResultCode::OK, stdout))
}
}
_ => {
let out = format!("stdout: {}\nstderr: {}", stdout, stderr);
Err((UpdateResultCode::INSTALL_FAILED, out))
}
}
}
|
installed_packages
|
identifier_name
|
variable3x5x8.rs
|
pub fn bits_used_for_label(label: u64) -> u8 {
if label & 0b1!= 0 {
3 + 1
} else if label & 0b10!= 0 {
5 + 2
} else {
8 + 2
}
}
pub fn bits_used_for_number(number: u32) -> u8 {
match number {
n if n < 8 => 3 + 1,
n if n < 33 => 5 + 2,
_ => 8 + 2
}
}
pub fn compress(number: u32) -> u64 {
if number == 1 {
return 1;
}
match bits_used_for_number(number) {
4 => {
match number {
0 => 0b0011,
n => ((n << 1) | 0b1) as u64
}
},
7 => {
match number {
0 => 0b000_0010,
n => (((n - 1) << 2) | 0b10) as u64
}
},
10 => {
match number {
0 => 0b00_0000_0000,
n => ((n - 1) << 2) as u64
}
},
_ => unreachable!()
}
}
pub fn
|
(label: u64) -> u32 {
match bits_used_for_label(label) {
4 => {
match (label >> 1) & 0b111 {
0b000 => 1,
0b001 => 0,
n => n as u32
}
},
7 => {
match (label >> 2) & 0b1_1111 {
0b0_0000 => 0,
n => (n + 1) as u32
}
},
10 => {
match (label >> 2) & 0b1111_1111 {
0b0000_0000 => 0,
n => (n + 1) as u32
}
},
_ => unreachable!()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compress_decompress() {
for i in range(0, 257) {
assert_eq!(i, decompress(compress(i)))
}
}
}
|
decompress
|
identifier_name
|
variable3x5x8.rs
|
pub fn bits_used_for_label(label: u64) -> u8 {
if label & 0b1!= 0 {
3 + 1
} else if label & 0b10!= 0 {
5 + 2
} else {
8 + 2
}
}
pub fn bits_used_for_number(number: u32) -> u8 {
match number {
n if n < 8 => 3 + 1,
n if n < 33 => 5 + 2,
_ => 8 + 2
}
}
pub fn compress(number: u32) -> u64 {
if number == 1 {
return 1;
}
match bits_used_for_number(number) {
4 => {
match number {
0 => 0b0011,
n => ((n << 1) | 0b1) as u64
}
},
7 => {
match number {
0 => 0b000_0010,
n => (((n - 1) << 2) | 0b10) as u64
}
},
10 => {
match number {
0 => 0b00_0000_0000,
n => ((n - 1) << 2) as u64
}
},
_ => unreachable!()
}
}
pub fn decompress(label: u64) -> u32 {
match bits_used_for_label(label) {
4 => {
match (label >> 1) & 0b111 {
0b000 => 1,
0b001 => 0,
n => n as u32
}
},
7 => {
match (label >> 2) & 0b1_1111 {
0b0_0000 => 0,
n => (n + 1) as u32
}
},
10 => {
match (label >> 2) & 0b1111_1111 {
|
},
_ => unreachable!()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compress_decompress() {
for i in range(0, 257) {
assert_eq!(i, decompress(compress(i)))
}
}
}
|
0b0000_0000 => 0,
n => (n + 1) as u32
}
|
random_line_split
|
variable3x5x8.rs
|
pub fn bits_used_for_label(label: u64) -> u8 {
if label & 0b1!= 0 {
3 + 1
} else if label & 0b10!= 0 {
5 + 2
} else {
8 + 2
}
}
pub fn bits_used_for_number(number: u32) -> u8
|
pub fn compress(number: u32) -> u64 {
if number == 1 {
return 1;
}
match bits_used_for_number(number) {
4 => {
match number {
0 => 0b0011,
n => ((n << 1) | 0b1) as u64
}
},
7 => {
match number {
0 => 0b000_0010,
n => (((n - 1) << 2) | 0b10) as u64
}
},
10 => {
match number {
0 => 0b00_0000_0000,
n => ((n - 1) << 2) as u64
}
},
_ => unreachable!()
}
}
pub fn decompress(label: u64) -> u32 {
match bits_used_for_label(label) {
4 => {
match (label >> 1) & 0b111 {
0b000 => 1,
0b001 => 0,
n => n as u32
}
},
7 => {
match (label >> 2) & 0b1_1111 {
0b0_0000 => 0,
n => (n + 1) as u32
}
},
10 => {
match (label >> 2) & 0b1111_1111 {
0b0000_0000 => 0,
n => (n + 1) as u32
}
},
_ => unreachable!()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compress_decompress() {
for i in range(0, 257) {
assert_eq!(i, decompress(compress(i)))
}
}
}
|
{
match number {
n if n < 8 => 3 + 1,
n if n < 33 => 5 + 2,
_ => 8 + 2
}
}
|
identifier_body
|
timer.rs
|
use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `read()` to block until
/// done.
///
/// Note the timer effective resolution is limited by underlying mio timer.
/// See `mioco::sleep()` for details.
pub struct Timer {
rc: RcEventSource<TimerCore>,
}
struct TimerCore {
// TODO: Rename these two?
timeout: Instant,
mio_timeout: Option<mio_orig::Timeout>,
}
impl Timer {
/// Create a new timer
pub fn new() -> Timer {
let timer_core = TimerCore {
timeout: Instant::now(),
mio_timeout: None,
};
Timer { rc: RcEventSource::new(timer_core) }
}
fn is_done(&self) -> bool {
self.rc.io_ref().should_resume()
}
}
impl Default for Timer {
fn default() -> Self {
Timer::new()
}
}
impl EventedImpl for Timer {
type Raw = TimerCore;
fn shared(&self) -> &RcEventSource<TimerCore> {
&self.rc
}
}
impl Timer {
/// Read a timer to block on it until it is done.
///
/// Returns current time
///
/// TODO: Return wakeup time instead
pub fn read(&mut self) -> Instant {
loop {
if let Some(t) = self.try_read() {
return t;
}
self.block_on(RW::read());
}
}
/// Try reading current time (if the timer is done)
///
/// TODO: Return wakeup time instead
pub fn try_read(&mut self) -> Option<Instant> {
let done = self.is_done();
if done {
Some(Instant::now())
} else {
None
}
}
/// Set timeout for the timer
///
/// The timeout counts from the time `set_timeout` is called.
///
/// Note the timer effective resolution is limited by underlying mio
/// timer. See `mioco::sleep()` for details.
pub fn set_timeout(&mut self, delay_ms: u64) {
self.rc.io_mut().timeout = Instant::now() + Duration::from_millis(delay_ms);
}
/// Set timeout for the timer using absolute time.
pub fn set_timeout_absolute(&mut self, timeout: Instant) {
self.rc.io_mut().timeout = timeout;
}
/// Get absolute value of the timer timeout.
pub fn get_timeout_absolute(&mut self) -> Instant {
|
fn should_resume(&self) -> bool {
trace!("Timer: should_resume? {}",
self.timeout <= Instant::now());
self.timeout <= Instant::now()
}
}
impl EventSourceTrait for TimerCore {
fn register(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
_interest: EventSet) -> bool {
let timeout = self.timeout;
let now = Instant::now();
let delay = if timeout <= now {
return true
} else {
let elapsed = timeout - now;
elapsed.as_secs() * 1000 + (elapsed.subsec_nanos() / 1000_000) as u64
};
trace!("Timer({}): set timeout in {}ms", token.as_usize(), delay);
match event_loop.timeout_ms(token, delay) {
Ok(timeout) => {
self.mio_timeout = Some(timeout);
}
Err(reason) => {
panic!("Could not create mio::Timeout: {:?}", reason);
}
}
false
}
fn reregister(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
interest: EventSet) -> bool {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
self.register(event_loop, token, interest)
}
fn deregister(&mut self, event_loop: &mut EventLoop<Handler>, _token: Token) {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
}
}
unsafe impl Send for Timer {}
|
self.rc.io_ref().timeout
}
}
impl TimerCore {
|
random_line_split
|
timer.rs
|
use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `read()` to block until
/// done.
///
/// Note the timer effective resolution is limited by underlying mio timer.
/// See `mioco::sleep()` for details.
pub struct Timer {
rc: RcEventSource<TimerCore>,
}
struct TimerCore {
// TODO: Rename these two?
timeout: Instant,
mio_timeout: Option<mio_orig::Timeout>,
}
impl Timer {
/// Create a new timer
pub fn new() -> Timer {
let timer_core = TimerCore {
timeout: Instant::now(),
mio_timeout: None,
};
Timer { rc: RcEventSource::new(timer_core) }
}
fn is_done(&self) -> bool {
self.rc.io_ref().should_resume()
}
}
impl Default for Timer {
fn default() -> Self
|
}
impl EventedImpl for Timer {
type Raw = TimerCore;
fn shared(&self) -> &RcEventSource<TimerCore> {
&self.rc
}
}
impl Timer {
/// Read a timer to block on it until it is done.
///
/// Returns current time
///
/// TODO: Return wakeup time instead
pub fn read(&mut self) -> Instant {
loop {
if let Some(t) = self.try_read() {
return t;
}
self.block_on(RW::read());
}
}
/// Try reading current time (if the timer is done)
///
/// TODO: Return wakeup time instead
pub fn try_read(&mut self) -> Option<Instant> {
let done = self.is_done();
if done {
Some(Instant::now())
} else {
None
}
}
/// Set timeout for the timer
///
/// The timeout counts from the time `set_timeout` is called.
///
/// Note the timer effective resolution is limited by underlying mio
/// timer. See `mioco::sleep()` for details.
pub fn set_timeout(&mut self, delay_ms: u64) {
self.rc.io_mut().timeout = Instant::now() + Duration::from_millis(delay_ms);
}
/// Set timeout for the timer using absolute time.
pub fn set_timeout_absolute(&mut self, timeout: Instant) {
self.rc.io_mut().timeout = timeout;
}
/// Get absolute value of the timer timeout.
pub fn get_timeout_absolute(&mut self) -> Instant {
self.rc.io_ref().timeout
}
}
impl TimerCore {
fn should_resume(&self) -> bool {
trace!("Timer: should_resume? {}",
self.timeout <= Instant::now());
self.timeout <= Instant::now()
}
}
impl EventSourceTrait for TimerCore {
fn register(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
_interest: EventSet) -> bool {
let timeout = self.timeout;
let now = Instant::now();
let delay = if timeout <= now {
return true
} else {
let elapsed = timeout - now;
elapsed.as_secs() * 1000 + (elapsed.subsec_nanos() / 1000_000) as u64
};
trace!("Timer({}): set timeout in {}ms", token.as_usize(), delay);
match event_loop.timeout_ms(token, delay) {
Ok(timeout) => {
self.mio_timeout = Some(timeout);
}
Err(reason) => {
panic!("Could not create mio::Timeout: {:?}", reason);
}
}
false
}
fn reregister(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
interest: EventSet) -> bool {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
self.register(event_loop, token, interest)
}
fn deregister(&mut self, event_loop: &mut EventLoop<Handler>, _token: Token) {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
}
}
unsafe impl Send for Timer {}
|
{
Timer::new()
}
|
identifier_body
|
timer.rs
|
use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `read()` to block until
/// done.
///
/// Note the timer effective resolution is limited by underlying mio timer.
/// See `mioco::sleep()` for details.
pub struct Timer {
rc: RcEventSource<TimerCore>,
}
struct TimerCore {
// TODO: Rename these two?
timeout: Instant,
mio_timeout: Option<mio_orig::Timeout>,
}
impl Timer {
/// Create a new timer
pub fn new() -> Timer {
let timer_core = TimerCore {
timeout: Instant::now(),
mio_timeout: None,
};
Timer { rc: RcEventSource::new(timer_core) }
}
fn is_done(&self) -> bool {
self.rc.io_ref().should_resume()
}
}
impl Default for Timer {
fn default() -> Self {
Timer::new()
}
}
impl EventedImpl for Timer {
type Raw = TimerCore;
fn shared(&self) -> &RcEventSource<TimerCore> {
&self.rc
}
}
impl Timer {
/// Read a timer to block on it until it is done.
///
/// Returns current time
///
/// TODO: Return wakeup time instead
pub fn read(&mut self) -> Instant {
loop {
if let Some(t) = self.try_read() {
return t;
}
self.block_on(RW::read());
}
}
/// Try reading current time (if the timer is done)
///
/// TODO: Return wakeup time instead
pub fn try_read(&mut self) -> Option<Instant> {
let done = self.is_done();
if done {
Some(Instant::now())
} else {
None
}
}
/// Set timeout for the timer
///
/// The timeout counts from the time `set_timeout` is called.
///
/// Note the timer effective resolution is limited by underlying mio
/// timer. See `mioco::sleep()` for details.
pub fn set_timeout(&mut self, delay_ms: u64) {
self.rc.io_mut().timeout = Instant::now() + Duration::from_millis(delay_ms);
}
/// Set timeout for the timer using absolute time.
pub fn set_timeout_absolute(&mut self, timeout: Instant) {
self.rc.io_mut().timeout = timeout;
}
/// Get absolute value of the timer timeout.
pub fn get_timeout_absolute(&mut self) -> Instant {
self.rc.io_ref().timeout
}
}
impl TimerCore {
fn should_resume(&self) -> bool {
trace!("Timer: should_resume? {}",
self.timeout <= Instant::now());
self.timeout <= Instant::now()
}
}
impl EventSourceTrait for TimerCore {
fn register(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
_interest: EventSet) -> bool {
let timeout = self.timeout;
let now = Instant::now();
let delay = if timeout <= now {
return true
} else {
let elapsed = timeout - now;
elapsed.as_secs() * 1000 + (elapsed.subsec_nanos() / 1000_000) as u64
};
trace!("Timer({}): set timeout in {}ms", token.as_usize(), delay);
match event_loop.timeout_ms(token, delay) {
Ok(timeout) => {
self.mio_timeout = Some(timeout);
}
Err(reason) =>
|
}
false
}
fn reregister(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
interest: EventSet) -> bool {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
self.register(event_loop, token, interest)
}
fn deregister(&mut self, event_loop: &mut EventLoop<Handler>, _token: Token) {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
}
}
unsafe impl Send for Timer {}
|
{
panic!("Could not create mio::Timeout: {:?}", reason);
}
|
conditional_block
|
timer.rs
|
use super::RW;
use super::thread::Handler;
use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl};
use mio_orig::{self, EventLoop, Token, EventSet};
use std::time::{Instant, Duration};
/// A Timer generating event after a given time
///
/// Use `MiocoHandle::select()` to wait for an event, or `read()` to block until
/// done.
///
/// Note the timer effective resolution is limited by underlying mio timer.
/// See `mioco::sleep()` for details.
pub struct Timer {
rc: RcEventSource<TimerCore>,
}
struct TimerCore {
// TODO: Rename these two?
timeout: Instant,
mio_timeout: Option<mio_orig::Timeout>,
}
impl Timer {
/// Create a new timer
pub fn new() -> Timer {
let timer_core = TimerCore {
timeout: Instant::now(),
mio_timeout: None,
};
Timer { rc: RcEventSource::new(timer_core) }
}
fn is_done(&self) -> bool {
self.rc.io_ref().should_resume()
}
}
impl Default for Timer {
fn default() -> Self {
Timer::new()
}
}
impl EventedImpl for Timer {
type Raw = TimerCore;
fn shared(&self) -> &RcEventSource<TimerCore> {
&self.rc
}
}
impl Timer {
/// Read a timer to block on it until it is done.
///
/// Returns current time
///
/// TODO: Return wakeup time instead
pub fn read(&mut self) -> Instant {
loop {
if let Some(t) = self.try_read() {
return t;
}
self.block_on(RW::read());
}
}
/// Try reading current time (if the timer is done)
///
/// TODO: Return wakeup time instead
pub fn try_read(&mut self) -> Option<Instant> {
let done = self.is_done();
if done {
Some(Instant::now())
} else {
None
}
}
/// Set timeout for the timer
///
/// The timeout counts from the time `set_timeout` is called.
///
/// Note the timer effective resolution is limited by underlying mio
/// timer. See `mioco::sleep()` for details.
pub fn set_timeout(&mut self, delay_ms: u64) {
self.rc.io_mut().timeout = Instant::now() + Duration::from_millis(delay_ms);
}
/// Set timeout for the timer using absolute time.
pub fn set_timeout_absolute(&mut self, timeout: Instant) {
self.rc.io_mut().timeout = timeout;
}
/// Get absolute value of the timer timeout.
pub fn get_timeout_absolute(&mut self) -> Instant {
self.rc.io_ref().timeout
}
}
impl TimerCore {
fn should_resume(&self) -> bool {
trace!("Timer: should_resume? {}",
self.timeout <= Instant::now());
self.timeout <= Instant::now()
}
}
impl EventSourceTrait for TimerCore {
fn register(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
_interest: EventSet) -> bool {
let timeout = self.timeout;
let now = Instant::now();
let delay = if timeout <= now {
return true
} else {
let elapsed = timeout - now;
elapsed.as_secs() * 1000 + (elapsed.subsec_nanos() / 1000_000) as u64
};
trace!("Timer({}): set timeout in {}ms", token.as_usize(), delay);
match event_loop.timeout_ms(token, delay) {
Ok(timeout) => {
self.mio_timeout = Some(timeout);
}
Err(reason) => {
panic!("Could not create mio::Timeout: {:?}", reason);
}
}
false
}
fn reregister(&mut self,
event_loop: &mut EventLoop<Handler>,
token: Token,
interest: EventSet) -> bool {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
self.register(event_loop, token, interest)
}
fn
|
(&mut self, event_loop: &mut EventLoop<Handler>, _token: Token) {
if let Some(timeout) = self.mio_timeout {
event_loop.clear_timeout(timeout);
}
}
}
unsafe impl Send for Timer {}
|
deregister
|
identifier_name
|
sched.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
|
/// Lock the calling thread to CPU `cpu_index`
pub fn set_cpu_affinity(cpu_index: usize) -> Result<(), nix::Error> {
let pid = nix::unistd::Pid::from_raw(0);
let mut cpuset = nix::sched::CpuSet::new();
cpuset.set(cpu_index)?;
nix::sched::sched_setaffinity(pid, &cpuset)?;
Ok(())
}
|
random_line_split
|
|
sched.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
/// Lock the calling thread to CPU `cpu_index`
pub fn set_cpu_affinity(cpu_index: usize) -> Result<(), nix::Error>
|
{
let pid = nix::unistd::Pid::from_raw(0);
let mut cpuset = nix::sched::CpuSet::new();
cpuset.set(cpu_index)?;
nix::sched::sched_setaffinity(pid, &cpuset)?;
Ok(())
}
|
identifier_body
|
|
sched.rs
|
/*
Precached - A Linux process monitor and pre-caching daemon
Copyright (C) 2017-2020 the precached developers
This file is part of precached.
Precached 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.
Precached 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 Precached. If not, see <http://www.gnu.org/licenses/>.
*/
/// Lock the calling thread to CPU `cpu_index`
pub fn
|
(cpu_index: usize) -> Result<(), nix::Error> {
let pid = nix::unistd::Pid::from_raw(0);
let mut cpuset = nix::sched::CpuSet::new();
cpuset.set(cpu_index)?;
nix::sched::sched_setaffinity(pid, &cpuset)?;
Ok(())
}
|
set_cpu_affinity
|
identifier_name
|
multiwindow.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main() {
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::scoped(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::scoped(move || {
run(window2, (0.0, 0.0, 1.0, 1.0));
});
let t3 = Thread::scoped(move || {
run(window3, (1.0, 0.0, 0.0, 1.0));
});
let _ = t1.join();
let _ = t2.join();
let _ = t3.join();
}
#[cfg(feature = "window")]
fn run(window: glutin::Window, color: (f32, f32, f32, f32)) {
|
context.draw_frame(color);
window.swap_buffers();
window.wait_events().next();
}
}
|
unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() {
|
random_line_split
|
multiwindow.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main()
|
}
#[cfg(feature = "window")]
fn run(window: glutin::Window, color: (f32, f32, f32, f32)) {
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().next();
}
}
|
{
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::scoped(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::scoped(move || {
run(window2, (0.0, 0.0, 1.0, 1.0));
});
let t3 = Thread::scoped(move || {
run(window3, (1.0, 0.0, 0.0, 1.0));
});
let _ = t1.join();
let _ = t2.join();
let _ = t3.join();
|
identifier_body
|
multiwindow.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::thread::Thread;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = "window")]
fn main() {
let window1 = glutin::Window::new().unwrap();
let window2 = glutin::Window::new().unwrap();
let window3 = glutin::Window::new().unwrap();
let t1 = Thread::scoped(move || {
run(window1, (0.0, 1.0, 0.0, 1.0));
});
let t2 = Thread::scoped(move || {
run(window2, (0.0, 0.0, 1.0, 1.0));
});
let t3 = Thread::scoped(move || {
run(window3, (1.0, 0.0, 0.0, 1.0));
});
let _ = t1.join();
let _ = t2.join();
let _ = t3.join();
}
#[cfg(feature = "window")]
fn
|
(window: glutin::Window, color: (f32, f32, f32, f32)) {
unsafe { window.make_current() };
let context = support::load(&window);
while!window.is_closed() {
context.draw_frame(color);
window.swap_buffers();
window.wait_events().next();
}
}
|
run
|
identifier_name
|
les_request.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
|
// 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/>.
//! LES request types.
use util::H256;
/// Either a hash or a number.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub enum HashOrNumber {
/// Block hash variant.
Hash(H256),
/// Block number variant.
Number(u64),
}
impl From<H256> for HashOrNumber {
fn from(hash: H256) -> Self {
HashOrNumber::Hash(hash)
}
}
impl From<u64> for HashOrNumber {
fn from(num: u64) -> Self {
HashOrNumber::Number(num)
}
}
/// A request for block headers.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct Headers {
/// Starting block number or hash.
pub start: HashOrNumber,
/// The maximum amount of headers which can be returned.
pub max: usize,
/// The amount of headers to skip between each response entry.
pub skip: u64,
/// Whether the headers should proceed in falling number from the initial block.
pub reverse: bool,
}
/// A request for specific block bodies.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct Bodies {
/// Hashes which bodies are being requested for.
pub block_hashes: Vec<H256>
}
/// A request for transaction receipts.
///
/// This request is answered with a list of transaction receipts for each block
/// requested.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct Receipts {
/// Block hashes to return receipts for.
pub block_hashes: Vec<H256>,
}
/// A request for a state proof
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct StateProof {
/// Block hash to query state from.
pub block: H256,
/// Key of the state trie -- corresponds to account hash.
pub key1: H256,
/// Key in that account's storage trie; if empty, then the account RLP should be
/// returned.
pub key2: Option<H256>,
/// if greater than zero, trie nodes beyond this level may be omitted.
pub from_level: u32, // could even safely be u8; trie w/ 32-byte key can be at most 64-levels deep.
}
/// A request for state proofs.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct StateProofs {
/// All the proof requests.
pub requests: Vec<StateProof>,
}
/// A request for contract code.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct ContractCode {
/// Block hash
pub block_hash: H256,
/// Account key (== sha3(address))
pub account_key: H256,
}
/// A request for contract code.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct ContractCodes {
/// Block hash and account key (== sha3(address)) pairs to fetch code for.
pub code_requests: Vec<ContractCode>,
}
/// A request for a header proof from the Canonical Hash Trie.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct HeaderProof {
/// Number of the CHT.
pub cht_number: u64,
/// Block number requested.
pub block_number: u64,
/// If greater than zero, trie nodes beyond this level may be omitted.
pub from_level: u32,
}
/// A request for header proofs from the CHT.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct HeaderProofs {
/// All the proof requests.
pub requests: Vec<HeaderProof>,
}
/// Kinds of requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub enum Kind {
/// Requesting headers.
Headers,
/// Requesting block bodies.
Bodies,
/// Requesting transaction receipts.
Receipts,
/// Requesting proofs of state trie nodes.
StateProofs,
/// Requesting contract code by hash.
Codes,
/// Requesting header proofs (from the CHT).
HeaderProofs,
}
/// Encompasses all possible types of requests in a single structure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub enum Request {
/// Requesting headers.
Headers(Headers),
/// Requesting block bodies.
Bodies(Bodies),
/// Requesting transaction receipts.
Receipts(Receipts),
/// Requesting state proofs.
StateProofs(StateProofs),
/// Requesting contract codes.
Codes(ContractCodes),
/// Requesting header proofs.
HeaderProofs(HeaderProofs),
}
impl Request {
/// Get the kind of request this is.
pub fn kind(&self) -> Kind {
match *self {
Request::Headers(_) => Kind::Headers,
Request::Bodies(_) => Kind::Bodies,
Request::Receipts(_) => Kind::Receipts,
Request::StateProofs(_) => Kind::StateProofs,
Request::Codes(_) => Kind::Codes,
Request::HeaderProofs(_) => Kind::HeaderProofs,
}
}
/// Get the amount of requests being made.
pub fn amount(&self) -> usize {
match *self {
Request::Headers(ref req) => req.max,
Request::Bodies(ref req) => req.block_hashes.len(),
Request::Receipts(ref req) => req.block_hashes.len(),
Request::StateProofs(ref req) => req.requests.len(),
Request::Codes(ref req) => req.code_requests.len(),
Request::HeaderProofs(ref req) => req.requests.len(),
}
}
}
|
// Parity is free software: you can redistribute it and/or modify
|
random_line_split
|
les_request.rs
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! LES request types.
use util::H256;
/// Either a hash or a number.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub enum HashOrNumber {
/// Block hash variant.
Hash(H256),
/// Block number variant.
Number(u64),
}
impl From<H256> for HashOrNumber {
fn from(hash: H256) -> Self {
HashOrNumber::Hash(hash)
}
}
impl From<u64> for HashOrNumber {
fn from(num: u64) -> Self {
HashOrNumber::Number(num)
}
}
/// A request for block headers.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct Headers {
/// Starting block number or hash.
pub start: HashOrNumber,
/// The maximum amount of headers which can be returned.
pub max: usize,
/// The amount of headers to skip between each response entry.
pub skip: u64,
/// Whether the headers should proceed in falling number from the initial block.
pub reverse: bool,
}
/// A request for specific block bodies.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct Bodies {
/// Hashes which bodies are being requested for.
pub block_hashes: Vec<H256>
}
/// A request for transaction receipts.
///
/// This request is answered with a list of transaction receipts for each block
/// requested.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct Receipts {
/// Block hashes to return receipts for.
pub block_hashes: Vec<H256>,
}
/// A request for a state proof
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct StateProof {
/// Block hash to query state from.
pub block: H256,
/// Key of the state trie -- corresponds to account hash.
pub key1: H256,
/// Key in that account's storage trie; if empty, then the account RLP should be
/// returned.
pub key2: Option<H256>,
/// if greater than zero, trie nodes beyond this level may be omitted.
pub from_level: u32, // could even safely be u8; trie w/ 32-byte key can be at most 64-levels deep.
}
/// A request for state proofs.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct StateProofs {
/// All the proof requests.
pub requests: Vec<StateProof>,
}
/// A request for contract code.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct ContractCode {
/// Block hash
pub block_hash: H256,
/// Account key (== sha3(address))
pub account_key: H256,
}
/// A request for contract code.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct ContractCodes {
/// Block hash and account key (== sha3(address)) pairs to fetch code for.
pub code_requests: Vec<ContractCode>,
}
/// A request for a header proof from the Canonical Hash Trie.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct HeaderProof {
/// Number of the CHT.
pub cht_number: u64,
/// Block number requested.
pub block_number: u64,
/// If greater than zero, trie nodes beyond this level may be omitted.
pub from_level: u32,
}
/// A request for header proofs from the CHT.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub struct HeaderProofs {
/// All the proof requests.
pub requests: Vec<HeaderProof>,
}
/// Kinds of requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub enum
|
{
/// Requesting headers.
Headers,
/// Requesting block bodies.
Bodies,
/// Requesting transaction receipts.
Receipts,
/// Requesting proofs of state trie nodes.
StateProofs,
/// Requesting contract code by hash.
Codes,
/// Requesting header proofs (from the CHT).
HeaderProofs,
}
/// Encompasses all possible types of requests in a single structure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "ipc", derive(Binary))]
pub enum Request {
/// Requesting headers.
Headers(Headers),
/// Requesting block bodies.
Bodies(Bodies),
/// Requesting transaction receipts.
Receipts(Receipts),
/// Requesting state proofs.
StateProofs(StateProofs),
/// Requesting contract codes.
Codes(ContractCodes),
/// Requesting header proofs.
HeaderProofs(HeaderProofs),
}
impl Request {
/// Get the kind of request this is.
pub fn kind(&self) -> Kind {
match *self {
Request::Headers(_) => Kind::Headers,
Request::Bodies(_) => Kind::Bodies,
Request::Receipts(_) => Kind::Receipts,
Request::StateProofs(_) => Kind::StateProofs,
Request::Codes(_) => Kind::Codes,
Request::HeaderProofs(_) => Kind::HeaderProofs,
}
}
/// Get the amount of requests being made.
pub fn amount(&self) -> usize {
match *self {
Request::Headers(ref req) => req.max,
Request::Bodies(ref req) => req.block_hashes.len(),
Request::Receipts(ref req) => req.block_hashes.len(),
Request::StateProofs(ref req) => req.requests.len(),
Request::Codes(ref req) => req.code_requests.len(),
Request::HeaderProofs(ref req) => req.requests.len(),
}
}
}
|
Kind
|
identifier_name
|
untrusted_rlp.rs
|
// Copyright 2015-2017 Parity Technologies
//
// 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 {Decodable, DecoderError};
use impls::decode_usize;
use rustc_hex::ToHex;
use std::cell::Cell;
use std::fmt;
/// rlp offset
#[derive(Copy, Clone, Debug)]
struct OffsetCache {
index: usize,
offset: usize,
}
impl OffsetCache {
fn new(index: usize, offset: usize) -> OffsetCache {
OffsetCache { index: index, offset: offset }
}
}
#[derive(Debug)]
/// RLP prototype
pub enum Prototype {
/// Empty
Null,
/// Value
Data(usize),
/// List
List(usize),
}
/// Stores basic information about item
pub struct PayloadInfo {
/// Header length in bytes
pub header_len: usize,
/// Value length in bytes
pub value_len: usize,
}
fn calculate_payload_info(header_bytes: &[u8], len_of_len: usize) -> Result<PayloadInfo, DecoderError> {
let header_len = 1 + len_of_len;
match header_bytes.get(1) {
Some(&0) => return Err(DecoderError::RlpDataLenWithZeroPrefix),
None => return Err(DecoderError::RlpIsTooShort),
_ => (),
}
if header_bytes.len() < header_len {
return Err(DecoderError::RlpIsTooShort);
}
let value_len = decode_usize(&header_bytes[1..header_len])?;
Ok(PayloadInfo::new(header_len, value_len))
}
impl PayloadInfo {
fn new(header_len: usize, value_len: usize) -> PayloadInfo {
PayloadInfo {
header_len: header_len,
value_len: value_len,
}
}
/// Total size of the RLP.
pub fn total(&self) -> usize {
self.header_len + self.value_len
}
/// Create a new object from the given bytes RLP. The bytes
pub fn from(header_bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
match header_bytes.first().cloned() {
None => Err(DecoderError::RlpIsTooShort),
Some(0...0x7f) => Ok(PayloadInfo::new(0, 1)),
Some(l @ 0x80...0xb7) => Ok(PayloadInfo::new(1, l as usize - 0x80)),
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
calculate_payload_info(header_bytes, len_of_len)
}
Some(l @ 0xc0...0xf7) => Ok(PayloadInfo::new(1, l as usize - 0xc0)),
Some(l @ 0xf8...0xff) => {
let len_of_len = l as usize - 0xf7;
calculate_payload_info(header_bytes, len_of_len)
}
// we cant reach this place, but rust requires _ to be implemented
_ => {
unreachable!();
}
}
}
}
/// Data-oriented view onto rlp-slice.
///
/// This is an immutable structure. No operations change it.
///
/// Should be used in places where, error handling is required,
/// eg. on input
#[derive(Debug)]
pub struct UntrustedRlp<'a> {
bytes: &'a [u8],
offset_cache: Cell<OffsetCache>,
count_cache: Cell<Option<usize>>,
}
impl<'a> Clone for UntrustedRlp<'a> {
fn clone(&self) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: self.bytes,
offset_cache: self.offset_cache.clone(),
count_cache: self.count_cache.clone(),
}
}
}
impl<'a> fmt::Display for UntrustedRlp<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self.prototype() {
Ok(Prototype::Null) => write!(f, "null"),
Ok(Prototype::Data(_)) => write!(f, "\"0x{}\"", self.data().unwrap().to_hex()),
Ok(Prototype::List(len)) => {
write!(f, "[")?;
for i in 0..len - 1 {
write!(f, "{}, ", self.at(i).unwrap())?;
}
write!(f, "{}", self.at(len - 1).unwrap())?;
write!(f, "]")
}
Err(err) => write!(f, "{:?}", err),
}
}
}
impl<'a, 'view> UntrustedRlp<'a>
where
'a: 'view,
|
{
pub fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: bytes,
offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
count_cache: Cell::new(None),
}
}
pub fn as_raw(&'view self) -> &'a [u8] {
self.bytes
}
pub fn prototype(&self) -> Result<Prototype, DecoderError> {
// optimize? && return appropriate errors
if self.is_data() {
Ok(Prototype::Data(self.size()))
} else if self.is_list() {
self.item_count().map(Prototype::List)
} else {
Ok(Prototype::Null)
}
}
pub fn payload_info(&self) -> Result<PayloadInfo, DecoderError> {
BasicDecoder::payload_info(self.bytes)
}
pub fn data(&'view self) -> Result<&'a [u8], DecoderError> {
let pi = BasicDecoder::payload_info(self.bytes)?;
Ok(&self.bytes[pi.header_len..(pi.header_len + pi.value_len)])
}
pub fn item_count(&self) -> Result<usize, DecoderError> {
match self.is_list() {
true => match self.count_cache.get() {
Some(c) => Ok(c),
None => {
let c = self.iter().count();
self.count_cache.set(Some(c));
Ok(c)
}
},
false => Err(DecoderError::RlpExpectedToBeList),
}
}
pub fn size(&self) -> usize {
match self.is_data() {
// TODO: No panic on malformed data, but ideally would Err on no PayloadInfo.
true => BasicDecoder::payload_info(self.bytes).map(|b| b.value_len).unwrap_or(0),
false => 0,
}
}
pub fn at(&'view self, index: usize) -> Result<UntrustedRlp<'a>, DecoderError> {
if!self.is_list() {
return Err(DecoderError::RlpExpectedToBeList);
}
// move to cached position if its index is less or equal to
// current search index, otherwise move to beginning of list
let c = self.offset_cache.get();
let (mut bytes, to_skip) = match c.index <= index {
true => (UntrustedRlp::consume(self.bytes, c.offset)?, index - c.index),
false => (self.consume_list_payload()?, index),
};
// skip up to x items
bytes = UntrustedRlp::consume_items(bytes, to_skip)?;
// update the cache
self.offset_cache.set(OffsetCache::new(index, self.bytes.len() - bytes.len()));
// construct new rlp
let found = BasicDecoder::payload_info(bytes)?;
Ok(UntrustedRlp::new(&bytes[0..found.header_len + found.value_len]))
}
pub fn is_null(&self) -> bool {
self.bytes.len() == 0
}
pub fn is_empty(&self) -> bool {
!self.is_null() && (self.bytes[0] == 0xc0 || self.bytes[0] == 0x80)
}
pub fn is_list(&self) -> bool {
!self.is_null() && self.bytes[0] >= 0xc0
}
pub fn is_data(&self) -> bool {
!self.is_null() && self.bytes[0] < 0xc0
}
pub fn is_int(&self) -> bool {
if self.is_null() {
return false;
}
match self.bytes[0] {
0...0x80 => true,
0x81...0xb7 => self.bytes[1]!= 0,
b @ 0xb8...0xbf => self.bytes[1 + b as usize - 0xb7]!= 0,
_ => false,
}
}
pub fn iter(&'view self) -> UntrustedRlpIterator<'a, 'view> {
self.into_iter()
}
pub fn as_val<T>(&self) -> Result<T, DecoderError>
where
T: Decodable,
{
T::decode(self)
}
pub fn as_list<T>(&self) -> Result<Vec<T>, DecoderError>
where
T: Decodable,
{
self.iter().map(|rlp| rlp.as_val()).collect()
}
pub fn val_at<T>(&self, index: usize) -> Result<T, DecoderError>
where
T: Decodable,
{
self.at(index)?.as_val()
}
pub fn list_at<T>(&self, index: usize) -> Result<Vec<T>, DecoderError>
where
T: Decodable,
{
self.at(index)?.as_list()
}
pub fn decoder(&self) -> BasicDecoder {
BasicDecoder::new(self.clone())
}
/// consumes first found prefix
fn consume_list_payload(&self) -> Result<&'a [u8], DecoderError> {
let item = BasicDecoder::payload_info(self.bytes)?;
let bytes = UntrustedRlp::consume(self.bytes, item.header_len)?;
Ok(bytes)
}
/// consumes fixed number of items
fn consume_items(bytes: &'a [u8], items: usize) -> Result<&'a [u8], DecoderError> {
let mut result = bytes;
for _ in 0..items {
let i = BasicDecoder::payload_info(result)?;
result = UntrustedRlp::consume(result, (i.header_len + i.value_len))?;
}
Ok(result)
}
/// consumes slice prefix of length `len`
fn consume(bytes: &'a [u8], len: usize) -> Result<&'a [u8], DecoderError> {
match bytes.len() >= len {
true => Ok(&bytes[len..]),
false => Err(DecoderError::RlpIsTooShort),
}
}
}
/// Iterator over rlp-slice list elements.
pub struct UntrustedRlpIterator<'a, 'view>
where
'a: 'view,
{
rlp: &'view UntrustedRlp<'a>,
index: usize,
}
impl<'a, 'view> IntoIterator for &'view UntrustedRlp<'a>
where
'a: 'view,
{
type Item = UntrustedRlp<'a>;
type IntoIter = UntrustedRlpIterator<'a, 'view>;
fn into_iter(self) -> Self::IntoIter {
UntrustedRlpIterator { rlp: self, index: 0 }
}
}
impl<'a, 'view> Iterator for UntrustedRlpIterator<'a, 'view> {
type Item = UntrustedRlp<'a>;
fn next(&mut self) -> Option<UntrustedRlp<'a>> {
let index = self.index;
let result = self.rlp.at(index).ok();
self.index += 1;
result
}
}
pub struct BasicDecoder<'a> {
rlp: UntrustedRlp<'a>,
}
impl<'a> BasicDecoder<'a> {
pub fn new(rlp: UntrustedRlp<'a>) -> BasicDecoder<'a> {
BasicDecoder { rlp: rlp }
}
/// Return first item info.
fn payload_info(bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
let item = PayloadInfo::from(bytes)?;
match item.header_len.checked_add(item.value_len) {
Some(x) if x <= bytes.len() => Ok(item),
_ => Err(DecoderError::RlpIsTooShort),
}
}
pub fn decode_value<T, F>(&self, f: F) -> Result<T, DecoderError>
where
F: Fn(&[u8]) -> Result<T, DecoderError>,
{
let bytes = self.rlp.as_raw();
match bytes.first().cloned() {
// RLP is too short.
None => Err(DecoderError::RlpIsTooShort),
// Single byte value.
Some(l @ 0...0x7f) => Ok(f(&[l])?),
// 0-55 bytes
Some(l @ 0x80...0xb7) => {
let last_index_of = 1 + l as usize - 0x80;
if bytes.len() < last_index_of {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let d = &bytes[1..last_index_of];
if l == 0x81 && d[0] < 0x80 {
return Err(DecoderError::RlpInvalidIndirection);
}
Ok(f(d)?)
}
// Longer than 55 bytes.
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
let begin_of_value = 1 as usize + len_of_len;
if bytes.len() < begin_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let len = decode_usize(&bytes[1..begin_of_value])?;
let last_index_of_value = begin_of_value.checked_add(len).ok_or(DecoderError::RlpInvalidLength)?;
if bytes.len() < last_index_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
Ok(f(&bytes[begin_of_value..last_index_of_value])?)
}
// We are reading value, not a list!
_ => Err(DecoderError::RlpExpectedToBeData),
}
}
}
#[cfg(test)]
mod tests {
use {UntrustedRlp, DecoderError};
#[test]
fn test_rlp_display() {
use rustc_hex::FromHex;
let data = "f84d0589010efbef67941f79b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
.from_hex()
.unwrap();
let rlp = UntrustedRlp::new(&data);
assert_eq!(format!("{}", rlp), "[\"0x05\", \"0x010efbef67941f79b2\", \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\", \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"]");
}
#[test]
fn length_overflow() {
let bs = [0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe5];
let rlp = UntrustedRlp::new(&bs);
let res: Result<u8, DecoderError> = rlp.as_val();
assert_eq!(Err(DecoderError::RlpInvalidLength), res);
}
}
|
random_line_split
|
|
untrusted_rlp.rs
|
// Copyright 2015-2017 Parity Technologies
//
// 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 {Decodable, DecoderError};
use impls::decode_usize;
use rustc_hex::ToHex;
use std::cell::Cell;
use std::fmt;
/// rlp offset
#[derive(Copy, Clone, Debug)]
struct OffsetCache {
index: usize,
offset: usize,
}
impl OffsetCache {
fn new(index: usize, offset: usize) -> OffsetCache {
OffsetCache { index: index, offset: offset }
}
}
#[derive(Debug)]
/// RLP prototype
pub enum Prototype {
/// Empty
Null,
/// Value
Data(usize),
/// List
List(usize),
}
/// Stores basic information about item
pub struct PayloadInfo {
/// Header length in bytes
pub header_len: usize,
/// Value length in bytes
pub value_len: usize,
}
fn calculate_payload_info(header_bytes: &[u8], len_of_len: usize) -> Result<PayloadInfo, DecoderError> {
let header_len = 1 + len_of_len;
match header_bytes.get(1) {
Some(&0) => return Err(DecoderError::RlpDataLenWithZeroPrefix),
None => return Err(DecoderError::RlpIsTooShort),
_ => (),
}
if header_bytes.len() < header_len {
return Err(DecoderError::RlpIsTooShort);
}
let value_len = decode_usize(&header_bytes[1..header_len])?;
Ok(PayloadInfo::new(header_len, value_len))
}
impl PayloadInfo {
fn new(header_len: usize, value_len: usize) -> PayloadInfo {
PayloadInfo {
header_len: header_len,
value_len: value_len,
}
}
/// Total size of the RLP.
pub fn total(&self) -> usize {
self.header_len + self.value_len
}
/// Create a new object from the given bytes RLP. The bytes
pub fn from(header_bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
match header_bytes.first().cloned() {
None => Err(DecoderError::RlpIsTooShort),
Some(0...0x7f) => Ok(PayloadInfo::new(0, 1)),
Some(l @ 0x80...0xb7) => Ok(PayloadInfo::new(1, l as usize - 0x80)),
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
calculate_payload_info(header_bytes, len_of_len)
}
Some(l @ 0xc0...0xf7) => Ok(PayloadInfo::new(1, l as usize - 0xc0)),
Some(l @ 0xf8...0xff) => {
let len_of_len = l as usize - 0xf7;
calculate_payload_info(header_bytes, len_of_len)
}
// we cant reach this place, but rust requires _ to be implemented
_ => {
unreachable!();
}
}
}
}
/// Data-oriented view onto rlp-slice.
///
/// This is an immutable structure. No operations change it.
///
/// Should be used in places where, error handling is required,
/// eg. on input
#[derive(Debug)]
pub struct UntrustedRlp<'a> {
bytes: &'a [u8],
offset_cache: Cell<OffsetCache>,
count_cache: Cell<Option<usize>>,
}
impl<'a> Clone for UntrustedRlp<'a> {
fn clone(&self) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: self.bytes,
offset_cache: self.offset_cache.clone(),
count_cache: self.count_cache.clone(),
}
}
}
impl<'a> fmt::Display for UntrustedRlp<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match self.prototype() {
Ok(Prototype::Null) => write!(f, "null"),
Ok(Prototype::Data(_)) => write!(f, "\"0x{}\"", self.data().unwrap().to_hex()),
Ok(Prototype::List(len)) => {
write!(f, "[")?;
for i in 0..len - 1 {
write!(f, "{}, ", self.at(i).unwrap())?;
}
write!(f, "{}", self.at(len - 1).unwrap())?;
write!(f, "]")
}
Err(err) => write!(f, "{:?}", err),
}
}
}
impl<'a, 'view> UntrustedRlp<'a>
where
'a: 'view,
{
pub fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> {
UntrustedRlp {
bytes: bytes,
offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)),
count_cache: Cell::new(None),
}
}
pub fn as_raw(&'view self) -> &'a [u8] {
self.bytes
}
pub fn prototype(&self) -> Result<Prototype, DecoderError> {
// optimize? && return appropriate errors
if self.is_data() {
Ok(Prototype::Data(self.size()))
} else if self.is_list() {
self.item_count().map(Prototype::List)
} else {
Ok(Prototype::Null)
}
}
pub fn payload_info(&self) -> Result<PayloadInfo, DecoderError> {
BasicDecoder::payload_info(self.bytes)
}
pub fn data(&'view self) -> Result<&'a [u8], DecoderError> {
let pi = BasicDecoder::payload_info(self.bytes)?;
Ok(&self.bytes[pi.header_len..(pi.header_len + pi.value_len)])
}
pub fn item_count(&self) -> Result<usize, DecoderError> {
match self.is_list() {
true => match self.count_cache.get() {
Some(c) => Ok(c),
None => {
let c = self.iter().count();
self.count_cache.set(Some(c));
Ok(c)
}
},
false => Err(DecoderError::RlpExpectedToBeList),
}
}
pub fn size(&self) -> usize {
match self.is_data() {
// TODO: No panic on malformed data, but ideally would Err on no PayloadInfo.
true => BasicDecoder::payload_info(self.bytes).map(|b| b.value_len).unwrap_or(0),
false => 0,
}
}
pub fn at(&'view self, index: usize) -> Result<UntrustedRlp<'a>, DecoderError> {
if!self.is_list() {
return Err(DecoderError::RlpExpectedToBeList);
}
// move to cached position if its index is less or equal to
// current search index, otherwise move to beginning of list
let c = self.offset_cache.get();
let (mut bytes, to_skip) = match c.index <= index {
true => (UntrustedRlp::consume(self.bytes, c.offset)?, index - c.index),
false => (self.consume_list_payload()?, index),
};
// skip up to x items
bytes = UntrustedRlp::consume_items(bytes, to_skip)?;
// update the cache
self.offset_cache.set(OffsetCache::new(index, self.bytes.len() - bytes.len()));
// construct new rlp
let found = BasicDecoder::payload_info(bytes)?;
Ok(UntrustedRlp::new(&bytes[0..found.header_len + found.value_len]))
}
pub fn is_null(&self) -> bool {
self.bytes.len() == 0
}
pub fn is_empty(&self) -> bool {
!self.is_null() && (self.bytes[0] == 0xc0 || self.bytes[0] == 0x80)
}
pub fn is_list(&self) -> bool {
!self.is_null() && self.bytes[0] >= 0xc0
}
pub fn is_data(&self) -> bool {
!self.is_null() && self.bytes[0] < 0xc0
}
pub fn is_int(&self) -> bool {
if self.is_null() {
return false;
}
match self.bytes[0] {
0...0x80 => true,
0x81...0xb7 => self.bytes[1]!= 0,
b @ 0xb8...0xbf => self.bytes[1 + b as usize - 0xb7]!= 0,
_ => false,
}
}
pub fn iter(&'view self) -> UntrustedRlpIterator<'a, 'view> {
self.into_iter()
}
pub fn as_val<T>(&self) -> Result<T, DecoderError>
where
T: Decodable,
{
T::decode(self)
}
pub fn as_list<T>(&self) -> Result<Vec<T>, DecoderError>
where
T: Decodable,
{
self.iter().map(|rlp| rlp.as_val()).collect()
}
pub fn val_at<T>(&self, index: usize) -> Result<T, DecoderError>
where
T: Decodable,
{
self.at(index)?.as_val()
}
pub fn list_at<T>(&self, index: usize) -> Result<Vec<T>, DecoderError>
where
T: Decodable,
{
self.at(index)?.as_list()
}
pub fn decoder(&self) -> BasicDecoder {
BasicDecoder::new(self.clone())
}
/// consumes first found prefix
fn consume_list_payload(&self) -> Result<&'a [u8], DecoderError> {
let item = BasicDecoder::payload_info(self.bytes)?;
let bytes = UntrustedRlp::consume(self.bytes, item.header_len)?;
Ok(bytes)
}
/// consumes fixed number of items
fn consume_items(bytes: &'a [u8], items: usize) -> Result<&'a [u8], DecoderError> {
let mut result = bytes;
for _ in 0..items {
let i = BasicDecoder::payload_info(result)?;
result = UntrustedRlp::consume(result, (i.header_len + i.value_len))?;
}
Ok(result)
}
/// consumes slice prefix of length `len`
fn consume(bytes: &'a [u8], len: usize) -> Result<&'a [u8], DecoderError> {
match bytes.len() >= len {
true => Ok(&bytes[len..]),
false => Err(DecoderError::RlpIsTooShort),
}
}
}
/// Iterator over rlp-slice list elements.
pub struct UntrustedRlpIterator<'a, 'view>
where
'a: 'view,
{
rlp: &'view UntrustedRlp<'a>,
index: usize,
}
impl<'a, 'view> IntoIterator for &'view UntrustedRlp<'a>
where
'a: 'view,
{
type Item = UntrustedRlp<'a>;
type IntoIter = UntrustedRlpIterator<'a, 'view>;
fn into_iter(self) -> Self::IntoIter {
UntrustedRlpIterator { rlp: self, index: 0 }
}
}
impl<'a, 'view> Iterator for UntrustedRlpIterator<'a, 'view> {
type Item = UntrustedRlp<'a>;
fn next(&mut self) -> Option<UntrustedRlp<'a>> {
let index = self.index;
let result = self.rlp.at(index).ok();
self.index += 1;
result
}
}
pub struct BasicDecoder<'a> {
rlp: UntrustedRlp<'a>,
}
impl<'a> BasicDecoder<'a> {
pub fn new(rlp: UntrustedRlp<'a>) -> BasicDecoder<'a> {
BasicDecoder { rlp: rlp }
}
/// Return first item info.
fn
|
(bytes: &[u8]) -> Result<PayloadInfo, DecoderError> {
let item = PayloadInfo::from(bytes)?;
match item.header_len.checked_add(item.value_len) {
Some(x) if x <= bytes.len() => Ok(item),
_ => Err(DecoderError::RlpIsTooShort),
}
}
pub fn decode_value<T, F>(&self, f: F) -> Result<T, DecoderError>
where
F: Fn(&[u8]) -> Result<T, DecoderError>,
{
let bytes = self.rlp.as_raw();
match bytes.first().cloned() {
// RLP is too short.
None => Err(DecoderError::RlpIsTooShort),
// Single byte value.
Some(l @ 0...0x7f) => Ok(f(&[l])?),
// 0-55 bytes
Some(l @ 0x80...0xb7) => {
let last_index_of = 1 + l as usize - 0x80;
if bytes.len() < last_index_of {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let d = &bytes[1..last_index_of];
if l == 0x81 && d[0] < 0x80 {
return Err(DecoderError::RlpInvalidIndirection);
}
Ok(f(d)?)
}
// Longer than 55 bytes.
Some(l @ 0xb8...0xbf) => {
let len_of_len = l as usize - 0xb7;
let begin_of_value = 1 as usize + len_of_len;
if bytes.len() < begin_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
let len = decode_usize(&bytes[1..begin_of_value])?;
let last_index_of_value = begin_of_value.checked_add(len).ok_or(DecoderError::RlpInvalidLength)?;
if bytes.len() < last_index_of_value {
return Err(DecoderError::RlpInconsistentLengthAndData);
}
Ok(f(&bytes[begin_of_value..last_index_of_value])?)
}
// We are reading value, not a list!
_ => Err(DecoderError::RlpExpectedToBeData),
}
}
}
#[cfg(test)]
mod tests {
use {UntrustedRlp, DecoderError};
#[test]
fn test_rlp_display() {
use rustc_hex::FromHex;
let data = "f84d0589010efbef67941f79b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
.from_hex()
.unwrap();
let rlp = UntrustedRlp::new(&data);
assert_eq!(format!("{}", rlp), "[\"0x05\", \"0x010efbef67941f79b2\", \"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421\", \"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470\"]");
}
#[test]
fn length_overflow() {
let bs = [0xbf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe5];
let rlp = UntrustedRlp::new(&bs);
let res: Result<u8, DecoderError> = rlp.as_val();
assert_eq!(Err(DecoderError::RlpInvalidLength), res);
}
}
|
payload_info
|
identifier_name
|
http.rs
|
use hyper::{Client, Error};
use hyper::client::Response;
use hyper::header::ContentType;
use hyper::method::Method;
/// Makes a DELETE request to etcd.
pub fn delete(url: String) -> Result<Response, Error> {
request(Method::Delete, url)
}
/// Makes a GET request to etcd.
pub fn
|
(url: String) -> Result<Response, Error> {
request(Method::Get, url)
}
/// Makes a POST request to etcd.
pub fn post(url: String, body: String) -> Result<Response, Error> {
request_with_body(Method::Post, url, body)
}
/// Makes a PUT request to etcd.
pub fn put(url: String, body: String) -> Result<Response, Error> {
request_with_body(Method::Put, url, body)
}
// private
/// Makes a request to etcd.
fn request(method: Method, url: String) -> Result<Response, Error> {
let client = Client::new();
let request = client.request(method, &url);
request.send()
}
/// Makes a request with an HTTP body to etcd.
fn request_with_body(method: Method, url: String, body: String) -> Result<Response, Error> {
let client = Client::new();
let content_type: ContentType = ContentType(
"application/x-www-form-urlencoded".parse().unwrap()
);
let request = client.request(method, &url).header(content_type).body(&body);
request.send()
}
|
get
|
identifier_name
|
http.rs
|
use hyper::{Client, Error};
use hyper::client::Response;
use hyper::header::ContentType;
use hyper::method::Method;
/// Makes a DELETE request to etcd.
pub fn delete(url: String) -> Result<Response, Error>
|
/// Makes a GET request to etcd.
pub fn get(url: String) -> Result<Response, Error> {
request(Method::Get, url)
}
/// Makes a POST request to etcd.
pub fn post(url: String, body: String) -> Result<Response, Error> {
request_with_body(Method::Post, url, body)
}
/// Makes a PUT request to etcd.
pub fn put(url: String, body: String) -> Result<Response, Error> {
request_with_body(Method::Put, url, body)
}
// private
/// Makes a request to etcd.
fn request(method: Method, url: String) -> Result<Response, Error> {
let client = Client::new();
let request = client.request(method, &url);
request.send()
}
/// Makes a request with an HTTP body to etcd.
fn request_with_body(method: Method, url: String, body: String) -> Result<Response, Error> {
let client = Client::new();
let content_type: ContentType = ContentType(
"application/x-www-form-urlencoded".parse().unwrap()
);
let request = client.request(method, &url).header(content_type).body(&body);
request.send()
}
|
{
request(Method::Delete, url)
}
|
identifier_body
|
http.rs
|
use hyper::{Client, Error};
use hyper::client::Response;
use hyper::header::ContentType;
use hyper::method::Method;
/// Makes a DELETE request to etcd.
pub fn delete(url: String) -> Result<Response, Error> {
request(Method::Delete, url)
}
/// Makes a GET request to etcd.
pub fn get(url: String) -> Result<Response, Error> {
request(Method::Get, url)
}
/// Makes a POST request to etcd.
pub fn post(url: String, body: String) -> Result<Response, Error> {
request_with_body(Method::Post, url, body)
}
|
/// Makes a PUT request to etcd.
pub fn put(url: String, body: String) -> Result<Response, Error> {
request_with_body(Method::Put, url, body)
}
// private
/// Makes a request to etcd.
fn request(method: Method, url: String) -> Result<Response, Error> {
let client = Client::new();
let request = client.request(method, &url);
request.send()
}
/// Makes a request with an HTTP body to etcd.
fn request_with_body(method: Method, url: String, body: String) -> Result<Response, Error> {
let client = Client::new();
let content_type: ContentType = ContentType(
"application/x-www-form-urlencoded".parse().unwrap()
);
let request = client.request(method, &url).header(content_type).body(&body);
request.send()
}
|
random_line_split
|
|
include.rs
|
/*
* Copyright (c) 2017-2020 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
Inhibit,
prelude::ButtonExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::Vertical;
use relm::Widget;
use relm_derive::{Msg, widget};
use self::Msg::*;
// Define the structure of the model.
pub struct
|
{
counter: i32,
}
// The messages that can be sent to the update function.
#[derive(Msg)]
pub enum Msg {
Decrement,
Increment,
Quit,
}
#[widget]
impl Widget for Win {
// The initial model.
fn model() -> Model {
Model {
counter: 0,
}
}
// Update the model according to the message received.
fn update(&mut self, event: Msg) {
match event {
Decrement => self.model.counter -= 1,
Increment => self.model.counter += 1,
Quit => gtk::main_quit(),
}
}
// Specify a view written in another file.
view!("tests/buttons.relm");
}
fn main() {
Win::run(()).expect("Win::run failed");
}
#[cfg(test)]
mod tests {
use gtk::prelude::{ButtonExt, LabelExt};
use gtk_test::{assert_label, assert_text};
use relm_test::click;
use crate::Win;
#[test]
fn label_change() {
let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let inc_button = &widgets.inc_button;
let dec_button = &widgets.dec_button;
let label = &widgets.label;
assert_label!(inc_button, "+");
assert_label!(dec_button, "-");
assert_text!(label, 0);
click(inc_button);
assert_text!(label, 1);
click(inc_button);
assert_text!(label, 2);
click(inc_button);
assert_text!(label, 3);
click(inc_button);
assert_text!(label, 4);
click(dec_button);
assert_text!(label, 3);
click(dec_button);
assert_text!(label, 2);
click(dec_button);
assert_text!(label, 1);
click(dec_button);
assert_text!(label, 0);
click(dec_button);
assert_text!(label, -1);
}
}
|
Model
|
identifier_name
|
include.rs
|
/*
* Copyright (c) 2017-2020 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
Inhibit,
prelude::ButtonExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::Vertical;
use relm::Widget;
use relm_derive::{Msg, widget};
use self::Msg::*;
// Define the structure of the model.
pub struct Model {
counter: i32,
}
// The messages that can be sent to the update function.
#[derive(Msg)]
pub enum Msg {
Decrement,
Increment,
Quit,
}
#[widget]
impl Widget for Win {
// The initial model.
fn model() -> Model {
Model {
counter: 0,
}
}
// Update the model according to the message received.
fn update(&mut self, event: Msg) {
match event {
Decrement => self.model.counter -= 1,
Increment => self.model.counter += 1,
Quit => gtk::main_quit(),
}
}
// Specify a view written in another file.
view!("tests/buttons.relm");
}
fn main()
|
#[cfg(test)]
mod tests {
use gtk::prelude::{ButtonExt, LabelExt};
use gtk_test::{assert_label, assert_text};
use relm_test::click;
use crate::Win;
#[test]
fn label_change() {
let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let inc_button = &widgets.inc_button;
let dec_button = &widgets.dec_button;
let label = &widgets.label;
assert_label!(inc_button, "+");
assert_label!(dec_button, "-");
assert_text!(label, 0);
click(inc_button);
assert_text!(label, 1);
click(inc_button);
assert_text!(label, 2);
click(inc_button);
assert_text!(label, 3);
click(inc_button);
assert_text!(label, 4);
click(dec_button);
assert_text!(label, 3);
click(dec_button);
assert_text!(label, 2);
click(dec_button);
assert_text!(label, 1);
click(dec_button);
assert_text!(label, 0);
click(dec_button);
assert_text!(label, -1);
}
}
|
{
Win::run(()).expect("Win::run failed");
}
|
identifier_body
|
include.rs
|
/*
|
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
Inhibit,
prelude::ButtonExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::Vertical;
use relm::Widget;
use relm_derive::{Msg, widget};
use self::Msg::*;
// Define the structure of the model.
pub struct Model {
counter: i32,
}
// The messages that can be sent to the update function.
#[derive(Msg)]
pub enum Msg {
Decrement,
Increment,
Quit,
}
#[widget]
impl Widget for Win {
// The initial model.
fn model() -> Model {
Model {
counter: 0,
}
}
// Update the model according to the message received.
fn update(&mut self, event: Msg) {
match event {
Decrement => self.model.counter -= 1,
Increment => self.model.counter += 1,
Quit => gtk::main_quit(),
}
}
// Specify a view written in another file.
view!("tests/buttons.relm");
}
fn main() {
Win::run(()).expect("Win::run failed");
}
#[cfg(test)]
mod tests {
use gtk::prelude::{ButtonExt, LabelExt};
use gtk_test::{assert_label, assert_text};
use relm_test::click;
use crate::Win;
#[test]
fn label_change() {
let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let inc_button = &widgets.inc_button;
let dec_button = &widgets.dec_button;
let label = &widgets.label;
assert_label!(inc_button, "+");
assert_label!(dec_button, "-");
assert_text!(label, 0);
click(inc_button);
assert_text!(label, 1);
click(inc_button);
assert_text!(label, 2);
click(inc_button);
assert_text!(label, 3);
click(inc_button);
assert_text!(label, 4);
click(dec_button);
assert_text!(label, 3);
click(dec_button);
assert_text!(label, 2);
click(dec_button);
assert_text!(label, 1);
click(dec_button);
assert_text!(label, 0);
click(dec_button);
assert_text!(label, -1);
}
}
|
* Copyright (c) 2017-2020 Boucher, Antoni <[email protected]>
|
random_line_split
|
main.rs
|
extern crate gtk;
pub mod stack;
pub mod calc;
// use gdk::prelude::*;
use gtk::prelude::*;
use gtk::{Builder, Button, Window, TextView, TextBuffer};
fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) {
let mut idx = 0;
for num in nums_vec {
let tv = text_view.clone();
num.connect_clicked(move |_| {
let _ = tv.get_buffer().unwrap().insert_at_cursor(&idx.to_string());
});
idx += 1;
}
}
fn map_btn_insert_at_cursor(text_view: &TextView, btn: &Button, txt: &str) {
let tv = text_view.clone();
let txt_cpy: String = (*txt).to_string();
btn.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
buf.insert_at_cursor(&txt_cpy);
});
}
fn calc_and_set_result(in_buf: &TextBuffer, out_buf: &TextBuffer){
let (begin, end) = in_buf.get_bounds();
match calc::calc(&(in_buf.get_text(&begin, &end, true)).unwrap()) {
Ok(x) => {
let stringed = format!("= {}", x);
out_buf.set_text(&stringed);
},
Err(x) => out_buf.set_text(&x)
}
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("calc_win.glade");
let builder = Builder::new_from_string(glade_src);
let window: Window = builder.get_object("calc_app_win").unwrap();
let text_view: TextView = builder.get_object("input_view").unwrap();
let output_view: TextView = builder.get_object("output_view").unwrap();
let nums_vec: Vec<Button> = vec![builder.get_object("btn_0").unwrap(),
builder.get_object("btn_1").unwrap(),
builder.get_object("btn_2").unwrap(),
builder.get_object("btn_3").unwrap(),
builder.get_object("btn_4").unwrap(),
builder.get_object("btn_5").unwrap(),
builder.get_object("btn_6").unwrap(),
builder.get_object("btn_7").unwrap(),
builder.get_object("btn_8").unwrap(),
builder.get_object("btn_9").unwrap()];
let btn_calc: Button = builder.get_object("btn_calc").unwrap();
let btn_clear: Button = builder.get_object("btn_clear").unwrap();
let btn_comma: Button = builder.get_object("btn_comma").unwrap();
let btn_sub: Button = builder.get_object("btn_sub").unwrap();
let btn_add: Button = builder.get_object("btn_add").unwrap();
let btn_mul: Button = builder.get_object("btn_mul").unwrap();
let btn_div: Button = builder.get_object("btn_div").unwrap();
let btn_percent: Button = builder.get_object("btn_percent").unwrap();
|
// let btn: Button = builder.get_object("btn1").unwrap();
// let image: Image = builder.get_object("image1").unwrap();
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
//Clear output view on input view changed
let tv = text_view.clone();
let tv_out = output_view.clone();
text_view.connect_key_press_event(move |_, key|{
match key.get_keyval(){
65293 | 65421 => { //ENTER, num lock enter button
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
Inhibit(true)
},
48...57 | 65...90 | 97...122 | 94 | 37 |
46 | 42 | 47 | 65288 | 65456...65465 | 40 | 41 |
65455 | 65450 | 65453 | 65451 | 65454
=> { //nums, letters, ^, %,., *, /, space, backspace, num lock, (, ) keys
tv_out.get_buffer().unwrap().set_text("");
Inhibit(false)
},
_ =>{
//println!("VAL {}", key.get_keyval());
Inhibit(true)
}
}
});
// Map buttons
map_number_btns(&text_view, &nums_vec);
// Calc result
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_calc.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
// let stringed = format!("{}",
// calc::calc(&(buf.get_text(&begin, &end, true)).unwrap()).unwrap());
});
// Clear text view
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_clear.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
buf.set_text("");
buf_out.set_text("");
});
// Operators
map_btn_insert_at_cursor(&text_view, &btn_comma, ".");
map_btn_insert_at_cursor(&text_view, &btn_percent, "%");
map_btn_insert_at_cursor(&text_view, &btn_sub, "-");
map_btn_insert_at_cursor(&text_view, &btn_add, "+");
map_btn_insert_at_cursor(&text_view, &btn_mul, "*");
map_btn_insert_at_cursor(&text_view, &btn_div, "/");
map_btn_insert_at_cursor(&text_view, &btn_par_left, "(");
map_btn_insert_at_cursor(&text_view, &btn_par_right, ")");
window.show_all();
gtk::main();
}
|
let btn_par_left: Button = builder.get_object("btn_par_left").unwrap();
let btn_par_right: Button = builder.get_object("btn_par_right").unwrap();
|
random_line_split
|
main.rs
|
extern crate gtk;
pub mod stack;
pub mod calc;
// use gdk::prelude::*;
use gtk::prelude::*;
use gtk::{Builder, Button, Window, TextView, TextBuffer};
fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) {
let mut idx = 0;
for num in nums_vec {
let tv = text_view.clone();
num.connect_clicked(move |_| {
let _ = tv.get_buffer().unwrap().insert_at_cursor(&idx.to_string());
});
idx += 1;
}
}
fn
|
(text_view: &TextView, btn: &Button, txt: &str) {
let tv = text_view.clone();
let txt_cpy: String = (*txt).to_string();
btn.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
buf.insert_at_cursor(&txt_cpy);
});
}
fn calc_and_set_result(in_buf: &TextBuffer, out_buf: &TextBuffer){
let (begin, end) = in_buf.get_bounds();
match calc::calc(&(in_buf.get_text(&begin, &end, true)).unwrap()) {
Ok(x) => {
let stringed = format!("= {}", x);
out_buf.set_text(&stringed);
},
Err(x) => out_buf.set_text(&x)
}
}
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("calc_win.glade");
let builder = Builder::new_from_string(glade_src);
let window: Window = builder.get_object("calc_app_win").unwrap();
let text_view: TextView = builder.get_object("input_view").unwrap();
let output_view: TextView = builder.get_object("output_view").unwrap();
let nums_vec: Vec<Button> = vec![builder.get_object("btn_0").unwrap(),
builder.get_object("btn_1").unwrap(),
builder.get_object("btn_2").unwrap(),
builder.get_object("btn_3").unwrap(),
builder.get_object("btn_4").unwrap(),
builder.get_object("btn_5").unwrap(),
builder.get_object("btn_6").unwrap(),
builder.get_object("btn_7").unwrap(),
builder.get_object("btn_8").unwrap(),
builder.get_object("btn_9").unwrap()];
let btn_calc: Button = builder.get_object("btn_calc").unwrap();
let btn_clear: Button = builder.get_object("btn_clear").unwrap();
let btn_comma: Button = builder.get_object("btn_comma").unwrap();
let btn_sub: Button = builder.get_object("btn_sub").unwrap();
let btn_add: Button = builder.get_object("btn_add").unwrap();
let btn_mul: Button = builder.get_object("btn_mul").unwrap();
let btn_div: Button = builder.get_object("btn_div").unwrap();
let btn_percent: Button = builder.get_object("btn_percent").unwrap();
let btn_par_left: Button = builder.get_object("btn_par_left").unwrap();
let btn_par_right: Button = builder.get_object("btn_par_right").unwrap();
// let btn: Button = builder.get_object("btn1").unwrap();
// let image: Image = builder.get_object("image1").unwrap();
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
//Clear output view on input view changed
let tv = text_view.clone();
let tv_out = output_view.clone();
text_view.connect_key_press_event(move |_, key|{
match key.get_keyval(){
65293 | 65421 => { //ENTER, num lock enter button
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
Inhibit(true)
},
48...57 | 65...90 | 97...122 | 94 | 37 |
46 | 42 | 47 | 65288 | 65456...65465 | 40 | 41 |
65455 | 65450 | 65453 | 65451 | 65454
=> { //nums, letters, ^, %,., *, /, space, backspace, num lock, (, ) keys
tv_out.get_buffer().unwrap().set_text("");
Inhibit(false)
},
_ =>{
//println!("VAL {}", key.get_keyval());
Inhibit(true)
}
}
});
// Map buttons
map_number_btns(&text_view, &nums_vec);
// Calc result
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_calc.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
// let stringed = format!("{}",
// calc::calc(&(buf.get_text(&begin, &end, true)).unwrap()).unwrap());
});
// Clear text view
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_clear.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
buf.set_text("");
buf_out.set_text("");
});
// Operators
map_btn_insert_at_cursor(&text_view, &btn_comma, ".");
map_btn_insert_at_cursor(&text_view, &btn_percent, "%");
map_btn_insert_at_cursor(&text_view, &btn_sub, "-");
map_btn_insert_at_cursor(&text_view, &btn_add, "+");
map_btn_insert_at_cursor(&text_view, &btn_mul, "*");
map_btn_insert_at_cursor(&text_view, &btn_div, "/");
map_btn_insert_at_cursor(&text_view, &btn_par_left, "(");
map_btn_insert_at_cursor(&text_view, &btn_par_right, ")");
window.show_all();
gtk::main();
}
|
map_btn_insert_at_cursor
|
identifier_name
|
main.rs
|
extern crate gtk;
pub mod stack;
pub mod calc;
// use gdk::prelude::*;
use gtk::prelude::*;
use gtk::{Builder, Button, Window, TextView, TextBuffer};
fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) {
let mut idx = 0;
for num in nums_vec {
let tv = text_view.clone();
num.connect_clicked(move |_| {
let _ = tv.get_buffer().unwrap().insert_at_cursor(&idx.to_string());
});
idx += 1;
}
}
fn map_btn_insert_at_cursor(text_view: &TextView, btn: &Button, txt: &str) {
let tv = text_view.clone();
let txt_cpy: String = (*txt).to_string();
btn.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
buf.insert_at_cursor(&txt_cpy);
});
}
fn calc_and_set_result(in_buf: &TextBuffer, out_buf: &TextBuffer){
let (begin, end) = in_buf.get_bounds();
match calc::calc(&(in_buf.get_text(&begin, &end, true)).unwrap()) {
Ok(x) => {
let stringed = format!("= {}", x);
out_buf.set_text(&stringed);
},
Err(x) => out_buf.set_text(&x)
}
}
fn main() {
if gtk::init().is_err()
|
let glade_src = include_str!("calc_win.glade");
let builder = Builder::new_from_string(glade_src);
let window: Window = builder.get_object("calc_app_win").unwrap();
let text_view: TextView = builder.get_object("input_view").unwrap();
let output_view: TextView = builder.get_object("output_view").unwrap();
let nums_vec: Vec<Button> = vec![builder.get_object("btn_0").unwrap(),
builder.get_object("btn_1").unwrap(),
builder.get_object("btn_2").unwrap(),
builder.get_object("btn_3").unwrap(),
builder.get_object("btn_4").unwrap(),
builder.get_object("btn_5").unwrap(),
builder.get_object("btn_6").unwrap(),
builder.get_object("btn_7").unwrap(),
builder.get_object("btn_8").unwrap(),
builder.get_object("btn_9").unwrap()];
let btn_calc: Button = builder.get_object("btn_calc").unwrap();
let btn_clear: Button = builder.get_object("btn_clear").unwrap();
let btn_comma: Button = builder.get_object("btn_comma").unwrap();
let btn_sub: Button = builder.get_object("btn_sub").unwrap();
let btn_add: Button = builder.get_object("btn_add").unwrap();
let btn_mul: Button = builder.get_object("btn_mul").unwrap();
let btn_div: Button = builder.get_object("btn_div").unwrap();
let btn_percent: Button = builder.get_object("btn_percent").unwrap();
let btn_par_left: Button = builder.get_object("btn_par_left").unwrap();
let btn_par_right: Button = builder.get_object("btn_par_right").unwrap();
// let btn: Button = builder.get_object("btn1").unwrap();
// let image: Image = builder.get_object("image1").unwrap();
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
//Clear output view on input view changed
let tv = text_view.clone();
let tv_out = output_view.clone();
text_view.connect_key_press_event(move |_, key|{
match key.get_keyval(){
65293 | 65421 => { //ENTER, num lock enter button
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
Inhibit(true)
},
48...57 | 65...90 | 97...122 | 94 | 37 |
46 | 42 | 47 | 65288 | 65456...65465 | 40 | 41 |
65455 | 65450 | 65453 | 65451 | 65454
=> { //nums, letters, ^, %,., *, /, space, backspace, num lock, (, ) keys
tv_out.get_buffer().unwrap().set_text("");
Inhibit(false)
},
_ =>{
//println!("VAL {}", key.get_keyval());
Inhibit(true)
}
}
});
// Map buttons
map_number_btns(&text_view, &nums_vec);
// Calc result
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_calc.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
// let stringed = format!("{}",
// calc::calc(&(buf.get_text(&begin, &end, true)).unwrap()).unwrap());
});
// Clear text view
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_clear.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
buf.set_text("");
buf_out.set_text("");
});
// Operators
map_btn_insert_at_cursor(&text_view, &btn_comma, ".");
map_btn_insert_at_cursor(&text_view, &btn_percent, "%");
map_btn_insert_at_cursor(&text_view, &btn_sub, "-");
map_btn_insert_at_cursor(&text_view, &btn_add, "+");
map_btn_insert_at_cursor(&text_view, &btn_mul, "*");
map_btn_insert_at_cursor(&text_view, &btn_div, "/");
map_btn_insert_at_cursor(&text_view, &btn_par_left, "(");
map_btn_insert_at_cursor(&text_view, &btn_par_right, ")");
window.show_all();
gtk::main();
}
|
{
println!("Failed to initialize GTK.");
return;
}
|
conditional_block
|
main.rs
|
extern crate gtk;
pub mod stack;
pub mod calc;
// use gdk::prelude::*;
use gtk::prelude::*;
use gtk::{Builder, Button, Window, TextView, TextBuffer};
fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) {
let mut idx = 0;
for num in nums_vec {
let tv = text_view.clone();
num.connect_clicked(move |_| {
let _ = tv.get_buffer().unwrap().insert_at_cursor(&idx.to_string());
});
idx += 1;
}
}
fn map_btn_insert_at_cursor(text_view: &TextView, btn: &Button, txt: &str) {
let tv = text_view.clone();
let txt_cpy: String = (*txt).to_string();
btn.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
buf.insert_at_cursor(&txt_cpy);
});
}
fn calc_and_set_result(in_buf: &TextBuffer, out_buf: &TextBuffer){
let (begin, end) = in_buf.get_bounds();
match calc::calc(&(in_buf.get_text(&begin, &end, true)).unwrap()) {
Ok(x) => {
let stringed = format!("= {}", x);
out_buf.set_text(&stringed);
},
Err(x) => out_buf.set_text(&x)
}
}
fn main()
|
builder.get_object("btn_4").unwrap(),
builder.get_object("btn_5").unwrap(),
builder.get_object("btn_6").unwrap(),
builder.get_object("btn_7").unwrap(),
builder.get_object("btn_8").unwrap(),
builder.get_object("btn_9").unwrap()];
let btn_calc: Button = builder.get_object("btn_calc").unwrap();
let btn_clear: Button = builder.get_object("btn_clear").unwrap();
let btn_comma: Button = builder.get_object("btn_comma").unwrap();
let btn_sub: Button = builder.get_object("btn_sub").unwrap();
let btn_add: Button = builder.get_object("btn_add").unwrap();
let btn_mul: Button = builder.get_object("btn_mul").unwrap();
let btn_div: Button = builder.get_object("btn_div").unwrap();
let btn_percent: Button = builder.get_object("btn_percent").unwrap();
let btn_par_left: Button = builder.get_object("btn_par_left").unwrap();
let btn_par_right: Button = builder.get_object("btn_par_right").unwrap();
// let btn: Button = builder.get_object("btn1").unwrap();
// let image: Image = builder.get_object("image1").unwrap();
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
//Clear output view on input view changed
let tv = text_view.clone();
let tv_out = output_view.clone();
text_view.connect_key_press_event(move |_, key|{
match key.get_keyval(){
65293 | 65421 => { //ENTER, num lock enter button
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
Inhibit(true)
},
48...57 | 65...90 | 97...122 | 94 | 37 |
46 | 42 | 47 | 65288 | 65456...65465 | 40 | 41 |
65455 | 65450 | 65453 | 65451 | 65454
=> { //nums, letters, ^, %,., *, /, space, backspace, num lock, (, ) keys
tv_out.get_buffer().unwrap().set_text("");
Inhibit(false)
},
_ =>{
//println!("VAL {}", key.get_keyval());
Inhibit(true)
}
}
});
// Map buttons
map_number_btns(&text_view, &nums_vec);
// Calc result
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_calc.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
calc_and_set_result(&buf, &buf_out);
// let stringed = format!("{}",
// calc::calc(&(buf.get_text(&begin, &end, true)).unwrap()).unwrap());
});
// Clear text view
let tv = text_view.clone();
let tv_out = output_view.clone();
btn_clear.connect_clicked(move |_| {
let buf = tv.get_buffer().unwrap();
let buf_out = tv_out.get_buffer().unwrap();
buf.set_text("");
buf_out.set_text("");
});
// Operators
map_btn_insert_at_cursor(&text_view, &btn_comma, ".");
map_btn_insert_at_cursor(&text_view, &btn_percent, "%");
map_btn_insert_at_cursor(&text_view, &btn_sub, "-");
map_btn_insert_at_cursor(&text_view, &btn_add, "+");
map_btn_insert_at_cursor(&text_view, &btn_mul, "*");
map_btn_insert_at_cursor(&text_view, &btn_div, "/");
map_btn_insert_at_cursor(&text_view, &btn_par_left, "(");
map_btn_insert_at_cursor(&text_view, &btn_par_right, ")");
window.show_all();
gtk::main();
}
|
{
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let glade_src = include_str!("calc_win.glade");
let builder = Builder::new_from_string(glade_src);
let window: Window = builder.get_object("calc_app_win").unwrap();
let text_view: TextView = builder.get_object("input_view").unwrap();
let output_view: TextView = builder.get_object("output_view").unwrap();
let nums_vec: Vec<Button> = vec![builder.get_object("btn_0").unwrap(),
builder.get_object("btn_1").unwrap(),
builder.get_object("btn_2").unwrap(),
builder.get_object("btn_3").unwrap(),
|
identifier_body
|
build.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// build.rs
// Bring in a dependency on an externally maintained `gcc` package which manages
// invoking the C compiler.
extern crate gcc;
fn main()
|
{
gcc::compile_library("libtinykeccak.a", &["src/tinykeccak.c"]);
}
|
identifier_body
|
|
build.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// build.rs
// Bring in a dependency on an externally maintained `gcc` package which manages
// invoking the C compiler.
extern crate gcc;
fn
|
() {
gcc::compile_library("libtinykeccak.a", &["src/tinykeccak.c"]);
}
|
main
|
identifier_name
|
build.rs
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// build.rs
|
fn main() {
gcc::compile_library("libtinykeccak.a", &["src/tinykeccak.c"]);
}
|
// Bring in a dependency on an externally maintained `gcc` package which manages
// invoking the C compiler.
extern crate gcc;
|
random_line_split
|
music.rs
|
//! This module provides the music struct, which allows to play and control a music from a file.
use libc;
use mpv;
use std::rc::Rc;
use std::cell::RefCell;
/// The music struct.
pub struct Music {
/// Indicates wether the music is playing, paused or stopped.
status: MusicStatus,
/// The mpv handler to control the music.
mpv: Option<Rc<RefCell<mpv::MpvHandler>>>
}
impl Music {
/// Creates a new music from a path to a music file.
pub fn new(path: &str) -> Result<Music, ()> {
// Set locale, because apparently, mpv needs it
unsafe {
libc::setlocale(libc::LC_NUMERIC, &('C' as i8));
}
let mpv_builder = mpv::MpvHandlerBuilder::new().expect("Failed to init MPV builder");
let mut mpv = mpv_builder.build().expect("Failed to build MPV handler");
let _ = mpv.set_property("pause", true);
if mpv.command(&["loadfile", path]).is_err() {
return Err(())
}
let arc = Rc::new(RefCell::new(mpv));
Ok(Music {
status: MusicStatus::Stopped,
mpv: Some(arc),
})
}
/// Plays the current music.
///
/// Tells MPV to set the pause property to false.
pub fn play(&mut self) {
self.status = MusicStatus::Playing;
|
///
/// Tells MPV to set the pause property to true, and to reset the playback-time.
pub fn stop(&mut self) {
self.status = MusicStatus::Stopped;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("playback-time", 0);
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", true);
}
/// Pauses the current music.
///
/// Tells MPV to set the pause property to true.
pub fn pause(&mut self) {
self.status = MusicStatus::Paused;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", true);
}
/// Returns the status of the music.
pub fn status(&self) -> MusicStatus {
self.status
}
/// Mangages the events from MPV. Returns true if the music is finished.
pub fn event_loop(&mut self) -> bool {
let mut ended = false;
if! self.mpv.is_none() {
let mpv = self.mpv.as_mut().unwrap();
loop {
match mpv.borrow_mut().wait_event(0.0) {
Some(mpv::Event::EndFile(_)) => {
ended = true;
},
Some(_) => {
},
None => {
break;
}
}
}
}
if ended {
self.stop();
}
ended
}
}
#[derive(Copy, Clone)]
/// The different possible music statuses.
pub enum MusicStatus {
Stopped,
Playing,
Paused
}
impl MusicStatus {
/// Returns a UTF-8 icon representing the music status.
pub fn get_icon(&self) -> String {
match *self {
MusicStatus::Stopped => "⏹",
MusicStatus::Playing => "▶",
MusicStatus::Paused => "⏸",
}.to_owned()
}
}
|
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", false);
}
/// Stops the current music.
|
random_line_split
|
music.rs
|
//! This module provides the music struct, which allows to play and control a music from a file.
use libc;
use mpv;
use std::rc::Rc;
use std::cell::RefCell;
/// The music struct.
pub struct Music {
/// Indicates wether the music is playing, paused or stopped.
status: MusicStatus,
/// The mpv handler to control the music.
mpv: Option<Rc<RefCell<mpv::MpvHandler>>>
}
impl Music {
/// Creates a new music from a path to a music file.
pub fn new(path: &str) -> Result<Music, ()> {
// Set locale, because apparently, mpv needs it
unsafe {
libc::setlocale(libc::LC_NUMERIC, &('C' as i8));
}
let mpv_builder = mpv::MpvHandlerBuilder::new().expect("Failed to init MPV builder");
let mut mpv = mpv_builder.build().expect("Failed to build MPV handler");
let _ = mpv.set_property("pause", true);
if mpv.command(&["loadfile", path]).is_err() {
return Err(())
}
let arc = Rc::new(RefCell::new(mpv));
Ok(Music {
status: MusicStatus::Stopped,
mpv: Some(arc),
})
}
/// Plays the current music.
///
/// Tells MPV to set the pause property to false.
pub fn play(&mut self) {
self.status = MusicStatus::Playing;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", false);
}
/// Stops the current music.
///
/// Tells MPV to set the pause property to true, and to reset the playback-time.
pub fn stop(&mut self) {
self.status = MusicStatus::Stopped;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("playback-time", 0);
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", true);
}
/// Pauses the current music.
///
/// Tells MPV to set the pause property to true.
pub fn pause(&mut self) {
self.status = MusicStatus::Paused;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", true);
}
/// Returns the status of the music.
pub fn status(&self) -> MusicStatus {
self.status
}
/// Mangages the events from MPV. Returns true if the music is finished.
pub fn event_loop(&mut self) -> bool
|
if ended {
self.stop();
}
ended
}
}
#[derive(Copy, Clone)]
/// The different possible music statuses.
pub enum MusicStatus {
Stopped,
Playing,
Paused
}
impl MusicStatus {
/// Returns a UTF-8 icon representing the music status.
pub fn get_icon(&self) -> String {
match *self {
MusicStatus::Stopped => "⏹",
MusicStatus::Playing => "▶",
MusicStatus::Paused => "⏸",
}.to_owned()
}
}
|
{
let mut ended = false;
if ! self.mpv.is_none() {
let mpv = self.mpv.as_mut().unwrap();
loop {
match mpv.borrow_mut().wait_event(0.0) {
Some(mpv::Event::EndFile(_)) => {
ended = true;
},
Some(_) => {
},
None => {
break;
}
}
}
}
|
identifier_body
|
music.rs
|
//! This module provides the music struct, which allows to play and control a music from a file.
use libc;
use mpv;
use std::rc::Rc;
use std::cell::RefCell;
/// The music struct.
pub struct Music {
/// Indicates wether the music is playing, paused or stopped.
status: MusicStatus,
/// The mpv handler to control the music.
mpv: Option<Rc<RefCell<mpv::MpvHandler>>>
}
impl Music {
/// Creates a new music from a path to a music file.
pub fn
|
(path: &str) -> Result<Music, ()> {
// Set locale, because apparently, mpv needs it
unsafe {
libc::setlocale(libc::LC_NUMERIC, &('C' as i8));
}
let mpv_builder = mpv::MpvHandlerBuilder::new().expect("Failed to init MPV builder");
let mut mpv = mpv_builder.build().expect("Failed to build MPV handler");
let _ = mpv.set_property("pause", true);
if mpv.command(&["loadfile", path]).is_err() {
return Err(())
}
let arc = Rc::new(RefCell::new(mpv));
Ok(Music {
status: MusicStatus::Stopped,
mpv: Some(arc),
})
}
/// Plays the current music.
///
/// Tells MPV to set the pause property to false.
pub fn play(&mut self) {
self.status = MusicStatus::Playing;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", false);
}
/// Stops the current music.
///
/// Tells MPV to set the pause property to true, and to reset the playback-time.
pub fn stop(&mut self) {
self.status = MusicStatus::Stopped;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("playback-time", 0);
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", true);
}
/// Pauses the current music.
///
/// Tells MPV to set the pause property to true.
pub fn pause(&mut self) {
self.status = MusicStatus::Paused;
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", true);
}
/// Returns the status of the music.
pub fn status(&self) -> MusicStatus {
self.status
}
/// Mangages the events from MPV. Returns true if the music is finished.
pub fn event_loop(&mut self) -> bool {
let mut ended = false;
if! self.mpv.is_none() {
let mpv = self.mpv.as_mut().unwrap();
loop {
match mpv.borrow_mut().wait_event(0.0) {
Some(mpv::Event::EndFile(_)) => {
ended = true;
},
Some(_) => {
},
None => {
break;
}
}
}
}
if ended {
self.stop();
}
ended
}
}
#[derive(Copy, Clone)]
/// The different possible music statuses.
pub enum MusicStatus {
Stopped,
Playing,
Paused
}
impl MusicStatus {
/// Returns a UTF-8 icon representing the music status.
pub fn get_icon(&self) -> String {
match *self {
MusicStatus::Stopped => "⏹",
MusicStatus::Playing => "▶",
MusicStatus::Paused => "⏸",
}.to_owned()
}
}
|
new
|
identifier_name
|
util.rs
|
use std::io::{self, Result, Read, Write, ErrorKind};
//copy with length limiting
pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W, len_max: u64) -> io::Result<u64> {
let mut buf = [0; 1024];
let mut written : u64 = 0;
while written < len_max {
let len = match r.read(&mut buf) {
Ok(0) => return Ok(written),
Ok(len) => len,
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
|
}
else {
let to_write : usize = len_max as usize - written as usize;
let to_write = if to_write > len {len} else {to_write}; //required?
try!(w.write_all(&buf[..to_write]));
written += to_write as u64;
}
}
Ok(written)
}
|
};
if (written+len as u64) < len_max {
try!(w.write_all(&buf[..len]));
written += len as u64;
|
random_line_split
|
util.rs
|
use std::io::{self, Result, Read, Write, ErrorKind};
//copy with length limiting
pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W, len_max: u64) -> io::Result<u64>
|
written += to_write as u64;
}
}
Ok(written)
}
|
{
let mut buf = [0; 1024];
let mut written : u64 = 0;
while written < len_max {
let len = match r.read(&mut buf) {
Ok(0) => return Ok(written),
Ok(len) => len,
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
if (written+len as u64) < len_max {
try!(w.write_all(&buf[..len]));
written += len as u64;
}
else {
let to_write : usize = len_max as usize - written as usize;
let to_write = if to_write > len {len} else {to_write}; //required?
try!(w.write_all(&buf[..to_write]));
|
identifier_body
|
util.rs
|
use std::io::{self, Result, Read, Write, ErrorKind};
//copy with length limiting
pub fn
|
<R: Read, W: Write>(r: &mut R, w: &mut W, len_max: u64) -> io::Result<u64> {
let mut buf = [0; 1024];
let mut written : u64 = 0;
while written < len_max {
let len = match r.read(&mut buf) {
Ok(0) => return Ok(written),
Ok(len) => len,
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e),
};
if (written+len as u64) < len_max {
try!(w.write_all(&buf[..len]));
written += len as u64;
}
else {
let to_write : usize = len_max as usize - written as usize;
let to_write = if to_write > len {len} else {to_write}; //required?
try!(w.write_all(&buf[..to_write]));
written += to_write as u64;
}
}
Ok(written)
}
|
copy
|
identifier_name
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::trace::Untraceable;
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::atom::Atom;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLImageElement {
pub htmlelement: HTMLElement,
image: Untraceable<RefCell<Option<Url>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.deref().window.root();
let image_cache = &window.image_cache_task;
match value {
None => {
*self.image.deref().borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.deref().borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, document),
image: Untraceable::new(RefCell::new(None)),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
fn SetAlt(self, alt: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("alt", alt)
}
make_getter!(Src)
fn SetSrc(self, src: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_url_attribute("src", src)
}
make_getter!(UseMap)
fn SetUseMap(self, use_map: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("usemap", use_map)
}
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("ismap", is_map.to_string())
}
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn SetWidth(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("width", width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("height", height)
}
make_getter!(Name)
fn SetName(self, name: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("name", name)
}
make_getter!(Align)
fn SetAlign(self, align: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("align", align)
}
make_uint_getter!(Hspace)
fn SetHspace(self, hspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("hspace", hspace)
}
make_uint_getter!(Vspace)
fn SetVspace(self, vspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("vspace", vspace)
}
make_getter!(LongDesc)
fn SetLongDesc(self, longdesc: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("longdesc", longdesc)
}
make_getter!(Border)
fn SetBorder(self, border: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("border", border)
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice()
|
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
{
let window = window_from_node(*self).root();
let url = window.deref().get_url();
self.update_image(Some((value, &url)));
}
|
conditional_block
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::trace::Untraceable;
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::atom::Atom;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLImageElement {
pub htmlelement: HTMLElement,
image: Untraceable<RefCell<Option<Url>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.deref().window.root();
let image_cache = &window.image_cache_task;
match value {
None => {
*self.image.deref().borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.deref().borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, document),
image: Untraceable::new(RefCell::new(None)),
}
}
|
let element = HTMLImageElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
fn SetAlt(self, alt: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("alt", alt)
}
make_getter!(Src)
fn SetSrc(self, src: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_url_attribute("src", src)
}
make_getter!(UseMap)
fn SetUseMap(self, use_map: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("usemap", use_map)
}
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("ismap", is_map.to_string())
}
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn SetWidth(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("width", width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("height", height)
}
make_getter!(Name)
fn SetName(self, name: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("name", name)
}
make_getter!(Align)
fn SetAlign(self, align: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("align", align)
}
make_uint_getter!(Hspace)
fn SetHspace(self, hspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("hspace", hspace)
}
make_uint_getter!(Vspace)
fn SetVspace(self, vspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("vspace", vspace)
}
make_getter!(LongDesc)
fn SetLongDesc(self, longdesc: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("longdesc", longdesc)
}
make_getter!(Border)
fn SetBorder(self, border: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("border", border)
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
let window = window_from_node(*self).root();
let url = window.deref().get_url();
self.update_image(Some((value, &url)));
}
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
|
random_line_split
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::trace::Untraceable;
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::atom::Atom;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLImageElement {
pub htmlelement: HTMLElement,
image: Untraceable<RefCell<Option<Url>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.deref().window.root();
let image_cache = &window.image_cache_task;
match value {
None => {
*self.image.deref().borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.deref().borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, document),
image: Untraceable::new(RefCell::new(None)),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
fn SetAlt(self, alt: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("alt", alt)
}
make_getter!(Src)
fn SetSrc(self, src: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_url_attribute("src", src)
}
make_getter!(UseMap)
fn SetUseMap(self, use_map: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("usemap", use_map)
}
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("ismap", is_map.to_string())
}
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn SetWidth(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("width", width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("height", height)
}
make_getter!(Name)
fn SetName(self, name: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("name", name)
}
make_getter!(Align)
fn SetAlign(self, align: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("align", align)
}
make_uint_getter!(Hspace)
fn SetHspace(self, hspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("hspace", hspace)
}
make_uint_getter!(Vspace)
fn SetVspace(self, vspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("vspace", vspace)
}
make_getter!(LongDesc)
fn SetLongDesc(self, longdesc: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("longdesc", longdesc)
}
make_getter!(Border)
fn SetBorder(self, border: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("border", border)
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
let window = window_from_node(*self).root();
let url = window.deref().get_url();
self.update_image(Some((value, &url)));
}
}
fn before_remove_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector
|
}
|
{
self.htmlelement.reflector()
}
|
identifier_body
|
htmlimageelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::trace::Untraceable;
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{Element, HTMLImageElementTypeId};
use dom::element::AttributeHandlers;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId, NodeHelpers, window_from_node};
use dom::virtualmethods::VirtualMethods;
use servo_net::image_cache_task;
use servo_util::atom::Atom;
use servo_util::geometry::to_px;
use servo_util::str::DOMString;
use url::{Url, UrlParser};
use std::cell::RefCell;
#[deriving(Encodable)]
#[must_root]
pub struct HTMLImageElement {
pub htmlelement: HTMLElement,
image: Untraceable<RefCell<Option<Url>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLImageElementTypeId))
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root();
let window = document.deref().window.root();
let image_cache = &window.image_cache_task;
match value {
None => {
*self.image.deref().borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(src.as_slice());
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.image.deref().borrow_mut() = Some(img_url.clone());
// inform the image cache to load this, but don't store a
// handle.
//
// TODO (Issue #84): don't prefetch if we are within a
// <noscript> tag.
image_cache.send(image_cache_task::Prefetch(img_url));
}
}
}
}
impl HTMLImageElement {
pub fn new_inherited(localName: DOMString, document: JSRef<Document>) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLImageElementTypeId, localName, document),
image: Untraceable::new(RefCell::new(None)),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
}
pub trait LayoutHTMLImageElementHelpers {
unsafe fn image(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> {
unsafe fn image(&self) -> Option<Url> {
(*self.unsafe_get()).image.borrow().clone()
}
}
impl<'a> HTMLImageElementMethods for JSRef<'a, HTMLImageElement> {
make_getter!(Alt)
fn SetAlt(self, alt: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("alt", alt)
}
make_getter!(Src)
fn SetSrc(self, src: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_url_attribute("src", src)
}
make_getter!(UseMap)
fn SetUseMap(self, use_map: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("usemap", use_map)
}
make_bool_getter!(IsMap)
fn SetIsMap(self, is_map: bool) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("ismap", is_map.to_string())
}
fn Width(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.width) as u32
}
fn SetWidth(self, width: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("width", width)
}
fn Height(self) -> u32 {
let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
to_px(rect.size.height) as u32
}
fn SetHeight(self, height: u32) {
let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.set_uint_attribute("height", height)
}
make_getter!(Name)
fn SetName(self, name: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("name", name)
}
make_getter!(Align)
fn SetAlign(self, align: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("align", align)
}
make_uint_getter!(Hspace)
fn SetHspace(self, hspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("hspace", hspace)
}
make_uint_getter!(Vspace)
fn SetVspace(self, vspace: u32) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_uint_attribute("vspace", vspace)
}
make_getter!(LongDesc)
fn SetLongDesc(self, longdesc: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("longdesc", longdesc)
}
make_getter!(Border)
fn SetBorder(self, border: DOMString) {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.set_string_attribute("border", border)
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.after_set_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
let window = window_from_node(*self).root();
let url = window.deref().get_url();
self.update_image(Some((value, &url)));
}
}
fn
|
(&self, name: &Atom, value: DOMString) {
match self.super_type() {
Some(ref s) => s.before_remove_attr(name, value.clone()),
_ => (),
}
if "src" == name.as_slice() {
self.update_image(None);
}
}
fn parse_plain_attribute(&self, name: &str, value: DOMString) -> AttrValue {
match name {
"width" | "height" | "hspace" | "vspace" => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl Reflectable for HTMLImageElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
before_remove_attr
|
identifier_name
|
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
extern crate rand;
use super::{inflate_bytes, deflate_bytes};
use self::rand::Rng;
#[test]
|
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
words.push(r.gen_vec::<u8>(range));
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
|
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
|
random_line_split
|
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>>
|
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
extern crate rand;
use super::{inflate_bytes, deflate_bytes};
use self::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
words.push(r.gen_vec::<u8>(range));
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
|
{
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
|
identifier_body
|
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn
|
(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
extern crate rand;
use super::{inflate_bytes, deflate_bytes};
use self::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
words.push(r.gen_vec::<u8>(range));
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
|
deflate_bytes
|
identifier_name
|
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://static.rust-lang.org/doc/master")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null()
|
else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
extern crate rand;
use super::{inflate_bytes, deflate_bytes};
use self::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
words.push(r.gen_vec::<u8>(range));
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
|
{
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
}
|
conditional_block
|
string-self-append.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main() {
// Make sure we properly handle repeated self-appends.
let mut a: StrBuf = "A".to_strbuf();
|
while i > 0 {
println!("{}", a.len());
assert_eq!(a.len(), expected_len);
a = format_strbuf!("{}{}", a, a);
i -= 1;
expected_len *= 2u;
}
}
|
let mut i = 20;
let mut expected_len = 1u;
|
random_line_split
|
string-self-append.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn
|
() {
// Make sure we properly handle repeated self-appends.
let mut a: StrBuf = "A".to_strbuf();
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
println!("{}", a.len());
assert_eq!(a.len(), expected_len);
a = format_strbuf!("{}{}", a, a);
i -= 1;
expected_len *= 2u;
}
}
|
main
|
identifier_name
|
string-self-append.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub fn main()
|
{
// Make sure we properly handle repeated self-appends.
let mut a: StrBuf = "A".to_strbuf();
let mut i = 20;
let mut expected_len = 1u;
while i > 0 {
println!("{}", a.len());
assert_eq!(a.len(), expected_len);
a = format_strbuf!("{}{}", a, a);
i -= 1;
expected_len *= 2u;
}
}
|
identifier_body
|
|
controlflow.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use lib::llvm::*;
use middle::lang_items::{FailFnLangItem, FailBoundsCheckFnLangItem};
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::debuginfo;
use middle::trans::expr;
use middle::ty;
use util::common::indenter;
use util::ppaux;
use middle::trans::type_::Type;
use syntax::ast;
use syntax::ast::Name;
use syntax::ast_util;
use syntax::codemap::Span;
use syntax::visit::Visitor;
pub fn
|
<'a>(bcx: &'a Block<'a>, b: &ast::Block, dest: expr::Dest)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_block");
let mut bcx = bcx;
for s in b.stmts.iter() {
bcx = trans_stmt(bcx, *s);
}
match b.expr {
Some(e) => {
bcx = expr::trans_into(bcx, e, dest);
}
None => {
assert!(dest == expr::Ignore || bcx.unreachable.get());
}
}
return bcx;
}
pub fn trans_if<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
thn: ast::P<ast::Block>,
els: Option<@ast::Expr>,
dest: expr::Dest)
-> &'a Block<'a> {
debug!("trans_if(bcx={}, cond={}, thn={:?}, dest={})",
bcx.to_str(), bcx.expr_to_str(cond), thn.id,
dest.to_str(bcx.ccx()));
let _indenter = indenter();
let _icx = push_ctxt("trans_if");
let Result {bcx, val: cond_val} =
expr::trans_to_datum(bcx, cond).to_result();
let cond_val = bool_to_i1(bcx, cond_val);
// Drop branches that are known to be impossible
if is_const(cond_val) &&!is_undef(cond_val) {
if const_to_uint(cond_val) == 1 {
match els {
Some(elexpr) => {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
trans.visit_expr(elexpr, ());
}
None => {}
}
// if true {.. } [else {.. }]
return with_scope(bcx, thn.info(), "if_true_then", |bcx| {
let bcx_out = trans_block(bcx, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
} else {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
trans.visit_block(thn, ());
match els {
// if false {.. } else {.. }
Some(elexpr) => {
return with_scope(bcx,
elexpr.info(),
"if_false_then",
|bcx| {
let bcx_out = trans_if_else(bcx, elexpr, dest, false);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
}
// if false {.. }
None => return bcx,
}
}
}
let then_bcx_in = scope_block(bcx, thn.info(), "then");
let then_bcx_out = trans_block(then_bcx_in, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
let then_bcx_out = trans_block_cleanups(then_bcx_out,
block_cleanups(then_bcx_in));
// Calling trans_block directly instead of trans_expr
// because trans_expr will create another scope block
// context for the block, but we've already got the
// 'else' context
let (else_bcx_in, next_bcx) = match els {
Some(elexpr) => {
let else_bcx_in = scope_block(bcx, elexpr.info(), "else");
let else_bcx_out = trans_if_else(else_bcx_in, elexpr, dest, true);
(else_bcx_in, join_blocks(bcx, [then_bcx_out, else_bcx_out]))
}
_ => {
let next_bcx = sub_block(bcx, "next");
Br(then_bcx_out, next_bcx.llbb);
(next_bcx, next_bcx)
}
};
debug!("then_bcx_in={}, else_bcx_in={}",
then_bcx_in.to_str(), else_bcx_in.to_str());
// Clear the source location because it is still set to whatever has been translated
// right before.
debuginfo::clear_source_location(else_bcx_in.fcx);
CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb);
return next_bcx;
// trans `else [ if {.. }... | {.. } ]`
fn trans_if_else<'a>(
else_bcx_in: &'a Block<'a>,
elexpr: @ast::Expr,
dest: expr::Dest,
cleanup: bool)
-> &'a Block<'a> {
let else_bcx_out = match elexpr.node {
ast::ExprIf(_, _, _) => {
let elseif_blk = ast_util::block_from_expr(elexpr);
trans_block(else_bcx_in, elseif_blk, dest)
}
ast::ExprBlock(blk) => {
trans_block(else_bcx_in, blk, dest)
}
// would be nice to have a constraint on ifs
_ => else_bcx_in.tcx().sess.bug("strange alternative in if")
};
if cleanup {
debuginfo::clear_source_location(else_bcx_in.fcx);
trans_block_cleanups(else_bcx_out, block_cleanups(else_bcx_in))
} else {
else_bcx_out
}
}
}
pub fn join_blocks<'a>(
parent_bcx: &'a Block<'a>,
in_cxs: &[&'a Block<'a>])
-> &'a Block<'a> {
let out = sub_block(parent_bcx, "join");
let mut reachable = false;
for bcx in in_cxs.iter() {
if!bcx.unreachable.get() {
Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
Unreachable(out);
}
return out;
}
pub fn trans_while<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
body: &ast::Block)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_while");
let next_bcx = sub_block(bcx, "while next");
// bcx
// |
// loop_bcx
// |
// cond_bcx_in <--------+
// | |
// cond_bcx_out |
// | | |
// | body_bcx_in |
// +------+ | |
// | body_bcx_out --+
// next_bcx
let loop_bcx = loop_scope_block(bcx, next_bcx, None, "`while`",
body.info());
let cond_bcx_in = scope_block(loop_bcx, cond.info(), "while loop cond");
let body_bcx_in = scope_block(loop_bcx, body.info(), "while loop body");
Br(bcx, loop_bcx.llbb);
Br(loop_bcx, cond_bcx_in.llbb);
// compile the condition
let Result {bcx: cond_bcx_out, val: cond_val} =
expr::trans_to_datum(cond_bcx_in, cond).to_result();
let cond_val = bool_to_i1(cond_bcx_out, cond_val);
let cond_bcx_out =
trans_block_cleanups(cond_bcx_out, block_cleanups(cond_bcx_in));
CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, next_bcx.llbb);
// loop body:
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, cond_bcx_in.llbb);
return next_bcx;
}
pub fn trans_loop<'a>(
bcx: &'a Block<'a>,
body: &ast::Block,
opt_label: Option<Name>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_loop");
let next_bcx = sub_block(bcx, "next");
let body_bcx_in = loop_scope_block(bcx, next_bcx, opt_label, "`loop`",
body.info());
Br(bcx, body_bcx_in.llbb);
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, body_bcx_in.llbb);
return next_bcx;
}
pub fn trans_break_cont<'a>(
bcx: &'a Block<'a>,
opt_label: Option<Name>,
to_end: bool)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_break_cont");
// Locate closest loop block, outputting cleanup as we go.
let mut unwind = bcx;
let mut cur_scope = unwind.scope.get();
let mut target;
loop {
cur_scope = match cur_scope {
Some(&ScopeInfo {
loop_break: Some(brk),
loop_label: l,
parent,
..
}) => {
// If we're looking for a labeled loop, check the label...
target = if to_end {
brk
} else {
unwind
};
match opt_label {
Some(desired) => match l {
Some(actual) if actual == desired => break,
// If it doesn't match the one we want,
// don't break
_ => parent,
},
None => break,
}
}
Some(inf) => inf.parent,
None => {
unwind = match unwind.parent {
Some(bcx) => bcx,
// This is a return from a loop body block
None => {
Store(bcx,
C_bool(!to_end),
bcx.fcx.llretptr.get().unwrap());
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
};
unwind.scope.get()
}
}
}
cleanup_and_Br(bcx, unwind, target.llbb);
Unreachable(bcx);
return bcx;
}
pub fn trans_break<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, true);
}
pub fn trans_cont<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, false);
}
pub fn trans_ret<'a>(bcx: &'a Block<'a>, e: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_ret");
let mut bcx = bcx;
let dest = match bcx.fcx.llretptr.get() {
None => expr::Ignore,
Some(retptr) => expr::SaveIn(retptr),
};
match e {
Some(x) => {
bcx = expr::trans_into(bcx, x, dest);
}
_ => ()
}
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_expr<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_expr: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_expr");
let mut bcx = bcx;
match fail_expr {
Some(arg_expr) => {
let ccx = bcx.ccx();
let tcx = ccx.tcx;
let arg_datum = unpack_datum!(
bcx, expr::trans_to_datum(bcx, arg_expr));
if ty::type_is_str(arg_datum.ty) {
let (lldata, _) = arg_datum.get_vec_base_and_len_no_root(bcx);
return trans_fail_value(bcx, sp_opt, lldata);
} else if bcx.unreachable.get() || ty::type_is_bot(arg_datum.ty) {
return bcx;
} else {
bcx.sess().span_bug(
arg_expr.span, ~"fail called with unsupported type " +
ppaux::ty_to_str(tcx, arg_datum.ty));
}
}
_ => trans_fail(bcx, sp_opt, @"explicit failure")
}
}
pub fn trans_fail<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_str: @str)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail");
let V_fail_str = C_cstr(bcx.ccx(), fail_str);
return trans_fail_value(bcx, sp_opt, V_fail_str);
}
fn trans_fail_value<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
V_fail_str: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_value");
let ccx = bcx.ccx();
let (V_filename, V_line) = match sp_opt {
Some(sp) => {
let sess = bcx.sess();
let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
(C_cstr(bcx.ccx(), loc.file.name),
loc.line as int)
}
None => {
(C_cstr(bcx.ccx(), @"<runtime>"), 0)
}
};
let V_str = PointerCast(bcx, V_fail_str, Type::i8p());
let V_filename = PointerCast(bcx, V_filename, Type::i8p());
let args = ~[V_str, V_filename, C_int(ccx, V_line)];
let did = langcall(bcx, sp_opt, "", FailFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_bounds_check<'a>(
bcx: &'a Block<'a>,
sp: Span,
index: ValueRef,
len: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_bounds_check");
let (filename, line) = filename_and_line_num_from_span(bcx, sp);
let args = ~[filename, line, index, len];
let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
|
trans_block
|
identifier_name
|
controlflow.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use lib::llvm::*;
use middle::lang_items::{FailFnLangItem, FailBoundsCheckFnLangItem};
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::debuginfo;
use middle::trans::expr;
use middle::ty;
use util::common::indenter;
use util::ppaux;
use middle::trans::type_::Type;
use syntax::ast;
use syntax::ast::Name;
use syntax::ast_util;
use syntax::codemap::Span;
use syntax::visit::Visitor;
pub fn trans_block<'a>(bcx: &'a Block<'a>, b: &ast::Block, dest: expr::Dest)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_block");
let mut bcx = bcx;
for s in b.stmts.iter() {
bcx = trans_stmt(bcx, *s);
}
match b.expr {
Some(e) => {
bcx = expr::trans_into(bcx, e, dest);
}
None => {
assert!(dest == expr::Ignore || bcx.unreachable.get());
}
}
return bcx;
}
pub fn trans_if<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
thn: ast::P<ast::Block>,
els: Option<@ast::Expr>,
dest: expr::Dest)
-> &'a Block<'a> {
debug!("trans_if(bcx={}, cond={}, thn={:?}, dest={})",
bcx.to_str(), bcx.expr_to_str(cond), thn.id,
dest.to_str(bcx.ccx()));
let _indenter = indenter();
let _icx = push_ctxt("trans_if");
let Result {bcx, val: cond_val} =
expr::trans_to_datum(bcx, cond).to_result();
let cond_val = bool_to_i1(bcx, cond_val);
// Drop branches that are known to be impossible
if is_const(cond_val) &&!is_undef(cond_val) {
if const_to_uint(cond_val) == 1 {
match els {
Some(elexpr) => {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
trans.visit_expr(elexpr, ());
}
None => {}
}
// if true {.. } [else {.. }]
return with_scope(bcx, thn.info(), "if_true_then", |bcx| {
let bcx_out = trans_block(bcx, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
} else {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
trans.visit_block(thn, ());
match els {
// if false {.. } else {.. }
Some(elexpr) => {
return with_scope(bcx,
elexpr.info(),
"if_false_then",
|bcx| {
let bcx_out = trans_if_else(bcx, elexpr, dest, false);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
}
// if false {.. }
None => return bcx,
}
}
}
let then_bcx_in = scope_block(bcx, thn.info(), "then");
let then_bcx_out = trans_block(then_bcx_in, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
let then_bcx_out = trans_block_cleanups(then_bcx_out,
block_cleanups(then_bcx_in));
// Calling trans_block directly instead of trans_expr
// because trans_expr will create another scope block
// context for the block, but we've already got the
// 'else' context
let (else_bcx_in, next_bcx) = match els {
Some(elexpr) => {
let else_bcx_in = scope_block(bcx, elexpr.info(), "else");
let else_bcx_out = trans_if_else(else_bcx_in, elexpr, dest, true);
(else_bcx_in, join_blocks(bcx, [then_bcx_out, else_bcx_out]))
}
_ => {
let next_bcx = sub_block(bcx, "next");
Br(then_bcx_out, next_bcx.llbb);
(next_bcx, next_bcx)
}
};
debug!("then_bcx_in={}, else_bcx_in={}",
then_bcx_in.to_str(), else_bcx_in.to_str());
// Clear the source location because it is still set to whatever has been translated
// right before.
debuginfo::clear_source_location(else_bcx_in.fcx);
CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb);
return next_bcx;
// trans `else [ if {.. }... | {.. } ]`
fn trans_if_else<'a>(
else_bcx_in: &'a Block<'a>,
elexpr: @ast::Expr,
dest: expr::Dest,
cleanup: bool)
-> &'a Block<'a> {
let else_bcx_out = match elexpr.node {
ast::ExprIf(_, _, _) => {
let elseif_blk = ast_util::block_from_expr(elexpr);
trans_block(else_bcx_in, elseif_blk, dest)
}
ast::ExprBlock(blk) => {
trans_block(else_bcx_in, blk, dest)
}
// would be nice to have a constraint on ifs
_ => else_bcx_in.tcx().sess.bug("strange alternative in if")
};
if cleanup {
debuginfo::clear_source_location(else_bcx_in.fcx);
trans_block_cleanups(else_bcx_out, block_cleanups(else_bcx_in))
} else {
else_bcx_out
}
}
}
pub fn join_blocks<'a>(
parent_bcx: &'a Block<'a>,
in_cxs: &[&'a Block<'a>])
-> &'a Block<'a> {
let out = sub_block(parent_bcx, "join");
let mut reachable = false;
for bcx in in_cxs.iter() {
if!bcx.unreachable.get() {
Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
Unreachable(out);
}
return out;
}
pub fn trans_while<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
body: &ast::Block)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_while");
let next_bcx = sub_block(bcx, "while next");
// bcx
// |
// loop_bcx
// |
// cond_bcx_in <--------+
// | |
// cond_bcx_out |
// | | |
// | body_bcx_in |
// +------+ | |
// | body_bcx_out --+
// next_bcx
let loop_bcx = loop_scope_block(bcx, next_bcx, None, "`while`",
body.info());
let cond_bcx_in = scope_block(loop_bcx, cond.info(), "while loop cond");
let body_bcx_in = scope_block(loop_bcx, body.info(), "while loop body");
Br(bcx, loop_bcx.llbb);
Br(loop_bcx, cond_bcx_in.llbb);
// compile the condition
let Result {bcx: cond_bcx_out, val: cond_val} =
expr::trans_to_datum(cond_bcx_in, cond).to_result();
let cond_val = bool_to_i1(cond_bcx_out, cond_val);
let cond_bcx_out =
trans_block_cleanups(cond_bcx_out, block_cleanups(cond_bcx_in));
CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, next_bcx.llbb);
// loop body:
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, cond_bcx_in.llbb);
return next_bcx;
}
pub fn trans_loop<'a>(
bcx: &'a Block<'a>,
body: &ast::Block,
opt_label: Option<Name>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_loop");
let next_bcx = sub_block(bcx, "next");
let body_bcx_in = loop_scope_block(bcx, next_bcx, opt_label, "`loop`",
body.info());
Br(bcx, body_bcx_in.llbb);
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, body_bcx_in.llbb);
return next_bcx;
}
pub fn trans_break_cont<'a>(
bcx: &'a Block<'a>,
opt_label: Option<Name>,
to_end: bool)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_break_cont");
// Locate closest loop block, outputting cleanup as we go.
let mut unwind = bcx;
let mut cur_scope = unwind.scope.get();
let mut target;
loop {
cur_scope = match cur_scope {
Some(&ScopeInfo {
loop_break: Some(brk),
loop_label: l,
parent,
..
}) =>
|
Some(inf) => inf.parent,
None => {
unwind = match unwind.parent {
Some(bcx) => bcx,
// This is a return from a loop body block
None => {
Store(bcx,
C_bool(!to_end),
bcx.fcx.llretptr.get().unwrap());
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
};
unwind.scope.get()
}
}
}
cleanup_and_Br(bcx, unwind, target.llbb);
Unreachable(bcx);
return bcx;
}
pub fn trans_break<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, true);
}
pub fn trans_cont<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, false);
}
pub fn trans_ret<'a>(bcx: &'a Block<'a>, e: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_ret");
let mut bcx = bcx;
let dest = match bcx.fcx.llretptr.get() {
None => expr::Ignore,
Some(retptr) => expr::SaveIn(retptr),
};
match e {
Some(x) => {
bcx = expr::trans_into(bcx, x, dest);
}
_ => ()
}
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_expr<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_expr: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_expr");
let mut bcx = bcx;
match fail_expr {
Some(arg_expr) => {
let ccx = bcx.ccx();
let tcx = ccx.tcx;
let arg_datum = unpack_datum!(
bcx, expr::trans_to_datum(bcx, arg_expr));
if ty::type_is_str(arg_datum.ty) {
let (lldata, _) = arg_datum.get_vec_base_and_len_no_root(bcx);
return trans_fail_value(bcx, sp_opt, lldata);
} else if bcx.unreachable.get() || ty::type_is_bot(arg_datum.ty) {
return bcx;
} else {
bcx.sess().span_bug(
arg_expr.span, ~"fail called with unsupported type " +
ppaux::ty_to_str(tcx, arg_datum.ty));
}
}
_ => trans_fail(bcx, sp_opt, @"explicit failure")
}
}
pub fn trans_fail<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_str: @str)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail");
let V_fail_str = C_cstr(bcx.ccx(), fail_str);
return trans_fail_value(bcx, sp_opt, V_fail_str);
}
fn trans_fail_value<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
V_fail_str: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_value");
let ccx = bcx.ccx();
let (V_filename, V_line) = match sp_opt {
Some(sp) => {
let sess = bcx.sess();
let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
(C_cstr(bcx.ccx(), loc.file.name),
loc.line as int)
}
None => {
(C_cstr(bcx.ccx(), @"<runtime>"), 0)
}
};
let V_str = PointerCast(bcx, V_fail_str, Type::i8p());
let V_filename = PointerCast(bcx, V_filename, Type::i8p());
let args = ~[V_str, V_filename, C_int(ccx, V_line)];
let did = langcall(bcx, sp_opt, "", FailFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_bounds_check<'a>(
bcx: &'a Block<'a>,
sp: Span,
index: ValueRef,
len: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_bounds_check");
let (filename, line) = filename_and_line_num_from_span(bcx, sp);
let args = ~[filename, line, index, len];
let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
|
{
// If we're looking for a labeled loop, check the label...
target = if to_end {
brk
} else {
unwind
};
match opt_label {
Some(desired) => match l {
Some(actual) if actual == desired => break,
// If it doesn't match the one we want,
// don't break
_ => parent,
},
None => break,
}
}
|
conditional_block
|
controlflow.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use lib::llvm::*;
use middle::lang_items::{FailFnLangItem, FailBoundsCheckFnLangItem};
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::debuginfo;
use middle::trans::expr;
use middle::ty;
use util::common::indenter;
use util::ppaux;
use middle::trans::type_::Type;
use syntax::ast;
use syntax::ast::Name;
use syntax::ast_util;
use syntax::codemap::Span;
use syntax::visit::Visitor;
pub fn trans_block<'a>(bcx: &'a Block<'a>, b: &ast::Block, dest: expr::Dest)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_block");
let mut bcx = bcx;
for s in b.stmts.iter() {
bcx = trans_stmt(bcx, *s);
}
match b.expr {
Some(e) => {
bcx = expr::trans_into(bcx, e, dest);
}
None => {
assert!(dest == expr::Ignore || bcx.unreachable.get());
}
}
return bcx;
}
pub fn trans_if<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
thn: ast::P<ast::Block>,
els: Option<@ast::Expr>,
dest: expr::Dest)
-> &'a Block<'a> {
debug!("trans_if(bcx={}, cond={}, thn={:?}, dest={})",
bcx.to_str(), bcx.expr_to_str(cond), thn.id,
dest.to_str(bcx.ccx()));
let _indenter = indenter();
let _icx = push_ctxt("trans_if");
let Result {bcx, val: cond_val} =
expr::trans_to_datum(bcx, cond).to_result();
let cond_val = bool_to_i1(bcx, cond_val);
// Drop branches that are known to be impossible
if is_const(cond_val) &&!is_undef(cond_val) {
if const_to_uint(cond_val) == 1 {
match els {
Some(elexpr) => {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
trans.visit_expr(elexpr, ());
}
None => {}
}
// if true {.. } [else {.. }]
return with_scope(bcx, thn.info(), "if_true_then", |bcx| {
let bcx_out = trans_block(bcx, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
} else {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
trans.visit_block(thn, ());
match els {
// if false {.. } else {.. }
Some(elexpr) => {
return with_scope(bcx,
elexpr.info(),
"if_false_then",
|bcx| {
let bcx_out = trans_if_else(bcx, elexpr, dest, false);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
}
// if false {.. }
None => return bcx,
}
}
}
let then_bcx_in = scope_block(bcx, thn.info(), "then");
let then_bcx_out = trans_block(then_bcx_in, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
let then_bcx_out = trans_block_cleanups(then_bcx_out,
block_cleanups(then_bcx_in));
// Calling trans_block directly instead of trans_expr
// because trans_expr will create another scope block
// context for the block, but we've already got the
// 'else' context
let (else_bcx_in, next_bcx) = match els {
Some(elexpr) => {
let else_bcx_in = scope_block(bcx, elexpr.info(), "else");
let else_bcx_out = trans_if_else(else_bcx_in, elexpr, dest, true);
(else_bcx_in, join_blocks(bcx, [then_bcx_out, else_bcx_out]))
}
_ => {
let next_bcx = sub_block(bcx, "next");
Br(then_bcx_out, next_bcx.llbb);
(next_bcx, next_bcx)
}
};
debug!("then_bcx_in={}, else_bcx_in={}",
then_bcx_in.to_str(), else_bcx_in.to_str());
// Clear the source location because it is still set to whatever has been translated
// right before.
debuginfo::clear_source_location(else_bcx_in.fcx);
CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb);
return next_bcx;
// trans `else [ if {.. }... | {.. } ]`
fn trans_if_else<'a>(
else_bcx_in: &'a Block<'a>,
elexpr: @ast::Expr,
dest: expr::Dest,
cleanup: bool)
-> &'a Block<'a> {
let else_bcx_out = match elexpr.node {
ast::ExprIf(_, _, _) => {
let elseif_blk = ast_util::block_from_expr(elexpr);
trans_block(else_bcx_in, elseif_blk, dest)
}
ast::ExprBlock(blk) => {
trans_block(else_bcx_in, blk, dest)
}
// would be nice to have a constraint on ifs
_ => else_bcx_in.tcx().sess.bug("strange alternative in if")
};
if cleanup {
debuginfo::clear_source_location(else_bcx_in.fcx);
trans_block_cleanups(else_bcx_out, block_cleanups(else_bcx_in))
} else {
else_bcx_out
}
}
}
pub fn join_blocks<'a>(
parent_bcx: &'a Block<'a>,
in_cxs: &[&'a Block<'a>])
-> &'a Block<'a> {
let out = sub_block(parent_bcx, "join");
let mut reachable = false;
for bcx in in_cxs.iter() {
if!bcx.unreachable.get() {
Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
Unreachable(out);
}
return out;
}
pub fn trans_while<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
body: &ast::Block)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_while");
let next_bcx = sub_block(bcx, "while next");
// bcx
// |
// loop_bcx
// |
// cond_bcx_in <--------+
// | |
// cond_bcx_out |
// | | |
// | body_bcx_in |
// +------+ | |
// | body_bcx_out --+
// next_bcx
let loop_bcx = loop_scope_block(bcx, next_bcx, None, "`while`",
body.info());
let cond_bcx_in = scope_block(loop_bcx, cond.info(), "while loop cond");
let body_bcx_in = scope_block(loop_bcx, body.info(), "while loop body");
Br(bcx, loop_bcx.llbb);
Br(loop_bcx, cond_bcx_in.llbb);
// compile the condition
let Result {bcx: cond_bcx_out, val: cond_val} =
expr::trans_to_datum(cond_bcx_in, cond).to_result();
let cond_val = bool_to_i1(cond_bcx_out, cond_val);
let cond_bcx_out =
trans_block_cleanups(cond_bcx_out, block_cleanups(cond_bcx_in));
CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, next_bcx.llbb);
// loop body:
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, cond_bcx_in.llbb);
return next_bcx;
}
pub fn trans_loop<'a>(
bcx: &'a Block<'a>,
body: &ast::Block,
opt_label: Option<Name>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_loop");
let next_bcx = sub_block(bcx, "next");
let body_bcx_in = loop_scope_block(bcx, next_bcx, opt_label, "`loop`",
body.info());
Br(bcx, body_bcx_in.llbb);
|
pub fn trans_break_cont<'a>(
bcx: &'a Block<'a>,
opt_label: Option<Name>,
to_end: bool)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_break_cont");
// Locate closest loop block, outputting cleanup as we go.
let mut unwind = bcx;
let mut cur_scope = unwind.scope.get();
let mut target;
loop {
cur_scope = match cur_scope {
Some(&ScopeInfo {
loop_break: Some(brk),
loop_label: l,
parent,
..
}) => {
// If we're looking for a labeled loop, check the label...
target = if to_end {
brk
} else {
unwind
};
match opt_label {
Some(desired) => match l {
Some(actual) if actual == desired => break,
// If it doesn't match the one we want,
// don't break
_ => parent,
},
None => break,
}
}
Some(inf) => inf.parent,
None => {
unwind = match unwind.parent {
Some(bcx) => bcx,
// This is a return from a loop body block
None => {
Store(bcx,
C_bool(!to_end),
bcx.fcx.llretptr.get().unwrap());
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
};
unwind.scope.get()
}
}
}
cleanup_and_Br(bcx, unwind, target.llbb);
Unreachable(bcx);
return bcx;
}
pub fn trans_break<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, true);
}
pub fn trans_cont<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, false);
}
pub fn trans_ret<'a>(bcx: &'a Block<'a>, e: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_ret");
let mut bcx = bcx;
let dest = match bcx.fcx.llretptr.get() {
None => expr::Ignore,
Some(retptr) => expr::SaveIn(retptr),
};
match e {
Some(x) => {
bcx = expr::trans_into(bcx, x, dest);
}
_ => ()
}
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_expr<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_expr: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_expr");
let mut bcx = bcx;
match fail_expr {
Some(arg_expr) => {
let ccx = bcx.ccx();
let tcx = ccx.tcx;
let arg_datum = unpack_datum!(
bcx, expr::trans_to_datum(bcx, arg_expr));
if ty::type_is_str(arg_datum.ty) {
let (lldata, _) = arg_datum.get_vec_base_and_len_no_root(bcx);
return trans_fail_value(bcx, sp_opt, lldata);
} else if bcx.unreachable.get() || ty::type_is_bot(arg_datum.ty) {
return bcx;
} else {
bcx.sess().span_bug(
arg_expr.span, ~"fail called with unsupported type " +
ppaux::ty_to_str(tcx, arg_datum.ty));
}
}
_ => trans_fail(bcx, sp_opt, @"explicit failure")
}
}
pub fn trans_fail<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_str: @str)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail");
let V_fail_str = C_cstr(bcx.ccx(), fail_str);
return trans_fail_value(bcx, sp_opt, V_fail_str);
}
fn trans_fail_value<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
V_fail_str: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_value");
let ccx = bcx.ccx();
let (V_filename, V_line) = match sp_opt {
Some(sp) => {
let sess = bcx.sess();
let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
(C_cstr(bcx.ccx(), loc.file.name),
loc.line as int)
}
None => {
(C_cstr(bcx.ccx(), @"<runtime>"), 0)
}
};
let V_str = PointerCast(bcx, V_fail_str, Type::i8p());
let V_filename = PointerCast(bcx, V_filename, Type::i8p());
let args = ~[V_str, V_filename, C_int(ccx, V_line)];
let did = langcall(bcx, sp_opt, "", FailFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_bounds_check<'a>(
bcx: &'a Block<'a>,
sp: Span,
index: ValueRef,
len: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_bounds_check");
let (filename, line) = filename_and_line_num_from_span(bcx, sp);
let args = ~[filename, line, index, len];
let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
|
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, body_bcx_in.llbb);
return next_bcx;
}
|
random_line_split
|
controlflow.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use lib::llvm::*;
use middle::lang_items::{FailFnLangItem, FailBoundsCheckFnLangItem};
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::callee;
use middle::trans::common::*;
use middle::trans::debuginfo;
use middle::trans::expr;
use middle::ty;
use util::common::indenter;
use util::ppaux;
use middle::trans::type_::Type;
use syntax::ast;
use syntax::ast::Name;
use syntax::ast_util;
use syntax::codemap::Span;
use syntax::visit::Visitor;
pub fn trans_block<'a>(bcx: &'a Block<'a>, b: &ast::Block, dest: expr::Dest)
-> &'a Block<'a>
|
pub fn trans_if<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
thn: ast::P<ast::Block>,
els: Option<@ast::Expr>,
dest: expr::Dest)
-> &'a Block<'a> {
debug!("trans_if(bcx={}, cond={}, thn={:?}, dest={})",
bcx.to_str(), bcx.expr_to_str(cond), thn.id,
dest.to_str(bcx.ccx()));
let _indenter = indenter();
let _icx = push_ctxt("trans_if");
let Result {bcx, val: cond_val} =
expr::trans_to_datum(bcx, cond).to_result();
let cond_val = bool_to_i1(bcx, cond_val);
// Drop branches that are known to be impossible
if is_const(cond_val) &&!is_undef(cond_val) {
if const_to_uint(cond_val) == 1 {
match els {
Some(elexpr) => {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
trans.visit_expr(elexpr, ());
}
None => {}
}
// if true {.. } [else {.. }]
return with_scope(bcx, thn.info(), "if_true_then", |bcx| {
let bcx_out = trans_block(bcx, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
} else {
let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
trans.visit_block(thn, ());
match els {
// if false {.. } else {.. }
Some(elexpr) => {
return with_scope(bcx,
elexpr.info(),
"if_false_then",
|bcx| {
let bcx_out = trans_if_else(bcx, elexpr, dest, false);
debuginfo::clear_source_location(bcx.fcx);
bcx_out
})
}
// if false {.. }
None => return bcx,
}
}
}
let then_bcx_in = scope_block(bcx, thn.info(), "then");
let then_bcx_out = trans_block(then_bcx_in, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
let then_bcx_out = trans_block_cleanups(then_bcx_out,
block_cleanups(then_bcx_in));
// Calling trans_block directly instead of trans_expr
// because trans_expr will create another scope block
// context for the block, but we've already got the
// 'else' context
let (else_bcx_in, next_bcx) = match els {
Some(elexpr) => {
let else_bcx_in = scope_block(bcx, elexpr.info(), "else");
let else_bcx_out = trans_if_else(else_bcx_in, elexpr, dest, true);
(else_bcx_in, join_blocks(bcx, [then_bcx_out, else_bcx_out]))
}
_ => {
let next_bcx = sub_block(bcx, "next");
Br(then_bcx_out, next_bcx.llbb);
(next_bcx, next_bcx)
}
};
debug!("then_bcx_in={}, else_bcx_in={}",
then_bcx_in.to_str(), else_bcx_in.to_str());
// Clear the source location because it is still set to whatever has been translated
// right before.
debuginfo::clear_source_location(else_bcx_in.fcx);
CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb);
return next_bcx;
// trans `else [ if {.. }... | {.. } ]`
fn trans_if_else<'a>(
else_bcx_in: &'a Block<'a>,
elexpr: @ast::Expr,
dest: expr::Dest,
cleanup: bool)
-> &'a Block<'a> {
let else_bcx_out = match elexpr.node {
ast::ExprIf(_, _, _) => {
let elseif_blk = ast_util::block_from_expr(elexpr);
trans_block(else_bcx_in, elseif_blk, dest)
}
ast::ExprBlock(blk) => {
trans_block(else_bcx_in, blk, dest)
}
// would be nice to have a constraint on ifs
_ => else_bcx_in.tcx().sess.bug("strange alternative in if")
};
if cleanup {
debuginfo::clear_source_location(else_bcx_in.fcx);
trans_block_cleanups(else_bcx_out, block_cleanups(else_bcx_in))
} else {
else_bcx_out
}
}
}
pub fn join_blocks<'a>(
parent_bcx: &'a Block<'a>,
in_cxs: &[&'a Block<'a>])
-> &'a Block<'a> {
let out = sub_block(parent_bcx, "join");
let mut reachable = false;
for bcx in in_cxs.iter() {
if!bcx.unreachable.get() {
Br(*bcx, out.llbb);
reachable = true;
}
}
if!reachable {
Unreachable(out);
}
return out;
}
pub fn trans_while<'a>(
bcx: &'a Block<'a>,
cond: &ast::Expr,
body: &ast::Block)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_while");
let next_bcx = sub_block(bcx, "while next");
// bcx
// |
// loop_bcx
// |
// cond_bcx_in <--------+
// | |
// cond_bcx_out |
// | | |
// | body_bcx_in |
// +------+ | |
// | body_bcx_out --+
// next_bcx
let loop_bcx = loop_scope_block(bcx, next_bcx, None, "`while`",
body.info());
let cond_bcx_in = scope_block(loop_bcx, cond.info(), "while loop cond");
let body_bcx_in = scope_block(loop_bcx, body.info(), "while loop body");
Br(bcx, loop_bcx.llbb);
Br(loop_bcx, cond_bcx_in.llbb);
// compile the condition
let Result {bcx: cond_bcx_out, val: cond_val} =
expr::trans_to_datum(cond_bcx_in, cond).to_result();
let cond_val = bool_to_i1(cond_bcx_out, cond_val);
let cond_bcx_out =
trans_block_cleanups(cond_bcx_out, block_cleanups(cond_bcx_in));
CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, next_bcx.llbb);
// loop body:
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, cond_bcx_in.llbb);
return next_bcx;
}
pub fn trans_loop<'a>(
bcx: &'a Block<'a>,
body: &ast::Block,
opt_label: Option<Name>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_loop");
let next_bcx = sub_block(bcx, "next");
let body_bcx_in = loop_scope_block(bcx, next_bcx, opt_label, "`loop`",
body.info());
Br(bcx, body_bcx_in.llbb);
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
cleanup_and_Br(body_bcx_out, body_bcx_in, body_bcx_in.llbb);
return next_bcx;
}
pub fn trans_break_cont<'a>(
bcx: &'a Block<'a>,
opt_label: Option<Name>,
to_end: bool)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_break_cont");
// Locate closest loop block, outputting cleanup as we go.
let mut unwind = bcx;
let mut cur_scope = unwind.scope.get();
let mut target;
loop {
cur_scope = match cur_scope {
Some(&ScopeInfo {
loop_break: Some(brk),
loop_label: l,
parent,
..
}) => {
// If we're looking for a labeled loop, check the label...
target = if to_end {
brk
} else {
unwind
};
match opt_label {
Some(desired) => match l {
Some(actual) if actual == desired => break,
// If it doesn't match the one we want,
// don't break
_ => parent,
},
None => break,
}
}
Some(inf) => inf.parent,
None => {
unwind = match unwind.parent {
Some(bcx) => bcx,
// This is a return from a loop body block
None => {
Store(bcx,
C_bool(!to_end),
bcx.fcx.llretptr.get().unwrap());
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
};
unwind.scope.get()
}
}
}
cleanup_and_Br(bcx, unwind, target.llbb);
Unreachable(bcx);
return bcx;
}
pub fn trans_break<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, true);
}
pub fn trans_cont<'a>(bcx: &'a Block<'a>, label_opt: Option<Name>)
-> &'a Block<'a> {
return trans_break_cont(bcx, label_opt, false);
}
pub fn trans_ret<'a>(bcx: &'a Block<'a>, e: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_ret");
let mut bcx = bcx;
let dest = match bcx.fcx.llretptr.get() {
None => expr::Ignore,
Some(retptr) => expr::SaveIn(retptr),
};
match e {
Some(x) => {
bcx = expr::trans_into(bcx, x, dest);
}
_ => ()
}
cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_expr<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_expr: Option<@ast::Expr>)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_expr");
let mut bcx = bcx;
match fail_expr {
Some(arg_expr) => {
let ccx = bcx.ccx();
let tcx = ccx.tcx;
let arg_datum = unpack_datum!(
bcx, expr::trans_to_datum(bcx, arg_expr));
if ty::type_is_str(arg_datum.ty) {
let (lldata, _) = arg_datum.get_vec_base_and_len_no_root(bcx);
return trans_fail_value(bcx, sp_opt, lldata);
} else if bcx.unreachable.get() || ty::type_is_bot(arg_datum.ty) {
return bcx;
} else {
bcx.sess().span_bug(
arg_expr.span, ~"fail called with unsupported type " +
ppaux::ty_to_str(tcx, arg_datum.ty));
}
}
_ => trans_fail(bcx, sp_opt, @"explicit failure")
}
}
pub fn trans_fail<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
fail_str: @str)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail");
let V_fail_str = C_cstr(bcx.ccx(), fail_str);
return trans_fail_value(bcx, sp_opt, V_fail_str);
}
fn trans_fail_value<'a>(
bcx: &'a Block<'a>,
sp_opt: Option<Span>,
V_fail_str: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_value");
let ccx = bcx.ccx();
let (V_filename, V_line) = match sp_opt {
Some(sp) => {
let sess = bcx.sess();
let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
(C_cstr(bcx.ccx(), loc.file.name),
loc.line as int)
}
None => {
(C_cstr(bcx.ccx(), @"<runtime>"), 0)
}
};
let V_str = PointerCast(bcx, V_fail_str, Type::i8p());
let V_filename = PointerCast(bcx, V_filename, Type::i8p());
let args = ~[V_str, V_filename, C_int(ccx, V_line)];
let did = langcall(bcx, sp_opt, "", FailFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
pub fn trans_fail_bounds_check<'a>(
bcx: &'a Block<'a>,
sp: Span,
index: ValueRef,
len: ValueRef)
-> &'a Block<'a> {
let _icx = push_ctxt("trans_fail_bounds_check");
let (filename, line) = filename_and_line_num_from_span(bcx, sp);
let args = ~[filename, line, index, len];
let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
let bcx = callee::trans_lang_call(bcx, did, args, Some(expr::Ignore)).bcx;
Unreachable(bcx);
return bcx;
}
|
{
let _icx = push_ctxt("trans_block");
let mut bcx = bcx;
for s in b.stmts.iter() {
bcx = trans_stmt(bcx, *s);
}
match b.expr {
Some(e) => {
bcx = expr::trans_into(bcx, e, dest);
}
None => {
assert!(dest == expr::Ignore || bcx.unreachable.get());
}
}
return bcx;
}
|
identifier_body
|
lib.rs
|
// Copyright (C) 2020 Inderjit Gill <[email protected]>
// This file is part of Seni
// Seni is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Seni 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(
feature = "cargo-clippy",
allow(
clippy::many_single_char_names,
clippy::too_many_arguments,
clippy::excessive_precision
)
)]
/*!
The core crate provides the basic functionality of the Seni system
*/
// this is just for documentation
pub mod seni_language;
// mod ast_checker;
mod bitmap;
mod bitmap_cache;
pub mod colour;
mod colour_palettes;
mod compiler;
pub mod constants;
mod context;
mod ease;
pub mod error;
mod focal;
mod gene;
mod geometry;
mod iname;
mod interp;
mod keywords;
mod lexer;
mod mathutil;
mod matrix;
mod native;
mod node;
mod opcodes;
mod packable;
mod parser;
mod path;
mod prng;
mod program;
mod render_list;
mod render_packet;
mod repeat;
mod rgb;
mod trait_list;
mod unparser;
mod uvmapper;
mod vm;
pub use crate::bitmap_cache::{BitmapCache, BitmapInfo};
pub use crate::compiler::{compile_preamble, compile_program, compile_program_with_genotype};
pub use crate::context::Context;
pub use crate::error::{Error, Result};
pub use crate::gene::{next_generation, Genotype};
pub use crate::packable::Packable;
pub use crate::parser::{parse, WordLut};
pub use crate::program::Program;
pub use crate::render_list::{RPCommand, RenderList};
pub use crate::render_packet::{
RenderPacket, RenderPacketGeometry, RenderPacketImage, RenderPacketMask,
};
pub use crate::trait_list::TraitList;
pub use crate::unparser::{simplified_unparse, unparse};
pub use crate::vm::{ProbeSample, VMProfiling, Var, Vm};
pub fn run_program_with_preamble(
vm: &mut Vm,
context: &mut Context,
program: &Program,
) -> Result<Var> {
context.reset_for_piece();
vm.reset();
// setup the env with the global variables in preamble
let preamble = compile_preamble()?;
vm.interpret(context, &preamble)?;
// reset the ip and setup any profiling of the main program
vm.init_for_main_program(&program, VMProfiling::Off)?;
vm.interpret(context, &program)?;
vm.top_stack_value()
}
pub fn program_from_source(s: &str) -> Result<Program> {
let (ast, word_lut) = parse(s)?;
let program = compile_program(&ast, &word_lut)?;
Ok(program)
}
pub fn program_from_source_and_genotype(s: &str, genotype: &mut Genotype) -> Result<Program> {
let (mut ast, word_lut) = parse(s)?;
let program = compile_program_with_genotype(&mut ast, &word_lut, genotype)?;
Ok(program)
}
pub fn bitmaps_to_transfer(program: &Program, context: &Context) -> Vec<String> {
// the bitmaps used by the current program
let bitmap_strings = program.data.bitmap_strings();
// keep the names that aren't already in the bitmap_cache
context.bitmap_cache.uncached(bitmap_strings)
}
pub fn build_traits(s: &str) -> Result<TraitList> {
let (ast, word_lut) = parse(s)?;
let trait_list = TraitList::compile(&ast, &word_lut)?;
Ok(trait_list)
}
pub fn compile_and_execute(s: &str) -> Result<Var> {
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let program = program_from_source(s)?;
run_program_with_preamble(&mut vm, &mut context, &program)
}
pub fn compile_and_execute_with_seeded_genotype(s: &str, seed: i32) -> Result<Var> {
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let trait_list = build_traits(s)?;
let mut genotype = Genotype::build_from_seed(&trait_list, seed)?;
let program = program_from_source_and_genotype(s, &mut genotype)?;
run_program_with_preamble(&mut vm, &mut context, &program)
}
pub fn compile_str(s: &str) -> Result<Program> {
let (ast, word_lut) = parse(s)?;
compile_program(&ast, &word_lut)
}
pub fn sen_parse(s: &str) -> i32 {
s.len() as i32
}
#[cfg(test)]
pub mod tests {
use super::*;
fn is_rendering_num_verts(
vm: &mut Vm,
context: &mut Context,
s: &str,
expected_num_verts: usize,
) {
let program = program_from_source(s).unwrap();
let _ = run_program_with_preamble(vm, context, &program).unwrap();
assert_eq!(1, context.render_list.get_num_render_packets() as i32);
let geo = context.get_rp_geometry(0).unwrap();
let num_floats = geo.get_geo_len();
let floats_per_vert = 8;
assert_eq!(expected_num_verts, num_floats / floats_per_vert);
}
#[test]
fn
|
() {
// vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let s = "(rect)";
is_rendering_num_verts(&mut vm, &mut context, &s, 4);
}
// #[test]
// fn explore_1() {
// // vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
// let mut vm: Vm = Default::default();
// let mut context: Context = Default::default();
// let s = "
// (define
// coords1 {[[-3.718 -69.162]
// [463.301 -57.804]
// [456.097 -315.570]
// [318.683 -384.297]]
// (gen/2d min: -500 max: 500)}
// coords2 {[[424.112 19.779]
// [2.641 246.678]
// [-449.001 -79.842]
// [37.301 206.818]]
// (gen/2d min: -500 max: 500)}
// coords3 {[[83.331 -282.954]
// [92.716 -393.120]
// [426.686 -420.284]
// [-29.734 335.671]]
// (gen/2d min: -500 max: 500)}
// col-fn-1 (col/build-procedural preset: {transformers (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// col-fn-2 (col/build-procedural preset: {mars (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// col-fn-3 (col/build-procedural preset: {knight-rider (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// num-copies {28 (gen/int min: 1 max: 28)}
// squish (interp/build from: [0 (- num-copies 1)] to: [{1.2 (gen/scalar max: 2)} {0.45 (gen/scalar max: 2)}]))
// (fn (draw angle: 0 copy: 0)
// (scale vector: [(interp/value from: squish t: copy) (interp/value from: squish t: copy)])
// (fence (t num: 200)
// (poly coords: [(interp/bezier t: t coords: coords1)
// (interp/bezier t: t coords: coords2)
// (interp/bezier t: t coords: coords3)]
// colours: [(col/value from: col-fn-1 t: t)
// (col/value from: col-fn-2 t: t)
// (col/value from: col-fn-3 t: t)])))
// (fn (render)
// (rect position: [500 500]
// width: 1000
// height: 1000
// colour: (col/value from: col-fn-1 t: 0.5))
// (on-matrix-stack
// (translate vector: canvas/centre
// (scale vector: [0.8 0.8])
// (repeat/rotate-mirrored fn: (address-of draw)
// copies: num-copies)))
// (render)
// ";
// is_rendering_num_verts(&mut vm, &mut context, &s, 1246);
// }
}
|
bug_running_preamble_crashed_vm
|
identifier_name
|
lib.rs
|
// Copyright (C) 2020 Inderjit Gill <[email protected]>
// This file is part of Seni
// Seni is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Seni 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 Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(
feature = "cargo-clippy",
allow(
clippy::many_single_char_names,
clippy::too_many_arguments,
clippy::excessive_precision
)
)]
/*!
The core crate provides the basic functionality of the Seni system
*/
// this is just for documentation
pub mod seni_language;
// mod ast_checker;
mod bitmap;
mod bitmap_cache;
pub mod colour;
mod colour_palettes;
mod compiler;
pub mod constants;
mod context;
mod ease;
pub mod error;
mod focal;
mod gene;
mod geometry;
mod iname;
mod interp;
mod keywords;
mod lexer;
mod mathutil;
mod matrix;
mod native;
mod node;
mod opcodes;
mod packable;
mod parser;
mod path;
mod prng;
mod program;
mod render_list;
mod render_packet;
mod repeat;
mod rgb;
mod trait_list;
mod unparser;
mod uvmapper;
mod vm;
pub use crate::bitmap_cache::{BitmapCache, BitmapInfo};
pub use crate::compiler::{compile_preamble, compile_program, compile_program_with_genotype};
pub use crate::context::Context;
pub use crate::error::{Error, Result};
pub use crate::gene::{next_generation, Genotype};
pub use crate::packable::Packable;
pub use crate::parser::{parse, WordLut};
pub use crate::program::Program;
pub use crate::render_list::{RPCommand, RenderList};
pub use crate::render_packet::{
RenderPacket, RenderPacketGeometry, RenderPacketImage, RenderPacketMask,
};
pub use crate::trait_list::TraitList;
pub use crate::unparser::{simplified_unparse, unparse};
pub use crate::vm::{ProbeSample, VMProfiling, Var, Vm};
pub fn run_program_with_preamble(
vm: &mut Vm,
context: &mut Context,
program: &Program,
) -> Result<Var> {
context.reset_for_piece();
vm.reset();
// setup the env with the global variables in preamble
let preamble = compile_preamble()?;
vm.interpret(context, &preamble)?;
// reset the ip and setup any profiling of the main program
vm.init_for_main_program(&program, VMProfiling::Off)?;
vm.interpret(context, &program)?;
vm.top_stack_value()
}
pub fn program_from_source(s: &str) -> Result<Program> {
let (ast, word_lut) = parse(s)?;
let program = compile_program(&ast, &word_lut)?;
Ok(program)
}
pub fn program_from_source_and_genotype(s: &str, genotype: &mut Genotype) -> Result<Program> {
let (mut ast, word_lut) = parse(s)?;
let program = compile_program_with_genotype(&mut ast, &word_lut, genotype)?;
Ok(program)
}
pub fn bitmaps_to_transfer(program: &Program, context: &Context) -> Vec<String> {
// the bitmaps used by the current program
let bitmap_strings = program.data.bitmap_strings();
// keep the names that aren't already in the bitmap_cache
context.bitmap_cache.uncached(bitmap_strings)
}
pub fn build_traits(s: &str) -> Result<TraitList> {
let (ast, word_lut) = parse(s)?;
let trait_list = TraitList::compile(&ast, &word_lut)?;
Ok(trait_list)
}
pub fn compile_and_execute(s: &str) -> Result<Var> {
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let program = program_from_source(s)?;
run_program_with_preamble(&mut vm, &mut context, &program)
}
pub fn compile_and_execute_with_seeded_genotype(s: &str, seed: i32) -> Result<Var> {
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let trait_list = build_traits(s)?;
let mut genotype = Genotype::build_from_seed(&trait_list, seed)?;
let program = program_from_source_and_genotype(s, &mut genotype)?;
run_program_with_preamble(&mut vm, &mut context, &program)
}
pub fn compile_str(s: &str) -> Result<Program> {
let (ast, word_lut) = parse(s)?;
compile_program(&ast, &word_lut)
}
pub fn sen_parse(s: &str) -> i32
|
#[cfg(test)]
pub mod tests {
use super::*;
fn is_rendering_num_verts(
vm: &mut Vm,
context: &mut Context,
s: &str,
expected_num_verts: usize,
) {
let program = program_from_source(s).unwrap();
let _ = run_program_with_preamble(vm, context, &program).unwrap();
assert_eq!(1, context.render_list.get_num_render_packets() as i32);
let geo = context.get_rp_geometry(0).unwrap();
let num_floats = geo.get_geo_len();
let floats_per_vert = 8;
assert_eq!(expected_num_verts, num_floats / floats_per_vert);
}
#[test]
fn bug_running_preamble_crashed_vm() {
// vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let s = "(rect)";
is_rendering_num_verts(&mut vm, &mut context, &s, 4);
}
// #[test]
// fn explore_1() {
// // vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
// let mut vm: Vm = Default::default();
// let mut context: Context = Default::default();
// let s = "
// (define
// coords1 {[[-3.718 -69.162]
// [463.301 -57.804]
// [456.097 -315.570]
// [318.683 -384.297]]
// (gen/2d min: -500 max: 500)}
// coords2 {[[424.112 19.779]
// [2.641 246.678]
// [-449.001 -79.842]
// [37.301 206.818]]
// (gen/2d min: -500 max: 500)}
// coords3 {[[83.331 -282.954]
// [92.716 -393.120]
// [426.686 -420.284]
// [-29.734 335.671]]
// (gen/2d min: -500 max: 500)}
// col-fn-1 (col/build-procedural preset: {transformers (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// col-fn-2 (col/build-procedural preset: {mars (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// col-fn-3 (col/build-procedural preset: {knight-rider (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// num-copies {28 (gen/int min: 1 max: 28)}
// squish (interp/build from: [0 (- num-copies 1)] to: [{1.2 (gen/scalar max: 2)} {0.45 (gen/scalar max: 2)}]))
// (fn (draw angle: 0 copy: 0)
// (scale vector: [(interp/value from: squish t: copy) (interp/value from: squish t: copy)])
// (fence (t num: 200)
// (poly coords: [(interp/bezier t: t coords: coords1)
// (interp/bezier t: t coords: coords2)
// (interp/bezier t: t coords: coords3)]
// colours: [(col/value from: col-fn-1 t: t)
// (col/value from: col-fn-2 t: t)
// (col/value from: col-fn-3 t: t)])))
// (fn (render)
// (rect position: [500 500]
// width: 1000
// height: 1000
// colour: (col/value from: col-fn-1 t: 0.5))
// (on-matrix-stack
// (translate vector: canvas/centre
// (scale vector: [0.8 0.8])
// (repeat/rotate-mirrored fn: (address-of draw)
// copies: num-copies)))
// (render)
// ";
// is_rendering_num_verts(&mut vm, &mut context, &s, 1246);
// }
}
|
{
s.len() as i32
}
|
identifier_body
|
lib.rs
|
// Copyright (C) 2020 Inderjit Gill <[email protected]>
// This file is part of Seni
// Seni is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Seni 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
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#![cfg_attr(
feature = "cargo-clippy",
allow(
clippy::many_single_char_names,
clippy::too_many_arguments,
clippy::excessive_precision
)
)]
/*!
The core crate provides the basic functionality of the Seni system
*/
// this is just for documentation
pub mod seni_language;
// mod ast_checker;
mod bitmap;
mod bitmap_cache;
pub mod colour;
mod colour_palettes;
mod compiler;
pub mod constants;
mod context;
mod ease;
pub mod error;
mod focal;
mod gene;
mod geometry;
mod iname;
mod interp;
mod keywords;
mod lexer;
mod mathutil;
mod matrix;
mod native;
mod node;
mod opcodes;
mod packable;
mod parser;
mod path;
mod prng;
mod program;
mod render_list;
mod render_packet;
mod repeat;
mod rgb;
mod trait_list;
mod unparser;
mod uvmapper;
mod vm;
pub use crate::bitmap_cache::{BitmapCache, BitmapInfo};
pub use crate::compiler::{compile_preamble, compile_program, compile_program_with_genotype};
pub use crate::context::Context;
pub use crate::error::{Error, Result};
pub use crate::gene::{next_generation, Genotype};
pub use crate::packable::Packable;
pub use crate::parser::{parse, WordLut};
pub use crate::program::Program;
pub use crate::render_list::{RPCommand, RenderList};
pub use crate::render_packet::{
RenderPacket, RenderPacketGeometry, RenderPacketImage, RenderPacketMask,
};
pub use crate::trait_list::TraitList;
pub use crate::unparser::{simplified_unparse, unparse};
pub use crate::vm::{ProbeSample, VMProfiling, Var, Vm};
pub fn run_program_with_preamble(
vm: &mut Vm,
context: &mut Context,
program: &Program,
) -> Result<Var> {
context.reset_for_piece();
vm.reset();
// setup the env with the global variables in preamble
let preamble = compile_preamble()?;
vm.interpret(context, &preamble)?;
// reset the ip and setup any profiling of the main program
vm.init_for_main_program(&program, VMProfiling::Off)?;
vm.interpret(context, &program)?;
vm.top_stack_value()
}
pub fn program_from_source(s: &str) -> Result<Program> {
let (ast, word_lut) = parse(s)?;
let program = compile_program(&ast, &word_lut)?;
Ok(program)
}
pub fn program_from_source_and_genotype(s: &str, genotype: &mut Genotype) -> Result<Program> {
let (mut ast, word_lut) = parse(s)?;
let program = compile_program_with_genotype(&mut ast, &word_lut, genotype)?;
Ok(program)
}
pub fn bitmaps_to_transfer(program: &Program, context: &Context) -> Vec<String> {
// the bitmaps used by the current program
let bitmap_strings = program.data.bitmap_strings();
// keep the names that aren't already in the bitmap_cache
context.bitmap_cache.uncached(bitmap_strings)
}
pub fn build_traits(s: &str) -> Result<TraitList> {
let (ast, word_lut) = parse(s)?;
let trait_list = TraitList::compile(&ast, &word_lut)?;
Ok(trait_list)
}
pub fn compile_and_execute(s: &str) -> Result<Var> {
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let program = program_from_source(s)?;
run_program_with_preamble(&mut vm, &mut context, &program)
}
pub fn compile_and_execute_with_seeded_genotype(s: &str, seed: i32) -> Result<Var> {
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let trait_list = build_traits(s)?;
let mut genotype = Genotype::build_from_seed(&trait_list, seed)?;
let program = program_from_source_and_genotype(s, &mut genotype)?;
run_program_with_preamble(&mut vm, &mut context, &program)
}
pub fn compile_str(s: &str) -> Result<Program> {
let (ast, word_lut) = parse(s)?;
compile_program(&ast, &word_lut)
}
pub fn sen_parse(s: &str) -> i32 {
s.len() as i32
}
#[cfg(test)]
pub mod tests {
use super::*;
fn is_rendering_num_verts(
vm: &mut Vm,
context: &mut Context,
s: &str,
expected_num_verts: usize,
) {
let program = program_from_source(s).unwrap();
let _ = run_program_with_preamble(vm, context, &program).unwrap();
assert_eq!(1, context.render_list.get_num_render_packets() as i32);
let geo = context.get_rp_geometry(0).unwrap();
let num_floats = geo.get_geo_len();
let floats_per_vert = 8;
assert_eq!(expected_num_verts, num_floats / floats_per_vert);
}
#[test]
fn bug_running_preamble_crashed_vm() {
// vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
let mut vm: Vm = Default::default();
let mut context: Context = Default::default();
let s = "(rect)";
is_rendering_num_verts(&mut vm, &mut context, &s, 4);
}
// #[test]
// fn explore_1() {
// // vm.ip wasn't being set to 0 in-between running the preamble and running the user's program
// let mut vm: Vm = Default::default();
// let mut context: Context = Default::default();
// let s = "
// (define
// coords1 {[[-3.718 -69.162]
// [463.301 -57.804]
// [456.097 -315.570]
// [318.683 -384.297]]
// (gen/2d min: -500 max: 500)}
// coords2 {[[424.112 19.779]
// [2.641 246.678]
// [-449.001 -79.842]
// [37.301 206.818]]
// (gen/2d min: -500 max: 500)}
// coords3 {[[83.331 -282.954]
// [92.716 -393.120]
// [426.686 -420.284]
// [-29.734 335.671]]
// (gen/2d min: -500 max: 500)}
// col-fn-1 (col/build-procedural preset: {transformers (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// col-fn-2 (col/build-procedural preset: {mars (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// col-fn-3 (col/build-procedural preset: {knight-rider (gen/select from: col/procedural-fn-presets)}
// alpha: 0.08)
// num-copies {28 (gen/int min: 1 max: 28)}
// squish (interp/build from: [0 (- num-copies 1)] to: [{1.2 (gen/scalar max: 2)} {0.45 (gen/scalar max: 2)}]))
// (fn (draw angle: 0 copy: 0)
// (scale vector: [(interp/value from: squish t: copy) (interp/value from: squish t: copy)])
// (fence (t num: 200)
// (poly coords: [(interp/bezier t: t coords: coords1)
// (interp/bezier t: t coords: coords2)
// (interp/bezier t: t coords: coords3)]
// colours: [(col/value from: col-fn-1 t: t)
// (col/value from: col-fn-2 t: t)
// (col/value from: col-fn-3 t: t)])))
// (fn (render)
// (rect position: [500 500]
// width: 1000
// height: 1000
// colour: (col/value from: col-fn-1 t: 0.5))
// (on-matrix-stack
// (translate vector: canvas/centre
// (scale vector: [0.8 0.8])
// (repeat/rotate-mirrored fn: (address-of draw)
// copies: num-copies)))
// (render)
// ";
// is_rendering_num_verts(&mut vm, &mut context, &s, 1246);
// }
}
|
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
|
random_line_split
|
dummy_variables.rs
|
use std::default::Default;
use std::marker::PhantomData;
use variable::GetVariable;
/// Struct that implement [`Index`],
/// used to fake variables when don't needed in expressions.
///
/// Prefer using this container with the [`DummyVariable`] fake type.
///
/// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Index.html
/// [`DummyVariable`]:../variable/struct.DummyVariable.html
/// [`index()`]: https://doc.rust-lang.org/std/ops/trait.Index.html#tymethod.index
#[derive(Debug)]
pub struct DummyVariables<T>(PhantomData<T>);
impl<T> Default for DummyVariables<T> {
fn default() -> Self
|
}
impl<T> GetVariable<()> for DummyVariables<T> {
type Output = T;
fn get_variable(&self, _: ()) -> Option<&Self::Output> {
None
}
}
|
{
DummyVariables(PhantomData::default())
}
|
identifier_body
|
dummy_variables.rs
|
use std::default::Default;
use std::marker::PhantomData;
use variable::GetVariable;
/// Struct that implement [`Index`],
/// used to fake variables when don't needed in expressions.
///
/// Prefer using this container with the [`DummyVariable`] fake type.
///
/// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Index.html
/// [`DummyVariable`]:../variable/struct.DummyVariable.html
/// [`index()`]: https://doc.rust-lang.org/std/ops/trait.Index.html#tymethod.index
#[derive(Debug)]
pub struct DummyVariables<T>(PhantomData<T>);
impl<T> Default for DummyVariables<T> {
|
}
}
impl<T> GetVariable<()> for DummyVariables<T> {
type Output = T;
fn get_variable(&self, _: ()) -> Option<&Self::Output> {
None
}
}
|
fn default() -> Self {
DummyVariables(PhantomData::default())
|
random_line_split
|
dummy_variables.rs
|
use std::default::Default;
use std::marker::PhantomData;
use variable::GetVariable;
/// Struct that implement [`Index`],
/// used to fake variables when don't needed in expressions.
///
/// Prefer using this container with the [`DummyVariable`] fake type.
///
/// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Index.html
/// [`DummyVariable`]:../variable/struct.DummyVariable.html
/// [`index()`]: https://doc.rust-lang.org/std/ops/trait.Index.html#tymethod.index
#[derive(Debug)]
pub struct DummyVariables<T>(PhantomData<T>);
impl<T> Default for DummyVariables<T> {
fn default() -> Self {
DummyVariables(PhantomData::default())
}
}
impl<T> GetVariable<()> for DummyVariables<T> {
type Output = T;
fn
|
(&self, _: ()) -> Option<&Self::Output> {
None
}
}
|
get_variable
|
identifier_name
|
graph.rs
|
//! Trace and batch implementations based on sorted ranges.
//!
//! The types and type aliases in this module start with either
//!
//! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered.
//! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered.
//!
//! Although `OrdVal` is more general than `OrdKey`, the latter has a simpler representation
//! and should consume fewer resources (computation and memory) when it applies.
// use std::cmp::Ordering;
use std::rc::Rc;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use timely::progress::nested::product::Product;
use timely::progress::timestamp::RootTimestamp;
type Node = u32;
///
struct GraphSpine<N> where N: Ord+Clone+'static {
spine: Spine<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>
}
impl<N> TraceReader<Node, N, Product<RootTimestamp, ()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
type Batch = Rc<GraphBatch<N>>;
type Cursor = RcBatchCursor<Node, N, Product<RootTimestamp, ()>, isize, GraphBatch<N>>;
fn cursor_through(&mut self, upper: &[Product<RootTimestamp,()>]) -> Option<(Self::Cursor, <Self::Cursor as Cursor<Node, N, Product<RootTimestamp,()>, isize>>::Storage)> {
let mut batch = Vec::new();
self.spine.map_batches(|b| batch.push(b.clone()));
assert!(batch.len() <= 1);
if upper == &[] {
batch.pop().map(|b| (b.cursor(), b))
}
else { None }
}
fn advance_by(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.advance_by(frontier)
}
fn advance_frontier(&mut self) -> &[Product<RootTimestamp,()>] { self.spine.advance_frontier() }
fn distinguish_since(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.distinguish_since(frontier)
}
fn distinguish_frontier(&mut self) -> &[Product<RootTimestamp,()>] { &self.spine.distinguish_frontier() }
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
self.spine.map_batches(f)
}
}
// A trace implementation for any key type that can be borrowed from or converted into `Key`.
// TODO: Almost all this implementation seems to be generic with respect to the trace and batch types.
impl<N> Trace<Node, N, Product<RootTimestamp,()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
fn new() -> Self {
GraphSpine {
spine: Spine::<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>::new()
}
}
// Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin
// merging the batch. This means it is a good time to perform amortized work proportional
// to the size of batch.
fn insert(&mut self, batch: Self::Batch)
|
fn close(&mut self) {
self.spine.close()
}
}
///
#[derive(Debug, Abomonation)]
pub struct GraphBatch<N> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
desc: Description<Product<RootTimestamp,()>>,
}
impl<N> BatchReader<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Cursor = GraphCursor;
fn cursor(&self) -> Self::Cursor { GraphCursor { key: self.index as Node, key_pos: 0, val_pos: 0 } }
fn len(&self) -> usize { self.edges.len() }
fn description(&self) -> &Description<Product<RootTimestamp,()>> { &self.desc }
}
impl<N> Batch<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Batcher = MergeBatcher<Node, N, Product<RootTimestamp,()>, isize, Self>;
type Builder = GraphBuilder<N>;
type Merger = GraphMerger;
fn begin_merge(&self, other: &Self) -> Self::Merger {
GraphMerger::new(self, other)
}
}
///
pub struct GraphMerger { }
impl<N> Merger<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphMerger where N: Ord+Clone+'static {
fn new(_batch1: &GraphBatch<N>, _batch2: &GraphBatch<N>) -> Self {
panic!("Cannot merge GraphBatch; they are static");
}
fn done(self) -> GraphBatch<N> {
panic!("Cannot merge GraphBatch; they are static");
}
fn work(&mut self, _source1: &GraphBatch<N>, _source2: &GraphBatch<N>, _frontier: &Option<Vec<Product<RootTimestamp,()>>>, _fuel: &mut usize) {
panic!("Cannot merge GraphBatch; they are static");
}
}
/// A cursor for navigating a single layer.
#[derive(Debug)]
pub struct GraphCursor {
key: Node,
key_pos: usize,
val_pos: usize,
}
impl<N> Cursor<Node, N, Product<RootTimestamp,()>, isize> for GraphCursor where N: Ord+Clone {
type Storage = GraphBatch<N>;
fn key<'a>(&self, storage: &'a Self::Storage) -> &'a Node { &storage.keys[self.key_pos] }
fn val<'a>(&self, storage: &'a Self::Storage) -> &'a N { &storage.edges[self.val_pos] }
fn map_times<L: FnMut(&Product<RootTimestamp,()>, isize)>(&mut self, _storage: &Self::Storage, mut logic: L) {
logic(&Product::new(RootTimestamp, ()), 1);
}
fn key_valid(&self, storage: &Self::Storage) -> bool { (self.key_pos + 1) < storage.nodes.len() }
fn val_valid(&self, storage: &Self::Storage) -> bool {
self.val_pos < storage.nodes[self.key_pos + 1]
}
fn step_key(&mut self, storage: &Self::Storage){
if self.key_valid(storage) {
self.key_pos += 1;
self.key += storage.peers as Node;
}
}
fn seek_key(&mut self, storage: &Self::Storage, key: &Node) {
if self.key_valid(storage) {
self.key_pos = (*key as usize) / storage.peers;
if self.key_pos + 1 >= storage.nodes.len() {
self.key_pos = storage.nodes.len() - 1;
}
self.val_pos = storage.nodes[self.key_pos];
self.key = (storage.peers * self.key_pos + storage.index) as Node;
}
}
fn step_val(&mut self, storage: &Self::Storage) {
if self.val_valid(storage) {
self.val_pos += 1;
}
}
fn seek_val(&mut self, storage: &Self::Storage, val: &N) {
if self.val_valid(storage) {
let lower = self.val_pos;
let upper = storage.nodes[self.key_pos + 1];
self.val_pos += advance(&storage.edges[lower.. upper], |tuple| tuple < val);
}
}
fn rewind_keys(&mut self, storage: &Self::Storage) { self.key_pos = 0; self.key = storage.index as Node; }
fn rewind_vals(&mut self, storage: &Self::Storage) {
if self.key_valid(storage) {
self.val_pos = storage.nodes[self.key_pos];
}
}
}
/// A builder for creating layers from unsorted update tuples.
pub struct GraphBuilder<N: Ord> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
}
impl<N> Builder<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphBuilder<N> where N: Ord+Clone+'static {
fn new() -> Self { Self::with_capacity(0) }
fn with_capacity(cap: usize) -> Self {
GraphBuilder {
index: 0,
peers: 1,
keys: Vec::new(),
nodes: Vec::new(),
edges: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, (key, val, _time, _diff): (Node, N, Product<RootTimestamp,()>, isize)) {
while self.nodes.len() <= (key as usize) / self.peers {
self.keys.push((self.peers * self.nodes.len() + self.index) as Node);
self.nodes.push(self.edges.len());
}
self.edges.push(val);
}
#[inline(never)]
fn done(mut self, lower: &[Product<RootTimestamp,()>], upper: &[Product<RootTimestamp,()>], since: &[Product<RootTimestamp,()>]) -> GraphBatch<N> {
println!("GraphBuilder::done(): {} nodes, {} edges.", self.nodes.len(), self.edges.len());
self.nodes.push(self.edges.len());
GraphBatch {
index: self.index,
peers: self.peers,
keys: self.keys,
nodes: self.nodes,
edges: self.edges,
desc: Description::new(lower, upper, since)
}
}
}
/// Reports the number of elements satisfing the predicate.
///
/// This methods *relies strongly* on the assumption that the predicate
/// stays false once it becomes false, a joint property of the predicate
/// and the slice. This allows `advance` to use exponential search to
/// count the number of elements in time logarithmic in the result.
#[inline(never)]
pub fn advance<T, F: Fn(&T)->bool>(slice: &[T], function: F) -> usize {
// start with no advance
let mut index = 0;
if index < slice.len() && function(&slice[index]) {
// advance in exponentially growing steps.
let mut step = 1;
while index + step < slice.len() && function(&slice[index + step]) {
index += step;
step = step << 1;
}
// advance in exponentially shrinking steps.
step = step >> 1;
while step > 0 {
if index + step < slice.len() && function(&slice[index + step]) {
index += step;
}
step = step >> 1;
}
index += 1;
}
index
}
|
{
self.spine.insert(batch)
}
|
identifier_body
|
graph.rs
|
//! Trace and batch implementations based on sorted ranges.
//!
//! The types and type aliases in this module start with either
//!
//! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered.
//! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered.
//!
//! Although `OrdVal` is more general than `OrdKey`, the latter has a simpler representation
//! and should consume fewer resources (computation and memory) when it applies.
// use std::cmp::Ordering;
use std::rc::Rc;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use timely::progress::nested::product::Product;
use timely::progress::timestamp::RootTimestamp;
type Node = u32;
///
struct GraphSpine<N> where N: Ord+Clone+'static {
spine: Spine<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>
}
impl<N> TraceReader<Node, N, Product<RootTimestamp, ()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
type Batch = Rc<GraphBatch<N>>;
type Cursor = RcBatchCursor<Node, N, Product<RootTimestamp, ()>, isize, GraphBatch<N>>;
fn cursor_through(&mut self, upper: &[Product<RootTimestamp,()>]) -> Option<(Self::Cursor, <Self::Cursor as Cursor<Node, N, Product<RootTimestamp,()>, isize>>::Storage)> {
let mut batch = Vec::new();
self.spine.map_batches(|b| batch.push(b.clone()));
assert!(batch.len() <= 1);
if upper == &[] {
batch.pop().map(|b| (b.cursor(), b))
}
else { None }
}
fn advance_by(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.advance_by(frontier)
}
fn advance_frontier(&mut self) -> &[Product<RootTimestamp,()>] { self.spine.advance_frontier() }
fn distinguish_since(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.distinguish_since(frontier)
}
fn distinguish_frontier(&mut self) -> &[Product<RootTimestamp,()>] { &self.spine.distinguish_frontier() }
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
self.spine.map_batches(f)
}
}
// A trace implementation for any key type that can be borrowed from or converted into `Key`.
// TODO: Almost all this implementation seems to be generic with respect to the trace and batch types.
impl<N> Trace<Node, N, Product<RootTimestamp,()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
fn new() -> Self {
GraphSpine {
spine: Spine::<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>::new()
}
}
// Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin
// merging the batch. This means it is a good time to perform amortized work proportional
// to the size of batch.
fn insert(&mut self, batch: Self::Batch) {
self.spine.insert(batch)
}
fn close(&mut self) {
self.spine.close()
}
}
///
#[derive(Debug, Abomonation)]
pub struct GraphBatch<N> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
desc: Description<Product<RootTimestamp,()>>,
}
impl<N> BatchReader<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Cursor = GraphCursor;
fn cursor(&self) -> Self::Cursor { GraphCursor { key: self.index as Node, key_pos: 0, val_pos: 0 } }
fn len(&self) -> usize { self.edges.len() }
fn description(&self) -> &Description<Product<RootTimestamp,()>> { &self.desc }
}
impl<N> Batch<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Batcher = MergeBatcher<Node, N, Product<RootTimestamp,()>, isize, Self>;
type Builder = GraphBuilder<N>;
type Merger = GraphMerger;
fn begin_merge(&self, other: &Self) -> Self::Merger {
GraphMerger::new(self, other)
}
}
///
pub struct GraphMerger { }
impl<N> Merger<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphMerger where N: Ord+Clone+'static {
fn new(_batch1: &GraphBatch<N>, _batch2: &GraphBatch<N>) -> Self {
panic!("Cannot merge GraphBatch; they are static");
}
fn done(self) -> GraphBatch<N> {
panic!("Cannot merge GraphBatch; they are static");
}
fn work(&mut self, _source1: &GraphBatch<N>, _source2: &GraphBatch<N>, _frontier: &Option<Vec<Product<RootTimestamp,()>>>, _fuel: &mut usize) {
panic!("Cannot merge GraphBatch; they are static");
}
}
/// A cursor for navigating a single layer.
#[derive(Debug)]
pub struct GraphCursor {
key: Node,
key_pos: usize,
val_pos: usize,
}
impl<N> Cursor<Node, N, Product<RootTimestamp,()>, isize> for GraphCursor where N: Ord+Clone {
type Storage = GraphBatch<N>;
fn key<'a>(&self, storage: &'a Self::Storage) -> &'a Node { &storage.keys[self.key_pos] }
fn val<'a>(&self, storage: &'a Self::Storage) -> &'a N { &storage.edges[self.val_pos] }
fn map_times<L: FnMut(&Product<RootTimestamp,()>, isize)>(&mut self, _storage: &Self::Storage, mut logic: L) {
logic(&Product::new(RootTimestamp, ()), 1);
}
fn key_valid(&self, storage: &Self::Storage) -> bool { (self.key_pos + 1) < storage.nodes.len() }
fn val_valid(&self, storage: &Self::Storage) -> bool {
self.val_pos < storage.nodes[self.key_pos + 1]
}
fn step_key(&mut self, storage: &Self::Storage){
if self.key_valid(storage) {
self.key_pos += 1;
self.key += storage.peers as Node;
}
}
fn seek_key(&mut self, storage: &Self::Storage, key: &Node) {
if self.key_valid(storage) {
self.key_pos = (*key as usize) / storage.peers;
if self.key_pos + 1 >= storage.nodes.len() {
self.key_pos = storage.nodes.len() - 1;
}
self.val_pos = storage.nodes[self.key_pos];
self.key = (storage.peers * self.key_pos + storage.index) as Node;
}
}
fn step_val(&mut self, storage: &Self::Storage) {
if self.val_valid(storage) {
self.val_pos += 1;
}
}
fn seek_val(&mut self, storage: &Self::Storage, val: &N) {
if self.val_valid(storage)
|
}
fn rewind_keys(&mut self, storage: &Self::Storage) { self.key_pos = 0; self.key = storage.index as Node; }
fn rewind_vals(&mut self, storage: &Self::Storage) {
if self.key_valid(storage) {
self.val_pos = storage.nodes[self.key_pos];
}
}
}
/// A builder for creating layers from unsorted update tuples.
pub struct GraphBuilder<N: Ord> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
}
impl<N> Builder<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphBuilder<N> where N: Ord+Clone+'static {
fn new() -> Self { Self::with_capacity(0) }
fn with_capacity(cap: usize) -> Self {
GraphBuilder {
index: 0,
peers: 1,
keys: Vec::new(),
nodes: Vec::new(),
edges: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, (key, val, _time, _diff): (Node, N, Product<RootTimestamp,()>, isize)) {
while self.nodes.len() <= (key as usize) / self.peers {
self.keys.push((self.peers * self.nodes.len() + self.index) as Node);
self.nodes.push(self.edges.len());
}
self.edges.push(val);
}
#[inline(never)]
fn done(mut self, lower: &[Product<RootTimestamp,()>], upper: &[Product<RootTimestamp,()>], since: &[Product<RootTimestamp,()>]) -> GraphBatch<N> {
println!("GraphBuilder::done(): {} nodes, {} edges.", self.nodes.len(), self.edges.len());
self.nodes.push(self.edges.len());
GraphBatch {
index: self.index,
peers: self.peers,
keys: self.keys,
nodes: self.nodes,
edges: self.edges,
desc: Description::new(lower, upper, since)
}
}
}
/// Reports the number of elements satisfing the predicate.
///
/// This methods *relies strongly* on the assumption that the predicate
/// stays false once it becomes false, a joint property of the predicate
/// and the slice. This allows `advance` to use exponential search to
/// count the number of elements in time logarithmic in the result.
#[inline(never)]
pub fn advance<T, F: Fn(&T)->bool>(slice: &[T], function: F) -> usize {
// start with no advance
let mut index = 0;
if index < slice.len() && function(&slice[index]) {
// advance in exponentially growing steps.
let mut step = 1;
while index + step < slice.len() && function(&slice[index + step]) {
index += step;
step = step << 1;
}
// advance in exponentially shrinking steps.
step = step >> 1;
while step > 0 {
if index + step < slice.len() && function(&slice[index + step]) {
index += step;
}
step = step >> 1;
}
index += 1;
}
index
}
|
{
let lower = self.val_pos;
let upper = storage.nodes[self.key_pos + 1];
self.val_pos += advance(&storage.edges[lower .. upper], |tuple| tuple < val);
}
|
conditional_block
|
graph.rs
|
//! Trace and batch implementations based on sorted ranges.
//!
//! The types and type aliases in this module start with either
//!
//! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered.
//! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered.
//!
//! Although `OrdVal` is more general than `OrdKey`, the latter has a simpler representation
//! and should consume fewer resources (computation and memory) when it applies.
// use std::cmp::Ordering;
use std::rc::Rc;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use timely::progress::nested::product::Product;
use timely::progress::timestamp::RootTimestamp;
type Node = u32;
///
struct GraphSpine<N> where N: Ord+Clone+'static {
spine: Spine<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>
}
impl<N> TraceReader<Node, N, Product<RootTimestamp, ()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
type Batch = Rc<GraphBatch<N>>;
type Cursor = RcBatchCursor<Node, N, Product<RootTimestamp, ()>, isize, GraphBatch<N>>;
fn cursor_through(&mut self, upper: &[Product<RootTimestamp,()>]) -> Option<(Self::Cursor, <Self::Cursor as Cursor<Node, N, Product<RootTimestamp,()>, isize>>::Storage)> {
let mut batch = Vec::new();
self.spine.map_batches(|b| batch.push(b.clone()));
assert!(batch.len() <= 1);
if upper == &[] {
batch.pop().map(|b| (b.cursor(), b))
}
else { None }
}
fn advance_by(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.advance_by(frontier)
}
fn advance_frontier(&mut self) -> &[Product<RootTimestamp,()>] { self.spine.advance_frontier() }
fn distinguish_since(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.distinguish_since(frontier)
}
fn distinguish_frontier(&mut self) -> &[Product<RootTimestamp,()>] { &self.spine.distinguish_frontier() }
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
self.spine.map_batches(f)
}
}
// A trace implementation for any key type that can be borrowed from or converted into `Key`.
// TODO: Almost all this implementation seems to be generic with respect to the trace and batch types.
impl<N> Trace<Node, N, Product<RootTimestamp,()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
fn new() -> Self {
|
}
}
// Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin
// merging the batch. This means it is a good time to perform amortized work proportional
// to the size of batch.
fn insert(&mut self, batch: Self::Batch) {
self.spine.insert(batch)
}
fn close(&mut self) {
self.spine.close()
}
}
///
#[derive(Debug, Abomonation)]
pub struct GraphBatch<N> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
desc: Description<Product<RootTimestamp,()>>,
}
impl<N> BatchReader<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Cursor = GraphCursor;
fn cursor(&self) -> Self::Cursor { GraphCursor { key: self.index as Node, key_pos: 0, val_pos: 0 } }
fn len(&self) -> usize { self.edges.len() }
fn description(&self) -> &Description<Product<RootTimestamp,()>> { &self.desc }
}
impl<N> Batch<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Batcher = MergeBatcher<Node, N, Product<RootTimestamp,()>, isize, Self>;
type Builder = GraphBuilder<N>;
type Merger = GraphMerger;
fn begin_merge(&self, other: &Self) -> Self::Merger {
GraphMerger::new(self, other)
}
}
///
pub struct GraphMerger { }
impl<N> Merger<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphMerger where N: Ord+Clone+'static {
fn new(_batch1: &GraphBatch<N>, _batch2: &GraphBatch<N>) -> Self {
panic!("Cannot merge GraphBatch; they are static");
}
fn done(self) -> GraphBatch<N> {
panic!("Cannot merge GraphBatch; they are static");
}
fn work(&mut self, _source1: &GraphBatch<N>, _source2: &GraphBatch<N>, _frontier: &Option<Vec<Product<RootTimestamp,()>>>, _fuel: &mut usize) {
panic!("Cannot merge GraphBatch; they are static");
}
}
/// A cursor for navigating a single layer.
#[derive(Debug)]
pub struct GraphCursor {
key: Node,
key_pos: usize,
val_pos: usize,
}
impl<N> Cursor<Node, N, Product<RootTimestamp,()>, isize> for GraphCursor where N: Ord+Clone {
type Storage = GraphBatch<N>;
fn key<'a>(&self, storage: &'a Self::Storage) -> &'a Node { &storage.keys[self.key_pos] }
fn val<'a>(&self, storage: &'a Self::Storage) -> &'a N { &storage.edges[self.val_pos] }
fn map_times<L: FnMut(&Product<RootTimestamp,()>, isize)>(&mut self, _storage: &Self::Storage, mut logic: L) {
logic(&Product::new(RootTimestamp, ()), 1);
}
fn key_valid(&self, storage: &Self::Storage) -> bool { (self.key_pos + 1) < storage.nodes.len() }
fn val_valid(&self, storage: &Self::Storage) -> bool {
self.val_pos < storage.nodes[self.key_pos + 1]
}
fn step_key(&mut self, storage: &Self::Storage){
if self.key_valid(storage) {
self.key_pos += 1;
self.key += storage.peers as Node;
}
}
fn seek_key(&mut self, storage: &Self::Storage, key: &Node) {
if self.key_valid(storage) {
self.key_pos = (*key as usize) / storage.peers;
if self.key_pos + 1 >= storage.nodes.len() {
self.key_pos = storage.nodes.len() - 1;
}
self.val_pos = storage.nodes[self.key_pos];
self.key = (storage.peers * self.key_pos + storage.index) as Node;
}
}
fn step_val(&mut self, storage: &Self::Storage) {
if self.val_valid(storage) {
self.val_pos += 1;
}
}
fn seek_val(&mut self, storage: &Self::Storage, val: &N) {
if self.val_valid(storage) {
let lower = self.val_pos;
let upper = storage.nodes[self.key_pos + 1];
self.val_pos += advance(&storage.edges[lower.. upper], |tuple| tuple < val);
}
}
fn rewind_keys(&mut self, storage: &Self::Storage) { self.key_pos = 0; self.key = storage.index as Node; }
fn rewind_vals(&mut self, storage: &Self::Storage) {
if self.key_valid(storage) {
self.val_pos = storage.nodes[self.key_pos];
}
}
}
/// A builder for creating layers from unsorted update tuples.
pub struct GraphBuilder<N: Ord> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
}
impl<N> Builder<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphBuilder<N> where N: Ord+Clone+'static {
fn new() -> Self { Self::with_capacity(0) }
fn with_capacity(cap: usize) -> Self {
GraphBuilder {
index: 0,
peers: 1,
keys: Vec::new(),
nodes: Vec::new(),
edges: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, (key, val, _time, _diff): (Node, N, Product<RootTimestamp,()>, isize)) {
while self.nodes.len() <= (key as usize) / self.peers {
self.keys.push((self.peers * self.nodes.len() + self.index) as Node);
self.nodes.push(self.edges.len());
}
self.edges.push(val);
}
#[inline(never)]
fn done(mut self, lower: &[Product<RootTimestamp,()>], upper: &[Product<RootTimestamp,()>], since: &[Product<RootTimestamp,()>]) -> GraphBatch<N> {
println!("GraphBuilder::done(): {} nodes, {} edges.", self.nodes.len(), self.edges.len());
self.nodes.push(self.edges.len());
GraphBatch {
index: self.index,
peers: self.peers,
keys: self.keys,
nodes: self.nodes,
edges: self.edges,
desc: Description::new(lower, upper, since)
}
}
}
/// Reports the number of elements satisfing the predicate.
///
/// This methods *relies strongly* on the assumption that the predicate
/// stays false once it becomes false, a joint property of the predicate
/// and the slice. This allows `advance` to use exponential search to
/// count the number of elements in time logarithmic in the result.
#[inline(never)]
pub fn advance<T, F: Fn(&T)->bool>(slice: &[T], function: F) -> usize {
// start with no advance
let mut index = 0;
if index < slice.len() && function(&slice[index]) {
// advance in exponentially growing steps.
let mut step = 1;
while index + step < slice.len() && function(&slice[index + step]) {
index += step;
step = step << 1;
}
// advance in exponentially shrinking steps.
step = step >> 1;
while step > 0 {
if index + step < slice.len() && function(&slice[index + step]) {
index += step;
}
step = step >> 1;
}
index += 1;
}
index
}
|
GraphSpine {
spine: Spine::<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>::new()
|
random_line_split
|
graph.rs
|
//! Trace and batch implementations based on sorted ranges.
//!
//! The types and type aliases in this module start with either
//!
//! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered.
//! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered.
//!
//! Although `OrdVal` is more general than `OrdKey`, the latter has a simpler representation
//! and should consume fewer resources (computation and memory) when it applies.
// use std::cmp::Ordering;
use std::rc::Rc;
// use ::Diff;
// use lattice::Lattice;
use trace::{Batch, BatchReader, Builder, Merger, Cursor, Trace, TraceReader};
use trace::description::Description;
use trace::rc_blanket_impls::RcBatchCursor;
// use trace::layers::MergeBuilder;
use super::spine_fueled::Spine;
use super::merge_batcher::MergeBatcher;
use timely::progress::nested::product::Product;
use timely::progress::timestamp::RootTimestamp;
type Node = u32;
///
struct GraphSpine<N> where N: Ord+Clone+'static {
spine: Spine<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>
}
impl<N> TraceReader<Node, N, Product<RootTimestamp, ()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
type Batch = Rc<GraphBatch<N>>;
type Cursor = RcBatchCursor<Node, N, Product<RootTimestamp, ()>, isize, GraphBatch<N>>;
fn cursor_through(&mut self, upper: &[Product<RootTimestamp,()>]) -> Option<(Self::Cursor, <Self::Cursor as Cursor<Node, N, Product<RootTimestamp,()>, isize>>::Storage)> {
let mut batch = Vec::new();
self.spine.map_batches(|b| batch.push(b.clone()));
assert!(batch.len() <= 1);
if upper == &[] {
batch.pop().map(|b| (b.cursor(), b))
}
else { None }
}
fn advance_by(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.advance_by(frontier)
}
fn advance_frontier(&mut self) -> &[Product<RootTimestamp,()>] { self.spine.advance_frontier() }
fn distinguish_since(&mut self, frontier: &[Product<RootTimestamp,()>]) {
self.spine.distinguish_since(frontier)
}
fn distinguish_frontier(&mut self) -> &[Product<RootTimestamp,()>] { &self.spine.distinguish_frontier() }
fn map_batches<F: FnMut(&Self::Batch)>(&mut self, f: F) {
self.spine.map_batches(f)
}
}
// A trace implementation for any key type that can be borrowed from or converted into `Key`.
// TODO: Almost all this implementation seems to be generic with respect to the trace and batch types.
impl<N> Trace<Node, N, Product<RootTimestamp,()>, isize> for GraphSpine<N>
where
N: Ord+Clone+'static,
{
fn new() -> Self {
GraphSpine {
spine: Spine::<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>::new()
}
}
// Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin
// merging the batch. This means it is a good time to perform amortized work proportional
// to the size of batch.
fn insert(&mut self, batch: Self::Batch) {
self.spine.insert(batch)
}
fn close(&mut self) {
self.spine.close()
}
}
///
#[derive(Debug, Abomonation)]
pub struct GraphBatch<N> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
desc: Description<Product<RootTimestamp,()>>,
}
impl<N> BatchReader<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Cursor = GraphCursor;
fn cursor(&self) -> Self::Cursor { GraphCursor { key: self.index as Node, key_pos: 0, val_pos: 0 } }
fn len(&self) -> usize { self.edges.len() }
fn description(&self) -> &Description<Product<RootTimestamp,()>> { &self.desc }
}
impl<N> Batch<Node, N, Product<RootTimestamp,()>, isize> for GraphBatch<N> where N: Ord+Clone+'static {
type Batcher = MergeBatcher<Node, N, Product<RootTimestamp,()>, isize, Self>;
type Builder = GraphBuilder<N>;
type Merger = GraphMerger;
fn begin_merge(&self, other: &Self) -> Self::Merger {
GraphMerger::new(self, other)
}
}
///
pub struct GraphMerger { }
impl<N> Merger<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphMerger where N: Ord+Clone+'static {
fn new(_batch1: &GraphBatch<N>, _batch2: &GraphBatch<N>) -> Self {
panic!("Cannot merge GraphBatch; they are static");
}
fn done(self) -> GraphBatch<N> {
panic!("Cannot merge GraphBatch; they are static");
}
fn work(&mut self, _source1: &GraphBatch<N>, _source2: &GraphBatch<N>, _frontier: &Option<Vec<Product<RootTimestamp,()>>>, _fuel: &mut usize) {
panic!("Cannot merge GraphBatch; they are static");
}
}
/// A cursor for navigating a single layer.
#[derive(Debug)]
pub struct GraphCursor {
key: Node,
key_pos: usize,
val_pos: usize,
}
impl<N> Cursor<Node, N, Product<RootTimestamp,()>, isize> for GraphCursor where N: Ord+Clone {
type Storage = GraphBatch<N>;
fn key<'a>(&self, storage: &'a Self::Storage) -> &'a Node { &storage.keys[self.key_pos] }
fn
|
<'a>(&self, storage: &'a Self::Storage) -> &'a N { &storage.edges[self.val_pos] }
fn map_times<L: FnMut(&Product<RootTimestamp,()>, isize)>(&mut self, _storage: &Self::Storage, mut logic: L) {
logic(&Product::new(RootTimestamp, ()), 1);
}
fn key_valid(&self, storage: &Self::Storage) -> bool { (self.key_pos + 1) < storage.nodes.len() }
fn val_valid(&self, storage: &Self::Storage) -> bool {
self.val_pos < storage.nodes[self.key_pos + 1]
}
fn step_key(&mut self, storage: &Self::Storage){
if self.key_valid(storage) {
self.key_pos += 1;
self.key += storage.peers as Node;
}
}
fn seek_key(&mut self, storage: &Self::Storage, key: &Node) {
if self.key_valid(storage) {
self.key_pos = (*key as usize) / storage.peers;
if self.key_pos + 1 >= storage.nodes.len() {
self.key_pos = storage.nodes.len() - 1;
}
self.val_pos = storage.nodes[self.key_pos];
self.key = (storage.peers * self.key_pos + storage.index) as Node;
}
}
fn step_val(&mut self, storage: &Self::Storage) {
if self.val_valid(storage) {
self.val_pos += 1;
}
}
fn seek_val(&mut self, storage: &Self::Storage, val: &N) {
if self.val_valid(storage) {
let lower = self.val_pos;
let upper = storage.nodes[self.key_pos + 1];
self.val_pos += advance(&storage.edges[lower.. upper], |tuple| tuple < val);
}
}
fn rewind_keys(&mut self, storage: &Self::Storage) { self.key_pos = 0; self.key = storage.index as Node; }
fn rewind_vals(&mut self, storage: &Self::Storage) {
if self.key_valid(storage) {
self.val_pos = storage.nodes[self.key_pos];
}
}
}
/// A builder for creating layers from unsorted update tuples.
pub struct GraphBuilder<N: Ord> {
index: usize,
peers: usize,
keys: Vec<Node>,
nodes: Vec<usize>,
edges: Vec<N>,
}
impl<N> Builder<Node, N, Product<RootTimestamp,()>, isize, GraphBatch<N>> for GraphBuilder<N> where N: Ord+Clone+'static {
fn new() -> Self { Self::with_capacity(0) }
fn with_capacity(cap: usize) -> Self {
GraphBuilder {
index: 0,
peers: 1,
keys: Vec::new(),
nodes: Vec::new(),
edges: Vec::with_capacity(cap),
}
}
#[inline]
fn push(&mut self, (key, val, _time, _diff): (Node, N, Product<RootTimestamp,()>, isize)) {
while self.nodes.len() <= (key as usize) / self.peers {
self.keys.push((self.peers * self.nodes.len() + self.index) as Node);
self.nodes.push(self.edges.len());
}
self.edges.push(val);
}
#[inline(never)]
fn done(mut self, lower: &[Product<RootTimestamp,()>], upper: &[Product<RootTimestamp,()>], since: &[Product<RootTimestamp,()>]) -> GraphBatch<N> {
println!("GraphBuilder::done(): {} nodes, {} edges.", self.nodes.len(), self.edges.len());
self.nodes.push(self.edges.len());
GraphBatch {
index: self.index,
peers: self.peers,
keys: self.keys,
nodes: self.nodes,
edges: self.edges,
desc: Description::new(lower, upper, since)
}
}
}
/// Reports the number of elements satisfing the predicate.
///
/// This methods *relies strongly* on the assumption that the predicate
/// stays false once it becomes false, a joint property of the predicate
/// and the slice. This allows `advance` to use exponential search to
/// count the number of elements in time logarithmic in the result.
#[inline(never)]
pub fn advance<T, F: Fn(&T)->bool>(slice: &[T], function: F) -> usize {
// start with no advance
let mut index = 0;
if index < slice.len() && function(&slice[index]) {
// advance in exponentially growing steps.
let mut step = 1;
while index + step < slice.len() && function(&slice[index + step]) {
index += step;
step = step << 1;
}
// advance in exponentially shrinking steps.
step = step >> 1;
while step > 0 {
if index + step < slice.len() && function(&slice[index + step]) {
index += step;
}
step = step >> 1;
}
index += 1;
}
index
}
|
val
|
identifier_name
|
tmux.rs
|
use fastup::{Document, Node};
use fastup::Node::*;
use color::Color888;
use std::fmt;
#[derive(Debug, Copy, Clone, Default)]
pub struct Renderer;
impl super::Renderer for Renderer {
fn render(&self, doc: &Document) -> String {
let env = Environment::default();
tmux_from_document(doc, &env) + "#[default]"
}
}
#[derive(Debug, Copy, Clone, Default)]
struct Environment {
foreground: Option<Color888>,
background: Option<Color888>,
bold: bool,
}
impl<'a> From<&'a Environment> for String {
fn from(env: &'a Environment) -> Self {
let mut style = "#[default".to_string();
if let Some(color) = env.foreground
|
if let Some(color) = env.background {
style += &format!(",bg=#{}", color);
}
if env.bold {
style += &format!(",bold");
}
style += "]";
style
}
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", String::from(self))
}
}
fn tmux_from_document(doc: &Document, env: &Environment) -> String {
doc.0.iter().map(|node| tmux_from_node(node, env)).collect()
}
fn tmux_from_node(node: &Node, env: &Environment) -> String {
match *node {
Text(ref text) => format!("{}{}", env, escape_tmux_format(text)),
Foreground(color, ref doc) => {
let env = Environment { foreground: Some(color.clamp_to_888()),..*env };
tmux_from_document(doc, &env)
}
Background(color, ref doc) => {
let env = Environment { background: Some(color.clamp_to_888()),..*env };
tmux_from_document(doc, &env)
}
Bold(ref doc) => {
let env = Environment { bold: true,..*env };
tmux_from_document(doc, &env)
}
Widget(..) => unreachable!(),
}
}
fn escape_tmux_format(text: &str) -> String {
text.replace("#", "###[]")
}
|
{
style += &format!(",fg=#{}", color);
}
|
conditional_block
|
tmux.rs
|
use fastup::{Document, Node};
use fastup::Node::*;
use color::Color888;
use std::fmt;
#[derive(Debug, Copy, Clone, Default)]
pub struct Renderer;
impl super::Renderer for Renderer {
fn render(&self, doc: &Document) -> String {
let env = Environment::default();
tmux_from_document(doc, &env) + "#[default]"
}
}
#[derive(Debug, Copy, Clone, Default)]
struct Environment {
foreground: Option<Color888>,
background: Option<Color888>,
bold: bool,
}
impl<'a> From<&'a Environment> for String {
fn from(env: &'a Environment) -> Self {
let mut style = "#[default".to_string();
if let Some(color) = env.foreground {
style += &format!(",fg=#{}", color);
}
if let Some(color) = env.background {
style += &format!(",bg=#{}", color);
}
if env.bold {
|
style += &format!(",bold");
}
style += "]";
style
}
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", String::from(self))
}
}
fn tmux_from_document(doc: &Document, env: &Environment) -> String {
doc.0.iter().map(|node| tmux_from_node(node, env)).collect()
}
fn tmux_from_node(node: &Node, env: &Environment) -> String {
match *node {
Text(ref text) => format!("{}{}", env, escape_tmux_format(text)),
Foreground(color, ref doc) => {
let env = Environment { foreground: Some(color.clamp_to_888()),..*env };
tmux_from_document(doc, &env)
}
Background(color, ref doc) => {
let env = Environment { background: Some(color.clamp_to_888()),..*env };
tmux_from_document(doc, &env)
}
Bold(ref doc) => {
let env = Environment { bold: true,..*env };
tmux_from_document(doc, &env)
}
Widget(..) => unreachable!(),
}
}
fn escape_tmux_format(text: &str) -> String {
text.replace("#", "###[]")
}
|
random_line_split
|
|
tmux.rs
|
use fastup::{Document, Node};
use fastup::Node::*;
use color::Color888;
use std::fmt;
#[derive(Debug, Copy, Clone, Default)]
pub struct Renderer;
impl super::Renderer for Renderer {
fn render(&self, doc: &Document) -> String {
let env = Environment::default();
tmux_from_document(doc, &env) + "#[default]"
}
}
#[derive(Debug, Copy, Clone, Default)]
struct Environment {
foreground: Option<Color888>,
background: Option<Color888>,
bold: bool,
}
impl<'a> From<&'a Environment> for String {
fn
|
(env: &'a Environment) -> Self {
let mut style = "#[default".to_string();
if let Some(color) = env.foreground {
style += &format!(",fg=#{}", color);
}
if let Some(color) = env.background {
style += &format!(",bg=#{}", color);
}
if env.bold {
style += &format!(",bold");
}
style += "]";
style
}
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", String::from(self))
}
}
fn tmux_from_document(doc: &Document, env: &Environment) -> String {
doc.0.iter().map(|node| tmux_from_node(node, env)).collect()
}
fn tmux_from_node(node: &Node, env: &Environment) -> String {
match *node {
Text(ref text) => format!("{}{}", env, escape_tmux_format(text)),
Foreground(color, ref doc) => {
let env = Environment { foreground: Some(color.clamp_to_888()),..*env };
tmux_from_document(doc, &env)
}
Background(color, ref doc) => {
let env = Environment { background: Some(color.clamp_to_888()),..*env };
tmux_from_document(doc, &env)
}
Bold(ref doc) => {
let env = Environment { bold: true,..*env };
tmux_from_document(doc, &env)
}
Widget(..) => unreachable!(),
}
}
fn escape_tmux_format(text: &str) -> String {
text.replace("#", "###[]")
}
|
from
|
identifier_name
|
htmliframeelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_str_as_empty};
use dom::document::AbstractDocument;
use dom::element::HTMLIframeElementTypeId;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Node, ScriptView};
use dom::windowproxy::WindowProxy;
use geom::size::Size2D;
use geom::rect::Rect;
use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg, PipelineId, SubpageId};
use std::ascii::StrAsciiExt;
use std::comm::ChanOne;
use extra::url::Url;
use std::util::replace;
enum SandboxAllowance {
AllowNothing = 0x00,
AllowSameOrigin = 0x01,
AllowTopNavigation = 0x02,
AllowForms = 0x04,
AllowScripts = 0x08,
AllowPointerLock = 0x10,
AllowPopups = 0x20
}
pub struct HTMLIFrameElement {
htmlelement: HTMLElement,
frame: Option<Url>,
size: Option<IFrameSize>,
sandbox: Option<u8>
}
struct IFrameSize {
pipeline_id: PipelineId,
subpage_id: SubpageId,
future_chan: Option<ChanOne<Size2D<uint>>>,
constellation_chan: ConstellationChan,
}
impl IFrameSize {
pub fn set_rect(&mut self, rect: Rect<f32>) {
let future_chan = replace(&mut self.future_chan, None);
do future_chan.map |future_chan| {
let Size2D { width, height } = rect.size;
future_chan.send(Size2D(width as uint, height as uint));
};
self.constellation_chan.send(FrameRectMsg(self.pipeline_id, self.subpage_id, rect));
}
}
impl HTMLIFrameElement {
pub fn is_sandboxed(&self) -> bool {
self.sandbox.is_some()
}
}
impl HTMLIFrameElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLIFrameElement {
HTMLIFrameElement {
htmlelement: HTMLElement::new(HTMLIframeElementTypeId, localName, document),
frame: None,
size: None,
sandbox: None,
}
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode<ScriptView> {
let element = HTMLIFrameElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLIFrameElementBinding::Wrap)
}
}
impl HTMLIFrameElement {
pub fn Src(&self) -> DOMString {
None
}
pub fn SetSrc(&mut self, _src: &DOMString) -> ErrorResult
|
pub fn Srcdoc(&self) -> DOMString {
None
}
pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Sandbox(&self, _abstract_self: AbstractNode<ScriptView>) -> DOMString {
self.htmlelement.element.GetAttribute(&Some(~"sandbox"))
}
pub fn SetSandbox(&mut self, abstract_self: AbstractNode<ScriptView>, sandbox: &DOMString) {
self.htmlelement.element.SetAttribute(abstract_self, &Some(~"sandbox"), sandbox);
}
pub fn AfterSetAttr(&mut self, name: &DOMString, value: &DOMString) {
let name = null_str_as_empty(name);
if "sandbox" == name {
let mut modes = AllowNothing as u8;
let words = null_str_as_empty(value);
for word in words.split_iter(' ') {
modes |= match word.to_ascii_lower().as_slice() {
"allow-same-origin" => AllowSameOrigin,
"allow-forms" => AllowForms,
"allow-pointer-lock" => AllowPointerLock,
"allow-popups" => AllowPopups,
"allow-scripts" => AllowScripts,
"allow-top-navigation" => AllowTopNavigation,
_ => AllowNothing
} as u8;
}
self.sandbox = Some(modes);
}
}
pub fn AllowFullscreen(&self) -> bool {
false
}
pub fn SetAllowFullscreen(&mut self, _allow: bool) -> ErrorResult {
Ok(())
}
pub fn Width(&self) -> DOMString {
None
}
pub fn SetWidth(&mut self, _width: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Height(&self) -> DOMString {
None
}
pub fn SetHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn GetContentDocument(&self) -> Option<AbstractDocument> {
None
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&mut self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Scrolling(&self) -> DOMString {
None
}
pub fn SetScrolling(&mut self, _scrolling: &DOMString) -> ErrorResult {
Ok(())
}
pub fn FrameBorder(&self) -> DOMString {
None
}
pub fn SetFrameBorder(&mut self, _frameborder: &DOMString) -> ErrorResult {
Ok(())
}
pub fn LongDesc(&self) -> DOMString {
None
}
pub fn SetLongDesc(&mut self, _longdesc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _marginheight: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _marginwidth: &DOMString) -> ErrorResult {
Ok(())
}
pub fn GetSVGDocument(&self) -> Option<AbstractDocument> {
None
}
}
|
{
Ok(())
}
|
identifier_body
|
htmliframeelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_str_as_empty};
use dom::document::AbstractDocument;
use dom::element::HTMLIframeElementTypeId;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Node, ScriptView};
use dom::windowproxy::WindowProxy;
use geom::size::Size2D;
use geom::rect::Rect;
use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg, PipelineId, SubpageId};
use std::ascii::StrAsciiExt;
use std::comm::ChanOne;
use extra::url::Url;
use std::util::replace;
enum SandboxAllowance {
AllowNothing = 0x00,
AllowSameOrigin = 0x01,
AllowTopNavigation = 0x02,
AllowForms = 0x04,
AllowScripts = 0x08,
AllowPointerLock = 0x10,
AllowPopups = 0x20
}
pub struct HTMLIFrameElement {
htmlelement: HTMLElement,
frame: Option<Url>,
size: Option<IFrameSize>,
sandbox: Option<u8>
}
struct IFrameSize {
pipeline_id: PipelineId,
subpage_id: SubpageId,
future_chan: Option<ChanOne<Size2D<uint>>>,
constellation_chan: ConstellationChan,
}
impl IFrameSize {
pub fn set_rect(&mut self, rect: Rect<f32>) {
let future_chan = replace(&mut self.future_chan, None);
do future_chan.map |future_chan| {
let Size2D { width, height } = rect.size;
future_chan.send(Size2D(width as uint, height as uint));
};
self.constellation_chan.send(FrameRectMsg(self.pipeline_id, self.subpage_id, rect));
}
}
impl HTMLIFrameElement {
pub fn is_sandboxed(&self) -> bool {
self.sandbox.is_some()
}
}
impl HTMLIFrameElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLIFrameElement {
HTMLIFrameElement {
htmlelement: HTMLElement::new(HTMLIframeElementTypeId, localName, document),
frame: None,
size: None,
sandbox: None,
}
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode<ScriptView> {
let element = HTMLIFrameElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLIFrameElementBinding::Wrap)
}
}
impl HTMLIFrameElement {
pub fn Src(&self) -> DOMString {
None
}
pub fn SetSrc(&mut self, _src: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Srcdoc(&self) -> DOMString {
None
}
pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Sandbox(&self, _abstract_self: AbstractNode<ScriptView>) -> DOMString {
self.htmlelement.element.GetAttribute(&Some(~"sandbox"))
}
pub fn SetSandbox(&mut self, abstract_self: AbstractNode<ScriptView>, sandbox: &DOMString) {
self.htmlelement.element.SetAttribute(abstract_self, &Some(~"sandbox"), sandbox);
}
pub fn AfterSetAttr(&mut self, name: &DOMString, value: &DOMString) {
let name = null_str_as_empty(name);
if "sandbox" == name {
let mut modes = AllowNothing as u8;
let words = null_str_as_empty(value);
for word in words.split_iter(' ') {
modes |= match word.to_ascii_lower().as_slice() {
"allow-same-origin" => AllowSameOrigin,
"allow-forms" => AllowForms,
"allow-pointer-lock" => AllowPointerLock,
"allow-popups" => AllowPopups,
"allow-scripts" => AllowScripts,
"allow-top-navigation" => AllowTopNavigation,
_ => AllowNothing
} as u8;
}
self.sandbox = Some(modes);
}
}
pub fn AllowFullscreen(&self) -> bool {
false
}
pub fn
|
(&mut self, _allow: bool) -> ErrorResult {
Ok(())
}
pub fn Width(&self) -> DOMString {
None
}
pub fn SetWidth(&mut self, _width: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Height(&self) -> DOMString {
None
}
pub fn SetHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn GetContentDocument(&self) -> Option<AbstractDocument> {
None
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&mut self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Scrolling(&self) -> DOMString {
None
}
pub fn SetScrolling(&mut self, _scrolling: &DOMString) -> ErrorResult {
Ok(())
}
pub fn FrameBorder(&self) -> DOMString {
None
}
pub fn SetFrameBorder(&mut self, _frameborder: &DOMString) -> ErrorResult {
Ok(())
}
pub fn LongDesc(&self) -> DOMString {
None
}
pub fn SetLongDesc(&mut self, _longdesc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _marginheight: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _marginwidth: &DOMString) -> ErrorResult {
Ok(())
}
pub fn GetSVGDocument(&self) -> Option<AbstractDocument> {
None
}
}
|
SetAllowFullscreen
|
identifier_name
|
htmliframeelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::HTMLIFrameElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_str_as_empty};
use dom::document::AbstractDocument;
use dom::element::HTMLIframeElementTypeId;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Node, ScriptView};
use dom::windowproxy::WindowProxy;
use geom::size::Size2D;
use geom::rect::Rect;
use servo_msg::constellation_msg::{ConstellationChan, FrameRectMsg, PipelineId, SubpageId};
use std::ascii::StrAsciiExt;
use std::comm::ChanOne;
use extra::url::Url;
use std::util::replace;
enum SandboxAllowance {
AllowNothing = 0x00,
AllowSameOrigin = 0x01,
AllowTopNavigation = 0x02,
AllowForms = 0x04,
AllowScripts = 0x08,
AllowPointerLock = 0x10,
AllowPopups = 0x20
}
pub struct HTMLIFrameElement {
htmlelement: HTMLElement,
frame: Option<Url>,
size: Option<IFrameSize>,
sandbox: Option<u8>
}
struct IFrameSize {
pipeline_id: PipelineId,
subpage_id: SubpageId,
future_chan: Option<ChanOne<Size2D<uint>>>,
constellation_chan: ConstellationChan,
}
impl IFrameSize {
pub fn set_rect(&mut self, rect: Rect<f32>) {
let future_chan = replace(&mut self.future_chan, None);
do future_chan.map |future_chan| {
let Size2D { width, height } = rect.size;
future_chan.send(Size2D(width as uint, height as uint));
};
self.constellation_chan.send(FrameRectMsg(self.pipeline_id, self.subpage_id, rect));
}
}
impl HTMLIFrameElement {
pub fn is_sandboxed(&self) -> bool {
self.sandbox.is_some()
}
}
impl HTMLIFrameElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLIFrameElement {
HTMLIFrameElement {
htmlelement: HTMLElement::new(HTMLIframeElementTypeId, localName, document),
frame: None,
size: None,
sandbox: None,
}
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode<ScriptView> {
let element = HTMLIFrameElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLIFrameElementBinding::Wrap)
}
}
impl HTMLIFrameElement {
pub fn Src(&self) -> DOMString {
None
}
pub fn SetSrc(&mut self, _src: &DOMString) -> ErrorResult {
Ok(())
}
|
pub fn Srcdoc(&self) -> DOMString {
None
}
pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Name(&self) -> DOMString {
None
}
pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Sandbox(&self, _abstract_self: AbstractNode<ScriptView>) -> DOMString {
self.htmlelement.element.GetAttribute(&Some(~"sandbox"))
}
pub fn SetSandbox(&mut self, abstract_self: AbstractNode<ScriptView>, sandbox: &DOMString) {
self.htmlelement.element.SetAttribute(abstract_self, &Some(~"sandbox"), sandbox);
}
pub fn AfterSetAttr(&mut self, name: &DOMString, value: &DOMString) {
let name = null_str_as_empty(name);
if "sandbox" == name {
let mut modes = AllowNothing as u8;
let words = null_str_as_empty(value);
for word in words.split_iter(' ') {
modes |= match word.to_ascii_lower().as_slice() {
"allow-same-origin" => AllowSameOrigin,
"allow-forms" => AllowForms,
"allow-pointer-lock" => AllowPointerLock,
"allow-popups" => AllowPopups,
"allow-scripts" => AllowScripts,
"allow-top-navigation" => AllowTopNavigation,
_ => AllowNothing
} as u8;
}
self.sandbox = Some(modes);
}
}
pub fn AllowFullscreen(&self) -> bool {
false
}
pub fn SetAllowFullscreen(&mut self, _allow: bool) -> ErrorResult {
Ok(())
}
pub fn Width(&self) -> DOMString {
None
}
pub fn SetWidth(&mut self, _width: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Height(&self) -> DOMString {
None
}
pub fn SetHeight(&mut self, _height: &DOMString) -> ErrorResult {
Ok(())
}
pub fn GetContentDocument(&self) -> Option<AbstractDocument> {
None
}
pub fn GetContentWindow(&self) -> Option<@mut WindowProxy> {
None
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&mut self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Scrolling(&self) -> DOMString {
None
}
pub fn SetScrolling(&mut self, _scrolling: &DOMString) -> ErrorResult {
Ok(())
}
pub fn FrameBorder(&self) -> DOMString {
None
}
pub fn SetFrameBorder(&mut self, _frameborder: &DOMString) -> ErrorResult {
Ok(())
}
pub fn LongDesc(&self) -> DOMString {
None
}
pub fn SetLongDesc(&mut self, _longdesc: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginHeight(&self) -> DOMString {
None
}
pub fn SetMarginHeight(&mut self, _marginheight: &DOMString) -> ErrorResult {
Ok(())
}
pub fn MarginWidth(&self) -> DOMString {
None
}
pub fn SetMarginWidth(&mut self, _marginwidth: &DOMString) -> ErrorResult {
Ok(())
}
pub fn GetSVGDocument(&self) -> Option<AbstractDocument> {
None
}
}
|
random_line_split
|
|
capture.rs
|
fn main()
|
// that. Immediately borrows `count`.
//
// A `mut` is required on `inc` because a `&mut` is stored inside.
// Thus, calling the closure mutates the closure which requires
// a `mut`.
let mut inc = || {
count += 1;
println!("`count`: {}", count);
};
// Call the closure.
inc();
inc();
//let reborrow = &mut count;
// ^ TODO: try uncommenting this line.
// A non-copy type.
let movable = Box::new(3);
// `mem::drop` requires `T` so this must take by value. A copy type
// would copy into the closure leaving the original untouched.
// A non-copy must move and so `movable` immediately moves into
// the closure.
let consume = || {
println!("`movable`: {:?}", movable);
mem::drop(movable);
};
// `consume` consumes the variable so this can only be called once.
consume();
//consume();
// ^ TODO: Try uncommenting this line.
}
|
{
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
// impose anything more restrictive.
let print = || println!("`color`: {}", color);
// Call the closure using the borrow.
print();
print();
let mut count = 0;
// A closure to increment `count` could take either `&mut count`
// or `count` but `&mut count` is less restrictive so it takes
|
identifier_body
|
capture.rs
|
fn
|
() {
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
// impose anything more restrictive.
let print = || println!("`color`: {}", color);
// Call the closure using the borrow.
print();
print();
let mut count = 0;
// A closure to increment `count` could take either `&mut count`
// or `count` but `&mut count` is less restrictive so it takes
// that. Immediately borrows `count`.
//
// A `mut` is required on `inc` because a `&mut` is stored inside.
// Thus, calling the closure mutates the closure which requires
// a `mut`.
let mut inc = || {
count += 1;
println!("`count`: {}", count);
};
// Call the closure.
inc();
inc();
//let reborrow = &mut count;
// ^ TODO: try uncommenting this line.
// A non-copy type.
let movable = Box::new(3);
// `mem::drop` requires `T` so this must take by value. A copy type
// would copy into the closure leaving the original untouched.
// A non-copy must move and so `movable` immediately moves into
// the closure.
let consume = || {
println!("`movable`: {:?}", movable);
mem::drop(movable);
};
// `consume` consumes the variable so this can only be called once.
consume();
//consume();
// ^ TODO: Try uncommenting this line.
}
|
main
|
identifier_name
|
capture.rs
|
fn main() {
use std::mem;
let color = "green";
// A closure to print `color` which immediately borrows (`&`)
// `color` and stores the borrow and closure in the `print`
// variable. It will remain borrowed until `print` goes out of
// scope. `println!` only requires `by reference` so it doesn't
// impose anything more restrictive.
let print = || println!("`color`: {}", color);
// Call the closure using the borrow.
print();
print();
let mut count = 0;
// A closure to increment `count` could take either `&mut count`
// or `count` but `&mut count` is less restrictive so it takes
// that. Immediately borrows `count`.
//
// A `mut` is required on `inc` because a `&mut` is stored inside.
// Thus, calling the closure mutates the closure which requires
// a `mut`.
let mut inc = || {
count += 1;
println!("`count`: {}", count);
};
// Call the closure.
inc();
inc();
//let reborrow = &mut count;
// ^ TODO: try uncommenting this line.
// A non-copy type.
let movable = Box::new(3);
// `mem::drop` requires `T` so this must take by value. A copy type
// would copy into the closure leaving the original untouched.
// A non-copy must move and so `movable` immediately moves into
// the closure.
let consume = || {
println!("`movable`: {:?}", movable);
mem::drop(movable);
};
// `consume` consumes the variable so this can only be called once.
consume();
|
//consume();
// ^ TODO: Try uncommenting this line.
}
|
random_line_split
|
|
mod.rs
|
/*!
Test supports module.
*/
#![allow(dead_code)]
use glium::{self, glutin};
use glium::backend::Facade;
use glium::index::PrimitiveType;
use std::env;
/// Builds a display for tests.
#[cfg(not(feature = "test_headless"))]
pub fn build_display() -> glium::Display {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
glium::Display::new(wb, cb, &event_loop).unwrap()
}
/// Builds a headless display for tests.
#[cfg(feature = "test_headless")]
pub fn build_display() -> glium::HeadlessRenderer {
let version = parse_version();
let hrb = glutin::HeadlessRendererBuilder::new(1024, 768)
.with_gl_debug_flag(true)
.with_gl(version)
.build()
.unwrap();
glium::HeadlessRenderer::new(hrb).unwrap()
}
/// Rebuilds an existing display.
///
/// In real applications this is used for things such as switching to fullscreen. Some things are
/// invalidated during a rebuild, and this has to be handled by glium.
pub fn rebuild_display(display: &glium::Display) {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
display.rebuild(wb, cb, &event_loop).unwrap();
}
fn parse_version() -> glutin::GlRequest {
match env::var("GLIUM_GL_VERSION") {
Ok(version) => {
// expects "OpenGL 3.3" for example
let mut iter = version.rsplitn(2,'');
let version = iter.next().unwrap();
let ty = iter.next().unwrap();
let mut iter = version.split('.');
let major = iter.next().unwrap().parse().unwrap();
let minor = iter.next().unwrap().parse().unwrap();
let ty = if ty == "OpenGL" {
glutin::Api::OpenGl
} else if ty == "OpenGL ES" {
glutin::Api::OpenGlEs
} else if ty == "WebGL" {
glutin::Api::WebGl
} else {
panic!();
};
glutin::GlRequest::Specific(ty, (major, minor))
},
Err(_) => glutin::GlRequest::Latest,
}
}
/// Builds a 2x2 unicolor texture.
pub fn build_unicolor_texture2d<F:?Sized>(facade: &F, red: f32, green: f32, blue: f32)
-> glium::Texture2d where F: Facade
{
let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);
glium::texture::Texture2d::new(facade, vec![
vec![color, color],
vec![color, color],
]).unwrap()
}
/// Builds a vertex buffer, index buffer, and program, to draw red `(1.0, 0.0, 0.0, 1.0)` to the whole screen.
pub fn build_fullscreen_red_pipeline<F:?Sized>(facade: &F) -> (glium::vertex::VertexBufferAny,
glium::index::IndexBufferAny, glium::Program) where F: Facade
{
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
(
glium::VertexBuffer::new(facade, &[
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).unwrap().into(),
glium::IndexBuffer::new(facade, PrimitiveType::TriangleStrip, &[0u8, 1, 2, 3]).unwrap().into(),
program!(facade,
110 => {
vertex: "
#version 110
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment: "
#version 110
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
},
100 => {
vertex: "
#version 100
attribute lowp vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment: "
#version 100
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
},
).unwrap()
)
}
/// Builds a vertex buffer and an index buffer corresponding to a rectangle.
///
/// The vertex buffer has the "position" attribute of type "vec2".
pub fn build_rectangle_vb_ib<F:?Sized>(facade: &F)
-> (glium::vertex::VertexBufferAny, glium::index::IndexBufferAny) where F: Facade
{
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
(
glium::VertexBuffer::new(facade, &[
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).unwrap().into(),
glium::IndexBuffer::new(facade, PrimitiveType::TriangleStrip, &[0u8, 1, 2, 3]).unwrap().into(),
)
}
/// Builds a texture suitable for rendering.
pub fn build_renderable_texture<F:?Sized>(facade: &F) -> glium::Texture2d where F: Facade
|
{
glium::Texture2d::empty(facade, 1024, 1024).unwrap()
}
|
identifier_body
|
|
mod.rs
|
/*!
Test supports module.
*/
#![allow(dead_code)]
use glium::{self, glutin};
use glium::backend::Facade;
use glium::index::PrimitiveType;
use std::env;
/// Builds a display for tests.
#[cfg(not(feature = "test_headless"))]
pub fn build_display() -> glium::Display {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
glium::Display::new(wb, cb, &event_loop).unwrap()
}
/// Builds a headless display for tests.
#[cfg(feature = "test_headless")]
pub fn build_display() -> glium::HeadlessRenderer {
let version = parse_version();
let hrb = glutin::HeadlessRendererBuilder::new(1024, 768)
.with_gl_debug_flag(true)
.with_gl(version)
.build()
.unwrap();
glium::HeadlessRenderer::new(hrb).unwrap()
}
/// Rebuilds an existing display.
///
/// In real applications this is used for things such as switching to fullscreen. Some things are
/// invalidated during a rebuild, and this has to be handled by glium.
pub fn
|
(display: &glium::Display) {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
display.rebuild(wb, cb, &event_loop).unwrap();
}
fn parse_version() -> glutin::GlRequest {
match env::var("GLIUM_GL_VERSION") {
Ok(version) => {
// expects "OpenGL 3.3" for example
let mut iter = version.rsplitn(2,'');
let version = iter.next().unwrap();
let ty = iter.next().unwrap();
let mut iter = version.split('.');
let major = iter.next().unwrap().parse().unwrap();
let minor = iter.next().unwrap().parse().unwrap();
let ty = if ty == "OpenGL" {
glutin::Api::OpenGl
} else if ty == "OpenGL ES" {
glutin::Api::OpenGlEs
} else if ty == "WebGL" {
glutin::Api::WebGl
} else {
panic!();
};
glutin::GlRequest::Specific(ty, (major, minor))
},
Err(_) => glutin::GlRequest::Latest,
}
}
/// Builds a 2x2 unicolor texture.
pub fn build_unicolor_texture2d<F:?Sized>(facade: &F, red: f32, green: f32, blue: f32)
-> glium::Texture2d where F: Facade
{
let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);
glium::texture::Texture2d::new(facade, vec![
vec![color, color],
vec![color, color],
]).unwrap()
}
/// Builds a vertex buffer, index buffer, and program, to draw red `(1.0, 0.0, 0.0, 1.0)` to the whole screen.
pub fn build_fullscreen_red_pipeline<F:?Sized>(facade: &F) -> (glium::vertex::VertexBufferAny,
glium::index::IndexBufferAny, glium::Program) where F: Facade
{
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
(
glium::VertexBuffer::new(facade, &[
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).unwrap().into(),
glium::IndexBuffer::new(facade, PrimitiveType::TriangleStrip, &[0u8, 1, 2, 3]).unwrap().into(),
program!(facade,
110 => {
vertex: "
#version 110
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment: "
#version 110
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
},
100 => {
vertex: "
#version 100
attribute lowp vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment: "
#version 100
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
},
).unwrap()
)
}
/// Builds a vertex buffer and an index buffer corresponding to a rectangle.
///
/// The vertex buffer has the "position" attribute of type "vec2".
pub fn build_rectangle_vb_ib<F:?Sized>(facade: &F)
-> (glium::vertex::VertexBufferAny, glium::index::IndexBufferAny) where F: Facade
{
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
(
glium::VertexBuffer::new(facade, &[
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).unwrap().into(),
glium::IndexBuffer::new(facade, PrimitiveType::TriangleStrip, &[0u8, 1, 2, 3]).unwrap().into(),
)
}
/// Builds a texture suitable for rendering.
pub fn build_renderable_texture<F:?Sized>(facade: &F) -> glium::Texture2d where F: Facade {
glium::Texture2d::empty(facade, 1024, 1024).unwrap()
}
|
rebuild_display
|
identifier_name
|
mod.rs
|
/*!
Test supports module.
*/
#![allow(dead_code)]
use glium::{self, glutin};
use glium::backend::Facade;
use glium::index::PrimitiveType;
use std::env;
/// Builds a display for tests.
#[cfg(not(feature = "test_headless"))]
pub fn build_display() -> glium::Display {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
glium::Display::new(wb, cb, &event_loop).unwrap()
}
/// Builds a headless display for tests.
#[cfg(feature = "test_headless")]
pub fn build_display() -> glium::HeadlessRenderer {
let version = parse_version();
let hrb = glutin::HeadlessRendererBuilder::new(1024, 768)
.with_gl_debug_flag(true)
.with_gl(version)
.build()
.unwrap();
glium::HeadlessRenderer::new(hrb).unwrap()
}
/// Rebuilds an existing display.
///
/// In real applications this is used for things such as switching to fullscreen. Some things are
/// invalidated during a rebuild, and this has to be handled by glium.
pub fn rebuild_display(display: &glium::Display) {
let version = parse_version();
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new().with_visible(false);
let cb = glutin::ContextBuilder::new()
.with_gl_debug_flag(true)
.with_gl(version);
display.rebuild(wb, cb, &event_loop).unwrap();
}
fn parse_version() -> glutin::GlRequest {
match env::var("GLIUM_GL_VERSION") {
Ok(version) => {
// expects "OpenGL 3.3" for example
let mut iter = version.rsplitn(2,'');
let version = iter.next().unwrap();
let ty = iter.next().unwrap();
let mut iter = version.split('.');
let major = iter.next().unwrap().parse().unwrap();
let minor = iter.next().unwrap().parse().unwrap();
let ty = if ty == "OpenGL" {
glutin::Api::OpenGl
} else if ty == "OpenGL ES" {
glutin::Api::OpenGlEs
} else if ty == "WebGL" {
glutin::Api::WebGl
} else {
panic!();
};
glutin::GlRequest::Specific(ty, (major, minor))
},
|
pub fn build_unicolor_texture2d<F:?Sized>(facade: &F, red: f32, green: f32, blue: f32)
-> glium::Texture2d where F: Facade
{
let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8);
glium::texture::Texture2d::new(facade, vec![
vec![color, color],
vec![color, color],
]).unwrap()
}
/// Builds a vertex buffer, index buffer, and program, to draw red `(1.0, 0.0, 0.0, 1.0)` to the whole screen.
pub fn build_fullscreen_red_pipeline<F:?Sized>(facade: &F) -> (glium::vertex::VertexBufferAny,
glium::index::IndexBufferAny, glium::Program) where F: Facade
{
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
(
glium::VertexBuffer::new(facade, &[
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).unwrap().into(),
glium::IndexBuffer::new(facade, PrimitiveType::TriangleStrip, &[0u8, 1, 2, 3]).unwrap().into(),
program!(facade,
110 => {
vertex: "
#version 110
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment: "
#version 110
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
},
100 => {
vertex: "
#version 100
attribute lowp vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
",
fragment: "
#version 100
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
",
},
).unwrap()
)
}
/// Builds a vertex buffer and an index buffer corresponding to a rectangle.
///
/// The vertex buffer has the "position" attribute of type "vec2".
pub fn build_rectangle_vb_ib<F:?Sized>(facade: &F)
-> (glium::vertex::VertexBufferAny, glium::index::IndexBufferAny) where F: Facade
{
#[derive(Copy, Clone)]
struct Vertex {
position: [f32; 2],
}
implement_vertex!(Vertex, position);
(
glium::VertexBuffer::new(facade, &[
Vertex { position: [-1.0, 1.0] }, Vertex { position: [1.0, 1.0] },
Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
]).unwrap().into(),
glium::IndexBuffer::new(facade, PrimitiveType::TriangleStrip, &[0u8, 1, 2, 3]).unwrap().into(),
)
}
/// Builds a texture suitable for rendering.
pub fn build_renderable_texture<F:?Sized>(facade: &F) -> glium::Texture2d where F: Facade {
glium::Texture2d::empty(facade, 1024, 1024).unwrap()
}
|
Err(_) => glutin::GlRequest::Latest,
}
}
/// Builds a 2x2 unicolor texture.
|
random_line_split
|
in_flight_requests.rs
|
use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
/// Requests already written to the wire that haven't yet received responses.
#[derive(Debug)]
pub struct InFlightRequests<Resp> {
request_data: FnvHashMap<u64, RequestData<Resp>>,
deadlines: DelayQueue<u64>,
}
impl<Resp> Default for InFlightRequests<Resp> {
fn default() -> Self {
Self {
request_data: Default::default(),
deadlines: Default::default(),
}
}
}
#[derive(Debug)]
struct RequestData<Resp> {
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
/// The key to remove the timer for the request's deadline.
deadline_key: delay_queue::Key,
}
/// An error returned when an attempt is made to insert a request with an ID that is already in
/// use.
#[derive(Debug)]
pub struct AlreadyExistsError;
impl<Resp> InFlightRequests<Resp> {
/// Returns the number of in-flight requests.
pub fn len(&self) -> usize {
self.request_data.len()
}
/// Returns true iff there are no requests in flight.
pub fn is_empty(&self) -> bool {
self.request_data.is_empty()
}
/// Starts a request, unless a request with the same ID is already in flight.
pub fn insert_request(
&mut self,
request_id: u64,
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
) -> Result<(), AlreadyExistsError> {
match self.request_data.entry(request_id) {
hash_map::Entry::Vacant(vacant) => {
let timeout = ctx.deadline.time_until();
trace!(
"[{}] Queuing request with timeout {:?}.",
ctx.trace_id(),
timeout,
);
let deadline_key = self.deadlines.insert(request_id, timeout);
vacant.insert(RequestData {
ctx,
response_completion,
deadline_key,
});
Ok(())
}
hash_map::Entry::Occupied(_) => Err(AlreadyExistsError),
}
}
/// Removes a request without aborting. Returns true iff the request was found.
pub fn complete_request(&mut self, response: Response<Resp>) -> bool {
if let Some(request_data) = self.request_data.remove(&response.request_id)
|
debug!(
"No in-flight request found for request_id = {}.",
response.request_id
);
// If the response completion was absent, then the request was already canceled.
false
}
/// Cancels a request without completing (typically used when a request handle was dropped
/// before the request completed).
pub fn cancel_request(&mut self, request_id: u64) -> Option<context::Context> {
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
trace!("[{}] Cancelling request.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
Some(request_data.ctx)
} else {
None
}
}
/// Yields a request that has expired, completing it with a TimedOut error.
/// The caller should send cancellation messages for any yielded request ID.
pub fn poll_expired(&mut self, cx: &mut Context) -> PollIo<u64> {
Poll::Ready(match ready!(self.deadlines.poll_expired(cx)) {
Some(Ok(expired)) => {
let request_id = expired.into_inner();
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
request_data.complete(Self::deadline_exceeded_error(request_id));
}
Some(Ok(request_id))
}
Some(Err(e)) => Some(Err(io::Error::new(io::ErrorKind::Other, e))),
None => None,
})
}
fn deadline_exceeded_error(request_id: u64) -> Response<Resp> {
Response {
request_id,
message: Err(ServerError {
kind: io::ErrorKind::TimedOut,
detail: Some("Client dropped expired request.".to_string()),
}),
}
}
}
/// When InFlightRequests is dropped, any outstanding requests are completed with a
/// deadline-exceeded error.
impl<Resp> Drop for InFlightRequests<Resp> {
fn drop(&mut self) {
let deadlines = &mut self.deadlines;
for (_, request_data) in self.request_data.drain() {
let expired = deadlines.remove(&request_data.deadline_key);
request_data.complete(Self::deadline_exceeded_error(expired.into_inner()));
}
}
}
impl<Resp> RequestData<Resp> {
fn complete(self, response: Response<Resp>) {
let _ = self.response_completion.send(response);
}
}
|
{
self.request_data.compact(0.1);
trace!("[{}] Received response.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
request_data.complete(response);
return true;
}
|
conditional_block
|
in_flight_requests.rs
|
use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
/// Requests already written to the wire that haven't yet received responses.
#[derive(Debug)]
pub struct InFlightRequests<Resp> {
request_data: FnvHashMap<u64, RequestData<Resp>>,
deadlines: DelayQueue<u64>,
}
impl<Resp> Default for InFlightRequests<Resp> {
fn default() -> Self {
Self {
request_data: Default::default(),
deadlines: Default::default(),
}
}
}
#[derive(Debug)]
struct RequestData<Resp> {
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
/// The key to remove the timer for the request's deadline.
deadline_key: delay_queue::Key,
}
/// An error returned when an attempt is made to insert a request with an ID that is already in
/// use.
#[derive(Debug)]
pub struct AlreadyExistsError;
impl<Resp> InFlightRequests<Resp> {
/// Returns the number of in-flight requests.
pub fn len(&self) -> usize {
self.request_data.len()
}
/// Returns true iff there are no requests in flight.
pub fn is_empty(&self) -> bool {
self.request_data.is_empty()
}
/// Starts a request, unless a request with the same ID is already in flight.
pub fn insert_request(
&mut self,
request_id: u64,
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
) -> Result<(), AlreadyExistsError> {
match self.request_data.entry(request_id) {
hash_map::Entry::Vacant(vacant) => {
let timeout = ctx.deadline.time_until();
trace!(
"[{}] Queuing request with timeout {:?}.",
ctx.trace_id(),
timeout,
);
let deadline_key = self.deadlines.insert(request_id, timeout);
vacant.insert(RequestData {
ctx,
response_completion,
deadline_key,
});
Ok(())
}
hash_map::Entry::Occupied(_) => Err(AlreadyExistsError),
}
}
/// Removes a request without aborting. Returns true iff the request was found.
pub fn complete_request(&mut self, response: Response<Resp>) -> bool {
if let Some(request_data) = self.request_data.remove(&response.request_id) {
self.request_data.compact(0.1);
trace!("[{}] Received response.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
request_data.complete(response);
return true;
}
debug!(
"No in-flight request found for request_id = {}.",
response.request_id
);
// If the response completion was absent, then the request was already canceled.
false
}
/// Cancels a request without completing (typically used when a request handle was dropped
/// before the request completed).
pub fn cancel_request(&mut self, request_id: u64) -> Option<context::Context> {
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
trace!("[{}] Cancelling request.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
Some(request_data.ctx)
} else {
None
}
}
/// Yields a request that has expired, completing it with a TimedOut error.
/// The caller should send cancellation messages for any yielded request ID.
pub fn poll_expired(&mut self, cx: &mut Context) -> PollIo<u64> {
Poll::Ready(match ready!(self.deadlines.poll_expired(cx)) {
Some(Ok(expired)) => {
let request_id = expired.into_inner();
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
request_data.complete(Self::deadline_exceeded_error(request_id));
}
Some(Ok(request_id))
}
Some(Err(e)) => Some(Err(io::Error::new(io::ErrorKind::Other, e))),
None => None,
})
}
fn deadline_exceeded_error(request_id: u64) -> Response<Resp> {
Response {
request_id,
message: Err(ServerError {
kind: io::ErrorKind::TimedOut,
detail: Some("Client dropped expired request.".to_string()),
}),
}
}
}
/// When InFlightRequests is dropped, any outstanding requests are completed with a
/// deadline-exceeded error.
impl<Resp> Drop for InFlightRequests<Resp> {
fn drop(&mut self) {
let deadlines = &mut self.deadlines;
for (_, request_data) in self.request_data.drain() {
let expired = deadlines.remove(&request_data.deadline_key);
request_data.complete(Self::deadline_exceeded_error(expired.into_inner()));
}
}
}
impl<Resp> RequestData<Resp> {
fn complete(self, response: Response<Resp>)
|
}
|
{
let _ = self.response_completion.send(response);
}
|
identifier_body
|
in_flight_requests.rs
|
use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
/// Requests already written to the wire that haven't yet received responses.
#[derive(Debug)]
pub struct InFlightRequests<Resp> {
request_data: FnvHashMap<u64, RequestData<Resp>>,
deadlines: DelayQueue<u64>,
}
impl<Resp> Default for InFlightRequests<Resp> {
fn default() -> Self {
Self {
request_data: Default::default(),
deadlines: Default::default(),
}
}
}
#[derive(Debug)]
struct RequestData<Resp> {
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
/// The key to remove the timer for the request's deadline.
deadline_key: delay_queue::Key,
}
/// An error returned when an attempt is made to insert a request with an ID that is already in
/// use.
#[derive(Debug)]
pub struct AlreadyExistsError;
impl<Resp> InFlightRequests<Resp> {
/// Returns the number of in-flight requests.
pub fn len(&self) -> usize {
self.request_data.len()
}
/// Returns true iff there are no requests in flight.
pub fn is_empty(&self) -> bool {
self.request_data.is_empty()
}
/// Starts a request, unless a request with the same ID is already in flight.
|
) -> Result<(), AlreadyExistsError> {
match self.request_data.entry(request_id) {
hash_map::Entry::Vacant(vacant) => {
let timeout = ctx.deadline.time_until();
trace!(
"[{}] Queuing request with timeout {:?}.",
ctx.trace_id(),
timeout,
);
let deadline_key = self.deadlines.insert(request_id, timeout);
vacant.insert(RequestData {
ctx,
response_completion,
deadline_key,
});
Ok(())
}
hash_map::Entry::Occupied(_) => Err(AlreadyExistsError),
}
}
/// Removes a request without aborting. Returns true iff the request was found.
pub fn complete_request(&mut self, response: Response<Resp>) -> bool {
if let Some(request_data) = self.request_data.remove(&response.request_id) {
self.request_data.compact(0.1);
trace!("[{}] Received response.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
request_data.complete(response);
return true;
}
debug!(
"No in-flight request found for request_id = {}.",
response.request_id
);
// If the response completion was absent, then the request was already canceled.
false
}
/// Cancels a request without completing (typically used when a request handle was dropped
/// before the request completed).
pub fn cancel_request(&mut self, request_id: u64) -> Option<context::Context> {
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
trace!("[{}] Cancelling request.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
Some(request_data.ctx)
} else {
None
}
}
/// Yields a request that has expired, completing it with a TimedOut error.
/// The caller should send cancellation messages for any yielded request ID.
pub fn poll_expired(&mut self, cx: &mut Context) -> PollIo<u64> {
Poll::Ready(match ready!(self.deadlines.poll_expired(cx)) {
Some(Ok(expired)) => {
let request_id = expired.into_inner();
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
request_data.complete(Self::deadline_exceeded_error(request_id));
}
Some(Ok(request_id))
}
Some(Err(e)) => Some(Err(io::Error::new(io::ErrorKind::Other, e))),
None => None,
})
}
fn deadline_exceeded_error(request_id: u64) -> Response<Resp> {
Response {
request_id,
message: Err(ServerError {
kind: io::ErrorKind::TimedOut,
detail: Some("Client dropped expired request.".to_string()),
}),
}
}
}
/// When InFlightRequests is dropped, any outstanding requests are completed with a
/// deadline-exceeded error.
impl<Resp> Drop for InFlightRequests<Resp> {
fn drop(&mut self) {
let deadlines = &mut self.deadlines;
for (_, request_data) in self.request_data.drain() {
let expired = deadlines.remove(&request_data.deadline_key);
request_data.complete(Self::deadline_exceeded_error(expired.into_inner()));
}
}
}
impl<Resp> RequestData<Resp> {
fn complete(self, response: Response<Resp>) {
let _ = self.response_completion.send(response);
}
}
|
pub fn insert_request(
&mut self,
request_id: u64,
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
|
random_line_split
|
in_flight_requests.rs
|
use crate::{
context,
util::{Compact, TimeUntil},
PollIo, Response, ServerError,
};
use fnv::FnvHashMap;
use futures::ready;
use log::{debug, trace};
use std::{
collections::hash_map,
io,
task::{Context, Poll},
};
use tokio::sync::oneshot;
use tokio_util::time::delay_queue::{self, DelayQueue};
/// Requests already written to the wire that haven't yet received responses.
#[derive(Debug)]
pub struct InFlightRequests<Resp> {
request_data: FnvHashMap<u64, RequestData<Resp>>,
deadlines: DelayQueue<u64>,
}
impl<Resp> Default for InFlightRequests<Resp> {
fn default() -> Self {
Self {
request_data: Default::default(),
deadlines: Default::default(),
}
}
}
#[derive(Debug)]
struct RequestData<Resp> {
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
/// The key to remove the timer for the request's deadline.
deadline_key: delay_queue::Key,
}
/// An error returned when an attempt is made to insert a request with an ID that is already in
/// use.
#[derive(Debug)]
pub struct AlreadyExistsError;
impl<Resp> InFlightRequests<Resp> {
/// Returns the number of in-flight requests.
pub fn len(&self) -> usize {
self.request_data.len()
}
/// Returns true iff there are no requests in flight.
pub fn is_empty(&self) -> bool {
self.request_data.is_empty()
}
/// Starts a request, unless a request with the same ID is already in flight.
pub fn insert_request(
&mut self,
request_id: u64,
ctx: context::Context,
response_completion: oneshot::Sender<Response<Resp>>,
) -> Result<(), AlreadyExistsError> {
match self.request_data.entry(request_id) {
hash_map::Entry::Vacant(vacant) => {
let timeout = ctx.deadline.time_until();
trace!(
"[{}] Queuing request with timeout {:?}.",
ctx.trace_id(),
timeout,
);
let deadline_key = self.deadlines.insert(request_id, timeout);
vacant.insert(RequestData {
ctx,
response_completion,
deadline_key,
});
Ok(())
}
hash_map::Entry::Occupied(_) => Err(AlreadyExistsError),
}
}
/// Removes a request without aborting. Returns true iff the request was found.
pub fn
|
(&mut self, response: Response<Resp>) -> bool {
if let Some(request_data) = self.request_data.remove(&response.request_id) {
self.request_data.compact(0.1);
trace!("[{}] Received response.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
request_data.complete(response);
return true;
}
debug!(
"No in-flight request found for request_id = {}.",
response.request_id
);
// If the response completion was absent, then the request was already canceled.
false
}
/// Cancels a request without completing (typically used when a request handle was dropped
/// before the request completed).
pub fn cancel_request(&mut self, request_id: u64) -> Option<context::Context> {
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
trace!("[{}] Cancelling request.", request_data.ctx.trace_id());
self.deadlines.remove(&request_data.deadline_key);
Some(request_data.ctx)
} else {
None
}
}
/// Yields a request that has expired, completing it with a TimedOut error.
/// The caller should send cancellation messages for any yielded request ID.
pub fn poll_expired(&mut self, cx: &mut Context) -> PollIo<u64> {
Poll::Ready(match ready!(self.deadlines.poll_expired(cx)) {
Some(Ok(expired)) => {
let request_id = expired.into_inner();
if let Some(request_data) = self.request_data.remove(&request_id) {
self.request_data.compact(0.1);
request_data.complete(Self::deadline_exceeded_error(request_id));
}
Some(Ok(request_id))
}
Some(Err(e)) => Some(Err(io::Error::new(io::ErrorKind::Other, e))),
None => None,
})
}
fn deadline_exceeded_error(request_id: u64) -> Response<Resp> {
Response {
request_id,
message: Err(ServerError {
kind: io::ErrorKind::TimedOut,
detail: Some("Client dropped expired request.".to_string()),
}),
}
}
}
/// When InFlightRequests is dropped, any outstanding requests are completed with a
/// deadline-exceeded error.
impl<Resp> Drop for InFlightRequests<Resp> {
fn drop(&mut self) {
let deadlines = &mut self.deadlines;
for (_, request_data) in self.request_data.drain() {
let expired = deadlines.remove(&request_data.deadline_key);
request_data.complete(Self::deadline_exceeded_error(expired.into_inner()));
}
}
}
impl<Resp> RequestData<Resp> {
fn complete(self, response: Response<Resp>) {
let _ = self.response_completion.send(response);
}
}
|
complete_request
|
identifier_name
|
match-value-binding-in-guard-3291.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.
fn foo(x: Option<Box<int>>, b: bool) -> int {
match x {
None => { 1 }
Some(ref x) if b => { *x.clone() }
Some(_) => { 0 }
}
}
pub fn main() {
foo(Some(box 22), true);
foo(Some(box 22), false);
|
foo(None, true);
foo(None, false);
}
|
random_line_split
|
|
match-value-binding-in-guard-3291.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.
fn
|
(x: Option<Box<int>>, b: bool) -> int {
match x {
None => { 1 }
Some(ref x) if b => { *x.clone() }
Some(_) => { 0 }
}
}
pub fn main() {
foo(Some(box 22), true);
foo(Some(box 22), false);
foo(None, true);
foo(None, false);
}
|
foo
|
identifier_name
|
match-value-binding-in-guard-3291.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.
fn foo(x: Option<Box<int>>, b: bool) -> int
|
pub fn main() {
foo(Some(box 22), true);
foo(Some(box 22), false);
foo(None, true);
foo(None, false);
}
|
{
match x {
None => { 1 }
Some(ref x) if b => { *x.clone() }
Some(_) => { 0 }
}
}
|
identifier_body
|
connection.rs
|
.query_pairs()
.into_iter()
.filter(|&(ref key, _)| key == "db")
.next()
{
Some((_, db)) => unwrap_or!(
db.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
None => 0,
},
passwd: url.password().and_then(|pw| Some(pw.to_string())),
})
}
#[cfg(not(unix))]
fn url_to_unix_connection_info(_: url::Url) -> RedisResult<ConnectionInfo> {
fail!((
ErrorKind::InvalidClientConfig,
"Unix sockets are not available on this platform."
));
}
impl IntoConnectionInfo for url::Url {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
if self.scheme() == "redis" {
url_to_tcp_connection_info(self)
} else if self.scheme() == "unix" || self.scheme() == "redis+unix" {
url_to_unix_connection_info(self)
} else {
fail!((
ErrorKind::InvalidClientConfig,
"URL provided is not a redis URL"
));
}
}
}
struct TcpConnection {
reader: BufReader<TcpStream>,
open: bool,
}
#[cfg(unix)]
struct UnixConnection {
sock: BufReader<UnixStream>,
open: bool,
}
enum ActualConnection {
Tcp(TcpConnection),
#[cfg(unix)]
Unix(UnixConnection),
}
/// Represents a stateful redis TCP connection.
pub struct Connection {
con: ActualConnection,
db: i64,
/// Flag indicating whether the connection was left in the PubSub state after dropping `PubSub`.
///
/// This flag is checked when attempting to send a command, and if it's raised, we attempt to
/// exit the pubsub state before executing the new request.
pubsub: bool,
}
/// Represents a pubsub connection.
pub struct PubSub<'a> {
con: &'a mut Connection,
}
/// Represents a pubsub message.
pub struct Msg {
payload: Value,
channel: Value,
pattern: Option<Value>,
}
impl ActualConnection {
pub fn new(addr: &ConnectionAddr) -> RedisResult<ActualConnection> {
Ok(match *addr {
ConnectionAddr::Tcp(ref host, ref port) => {
let host: &str = &*host;
let tcp = TcpStream::connect((host, *port))?;
let buffered = BufReader::new(tcp);
ActualConnection::Tcp(TcpConnection {
reader: buffered,
open: true,
})
}
#[cfg(unix)]
ConnectionAddr::Unix(ref path) => ActualConnection::Unix(UnixConnection {
sock: BufReader::new(UnixStream::connect(path)?),
open: true,
}),
#[cfg(not(unix))]
ConnectionAddr::Unix(ref path) => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot connect to unix sockets \
on this platform"
));
}
})
}
pub fn send_bytes(&mut self, bytes: &[u8]) -> RedisResult<Value> {
match *self {
ActualConnection::Tcp(ref mut connection) => {
let res = connection
.reader
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match res {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let result = connection
.sock
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match result {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
}
}
pub fn read_response(&mut self) -> RedisResult<Value> {
let result = Parser::new(match *self {
ActualConnection::Tcp(TcpConnection { ref mut reader,.. }) => reader as &mut BufRead,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref mut sock,.. }) => sock as &mut BufRead,
})
.parse_value();
// shutdown connection on protocol error
match result {
Err(ref e) if e.kind() == ErrorKind::ResponseError => match *self {
ActualConnection::Tcp(ref mut connection) => {
let _ = connection.reader.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let _ = connection.sock.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
},
_ => (),
}
result
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_write_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_write_timeout(dur)?;
}
}
Ok(())
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_read_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_read_timeout(dur)?;
}
}
Ok(())
}
pub fn is_open(&self) -> bool {
match *self {
ActualConnection::Tcp(TcpConnection { open,.. }) => open,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { open,.. }) => open,
}
}
}
pub fn connect(connection_info: &ConnectionInfo) -> RedisResult<Connection> {
let con = ActualConnection::new(&connection_info.addr)?;
let mut rv = Connection {
con: con,
db: connection_info.db,
pubsub: false,
};
match connection_info.passwd {
Some(ref passwd) => match cmd("AUTH").arg(&**passwd).query::<Value>(&mut rv) {
Ok(Value::Okay) => {}
_ => {
fail!((
ErrorKind::AuthenticationFailed,
"Password authentication failed"
));
}
},
None => {}
}
if connection_info.db!= 0 {
match cmd("SELECT")
.arg(connection_info.db)
.query::<Value>(&mut rv)
{
Ok(Value::Okay) => {}
_ => fail!((
ErrorKind::ResponseError,
"Redis server refused to switch database"
)),
}
}
Ok(rv)
}
/// Implements the "stateless" part of the connection interface that is used by the
/// different objects in redis-rs. Primarily it obviously applies to `Connection`
/// object but also some other objects implement the interface (for instance
/// whole clients or certain redis results).
///
/// Generally clients and connections (as well as redis results of those) implement
/// this trait. Actual connections provide more functionality which can be used
/// to implement things like `PubSub` but they also can modify the intrinsic
/// state of the TCP connection. This is not possible with `ConnectionLike`
/// implementors because that functionality is not exposed.
pub trait ConnectionLike {
/// Sends an already encoded (packed) command into the TCP socket and
/// reads the single response from it.
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value>;
/// Sends multiple already encoded (packed) command into the TCP socket
/// and reads `count` responses from it. This is used to implement
/// pipelining.
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>>;
/// Returns the database this connection is bound to. Note that this
/// information might be unreliable because it's initially cached and
/// also might be incorrect if the connection like object is not
/// actually connected.
fn get_db(&self) -> i64;
}
/// A connection is an object that represents a single redis connection. It
/// provides basic support for sending encoded commands into a redis connection
/// and to read a response from it. It's bound to a single database and can
/// only be created from the client.
///
/// You generally do not much with this object other than passing it to
/// `Cmd` objects.
impl Connection {
/// Sends an already encoded (packed) command into the TCP socket and
/// does not read a response. This is useful for commands like
/// `MONITOR` which yield multiple items. This needs to be used with
/// care because it changes the state of the connection.
pub fn send_packed_command(&mut self, cmd: &[u8]) -> RedisResult<()> {
self.con.send_bytes(cmd)?;
Ok(())
}
/// Fetches a single response from the connection. This is useful
/// if used in combination with `send_packed_command`.
pub fn recv_response(&mut self) -> RedisResult<Value> {
self.con.read_response()
}
/// Sets the write timeout for the connection.
///
/// If the provided value is `None`, then `send_packed_command` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_write_timeout(dur)
}
/// Sets the read timeout for the connection.
///
/// If the provided value is `None`, then `recv_response` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_read_timeout(dur)
}
pub fn as_pubsub<'a>(&'a mut self) -> PubSub<'a> {
// NOTE: The pubsub flag is intentionally not raised at this time since running commands
// within the pubsub state should not try and exit from the pubsub state.
PubSub::new(self)
}
fn exit_pubsub(&mut self) -> RedisResult<()> {
let res = self.clear_active_subscriptions();
if res.is_ok() {
self.pubsub = false;
} else {
// Raise the pubsub flag to indicate the connection is "stuck" in that state.
self.pubsub = true;
}
res
}
/// Get the inner connection out of a PubSub
///
/// Any active subscriptions are unsubscribed. In the event of an error, the connection is
/// dropped.
fn clear_active_subscriptions(&mut self) -> RedisResult<()> {
// Responses to unsubscribe commands return in a 3-tuple with values
// ("unsubscribe" or "punsubscribe", name of subscription removed, count of remaining subs).
// The "count of remaining subs" includes both pattern subscriptions and non pattern
// subscriptions. Thus, to accurately drain all unsubscribe messages received from the
// server, both commands need to be executed at once.
{
// Prepare both unsubscribe commands
let unsubscribe = cmd("UNSUBSCRIBE").get_packed_command();
let punsubscribe = cmd("PUNSUBSCRIBE").get_packed_command();
// Grab a reference to the underlying connection so that we may send
// the commands without immediately blocking for a response.
let con = &mut self.con;
// Execute commands
con.send_bytes(&unsubscribe)?;
con.send_bytes(&punsubscribe)?;
}
// Receive responses
//
// There will be at minimum two responses - 1 for each of punsubscribe and unsubscribe
// commands. There may be more responses if there are active subscriptions. In this case,
// messages are received until the _subscription count_ in the responses reach zero.
let mut received_unsub = false;
let mut received_punsub = false;
loop {
let res: (Vec<u8>, (), isize) = from_redis_value(&self.recv_response()?)?;
match res.0.first().map(|v| *v) {
Some(b'u') => received_unsub = true,
Some(b'p') => received_punsub = true,
_ => (),
}
if received_unsub && received_punsub && res.2 == 0 {
break;
}
}
// Finally, the connection is back in its normal state since all subscriptions were
// cancelled *and* all unsubscribe messages were received.
Ok(())
}
/// Returns the connection status.
///
/// The connection is open until any `read_response` call recieved an
/// invalid response from the server (most likely a closed or dropped
/// connection, otherwise a Redis protocol error). When using unix
/// sockets the connection is open until writing a command failed with a
/// `BrokenPipe` error.
pub fn is_open(&self) -> bool {
self.con.is_open()
}
}
impl ConnectionLike for Connection {
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
con.read_response()
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
let mut rv = vec![];
for idx in 0..(offset + count) {
let item = con.read_response()?;
if idx >= offset {
rv.push(item);
}
}
Ok(rv)
}
fn get_db(&self) -> i64 {
self.db
}
}
/// The pubsub object provides convenient access to the redis pubsub
/// system. Once created you can subscribe and unsubscribe from channels
/// and listen in on messages.
///
/// Example:
///
/// ```rust,no_run
/// # fn do_something() -> redis::RedisResult<()> {
/// let client = redis::Client::open("redis://127.0.0.1/")?;
/// let mut con = client.get_connection()?;
/// let mut pubsub = con.as_pubsub();
/// pubsub.subscribe("channel_1")?;
/// pubsub.subscribe("channel_2")?;
///
/// loop {
/// let msg = pubsub.get_message()?;
/// let payload : String = msg.get_payload()?;
/// println!("channel '{}': {}", msg.get_channel_name(), payload);
/// }
/// # }
/// ```
impl<'a> PubSub<'a> {
fn new(con: &'a mut Connection) -> Self {
Self { con }
}
/// Subscribes to a new channel.
pub fn subscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("SUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Subscribes to a new channel with a pattern.
pub fn psubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel.
pub fn unsubscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("UNSUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel with a pattern.
pub fn punsubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PUNSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Fetches the next message from the pubsub connection. Blocks until
/// a message becomes available. This currently does not provide a
/// wait not to block :(
///
/// The message itself is still generic and can be converted into an
/// appropriate type through the helper methods on it.
pub fn get_message(&mut self) -> RedisResult<Msg> {
loop {
let raw_msg: Vec<Value> = from_redis_value(&self.con.recv_response()?)?;
let mut iter = raw_msg.into_iter();
let msg_type: String = from_redis_value(&unwrap_or!(iter.next(), continue))?;
let mut pattern = None;
let payload;
let channel;
if msg_type == "message" {
channel = unwrap_or!(iter.next(), continue);
payload = unwrap_or!(iter.next(), continue);
} else if msg_type == "pmessage" {
pattern = Some(unwrap_or!(iter.next(), continue));
channel = unwrap_or!(iter.next(), continue);
payload = unwrap_or!(iter.next(), continue);
} else {
continue;
}
return Ok(Msg {
payload: payload,
channel: channel,
pattern: pattern,
});
}
}
/// Sets the read timeout for the connection.
///
/// If the provided value is `None`, then `get_message` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_read_timeout(dur)
}
}
impl<'a> Drop for PubSub<'a> {
fn drop(&mut self) {
let _ = self.con.exit_pubsub();
}
}
/// This holds the data that comes from listening to a pubsub
/// connection. It only contains actual message data.
impl Msg {
/// Returns the channel this message came on.
pub fn get_channel<T: FromRedisValue>(&self) -> RedisResult<T> {
from_redis_value(&self.channel)
}
/// Convenience method to get a string version of the channel. Unless
/// your channel contains non utf-8 bytes you can always use this
/// method. If the channel is not a valid string (which really should
/// not happen) then the return value is `"?"`.
pub fn get_channel_name(&self) -> &str {
match self.channel {
Value::Data(ref bytes) => from_utf8(bytes).unwrap_or("?"),
_ => "?",
}
}
/// Returns the message's payload in a specific format.
pub fn get_payload<T: FromRedisValue>(&self) -> RedisResult<T> {
from_redis_value(&self.payload)
}
/// Returns the bytes that are the message's payload. This can be used
/// as an alternative to the `get_payload` function if you are interested
/// in the raw bytes in it.
pub fn get_payload_bytes(&self) -> &[u8] {
match self.payload {
Value::Data(ref bytes) => bytes,
_ => b"",
}
}
/// Returns true if the message was constructed from a pattern
/// subscription.
pub fn
|
from_pattern
|
identifier_name
|
|
connection.rs
|
>;
}
impl IntoConnectionInfo for ConnectionInfo {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
Ok(self)
}
}
impl<'a> IntoConnectionInfo for &'a str {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
match parse_redis_url(self) {
Ok(u) => u.into_connection_info(),
Err(_) => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
}
}
}
fn url_to_tcp_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: Box::new(ConnectionAddr::Tcp(
match url.host() {
Some(host) => host.to_string(),
None => fail!((ErrorKind::InvalidClientConfig, "Missing hostname")),
},
url.port().unwrap_or(DEFAULT_PORT),
)),
db: match url.path().trim_matches('/') {
"" => 0,
path => unwrap_or!(
path.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
},
passwd: match url.password() {
Some(pw) => match url::percent_encoding::percent_decode(pw.as_bytes()).decode_utf8() {
Ok(decoded) => Some(decoded.into_owned()),
Err(_) => fail!((
ErrorKind::InvalidClientConfig,
"Password is not valid UTF-8 string"
)),
},
None => None,
},
})
}
#[cfg(unix)]
fn url_to_unix_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: Box::new(ConnectionAddr::Unix(unwrap_or!(
url.to_file_path().ok(),
fail!((ErrorKind::InvalidClientConfig, "Missing path"))
))),
db: match url
.query_pairs()
.into_iter()
.filter(|&(ref key, _)| key == "db")
.next()
{
Some((_, db)) => unwrap_or!(
db.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
None => 0,
},
passwd: url.password().and_then(|pw| Some(pw.to_string())),
})
}
#[cfg(not(unix))]
fn url_to_unix_connection_info(_: url::Url) -> RedisResult<ConnectionInfo> {
fail!((
ErrorKind::InvalidClientConfig,
"Unix sockets are not available on this platform."
));
}
impl IntoConnectionInfo for url::Url {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
if self.scheme() == "redis" {
url_to_tcp_connection_info(self)
} else if self.scheme() == "unix" || self.scheme() == "redis+unix" {
url_to_unix_connection_info(self)
} else {
fail!((
ErrorKind::InvalidClientConfig,
"URL provided is not a redis URL"
));
}
}
}
struct TcpConnection {
reader: BufReader<TcpStream>,
open: bool,
}
#[cfg(unix)]
struct UnixConnection {
sock: BufReader<UnixStream>,
open: bool,
}
enum ActualConnection {
Tcp(TcpConnection),
#[cfg(unix)]
Unix(UnixConnection),
}
/// Represents a stateful redis TCP connection.
pub struct Connection {
con: ActualConnection,
db: i64,
/// Flag indicating whether the connection was left in the PubSub state after dropping `PubSub`.
///
/// This flag is checked when attempting to send a command, and if it's raised, we attempt to
/// exit the pubsub state before executing the new request.
pubsub: bool,
}
/// Represents a pubsub connection.
pub struct PubSub<'a> {
con: &'a mut Connection,
}
/// Represents a pubsub message.
pub struct Msg {
payload: Value,
channel: Value,
pattern: Option<Value>,
}
impl ActualConnection {
pub fn new(addr: &ConnectionAddr) -> RedisResult<ActualConnection> {
Ok(match *addr {
ConnectionAddr::Tcp(ref host, ref port) => {
let host: &str = &*host;
let tcp = TcpStream::connect((host, *port))?;
let buffered = BufReader::new(tcp);
ActualConnection::Tcp(TcpConnection {
reader: buffered,
open: true,
})
}
#[cfg(unix)]
ConnectionAddr::Unix(ref path) => ActualConnection::Unix(UnixConnection {
sock: BufReader::new(UnixStream::connect(path)?),
open: true,
}),
#[cfg(not(unix))]
ConnectionAddr::Unix(ref path) => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot connect to unix sockets \
on this platform"
));
}
})
}
pub fn send_bytes(&mut self, bytes: &[u8]) -> RedisResult<Value> {
match *self {
ActualConnection::Tcp(ref mut connection) => {
let res = connection
.reader
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match res {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let result = connection
.sock
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match result {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
}
}
pub fn read_response(&mut self) -> RedisResult<Value> {
let result = Parser::new(match *self {
ActualConnection::Tcp(TcpConnection { ref mut reader,.. }) => reader as &mut BufRead,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref mut sock,.. }) => sock as &mut BufRead,
})
.parse_value();
// shutdown connection on protocol error
match result {
Err(ref e) if e.kind() == ErrorKind::ResponseError => match *self {
ActualConnection::Tcp(ref mut connection) => {
let _ = connection.reader.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let _ = connection.sock.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
},
_ => (),
}
result
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_write_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_write_timeout(dur)?;
}
}
Ok(())
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_read_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_read_timeout(dur)?;
}
}
Ok(())
}
pub fn is_open(&self) -> bool {
match *self {
ActualConnection::Tcp(TcpConnection { open,.. }) => open,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { open,.. }) => open,
}
}
}
pub fn connect(connection_info: &ConnectionInfo) -> RedisResult<Connection> {
let con = ActualConnection::new(&connection_info.addr)?;
let mut rv = Connection {
con: con,
db: connection_info.db,
pubsub: false,
};
match connection_info.passwd {
Some(ref passwd) => match cmd("AUTH").arg(&**passwd).query::<Value>(&mut rv) {
Ok(Value::Okay) => {}
_ => {
fail!((
ErrorKind::AuthenticationFailed,
"Password authentication failed"
));
}
},
None => {}
}
if connection_info.db!= 0 {
match cmd("SELECT")
.arg(connection_info.db)
.query::<Value>(&mut rv)
{
Ok(Value::Okay) =>
|
_ => fail!((
ErrorKind::ResponseError,
"Redis server refused to switch database"
)),
}
}
Ok(rv)
}
/// Implements the "stateless" part of the connection interface that is used by the
/// different objects in redis-rs. Primarily it obviously applies to `Connection`
/// object but also some other objects implement the interface (for instance
/// whole clients or certain redis results).
///
/// Generally clients and connections (as well as redis results of those) implement
/// this trait. Actual connections provide more functionality which can be used
/// to implement things like `PubSub` but they also can modify the intrinsic
/// state of the TCP connection. This is not possible with `ConnectionLike`
/// implementors because that functionality is not exposed.
pub trait ConnectionLike {
/// Sends an already encoded (packed) command into the TCP socket and
/// reads the single response from it.
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value>;
/// Sends multiple already encoded (packed) command into the TCP socket
/// and reads `count` responses from it. This is used to implement
/// pipelining.
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>>;
/// Returns the database this connection is bound to. Note that this
/// information might be unreliable because it's initially cached and
/// also might be incorrect if the connection like object is not
/// actually connected.
fn get_db(&self) -> i64;
}
/// A connection is an object that represents a single redis connection. It
/// provides basic support for sending encoded commands into a redis connection
/// and to read a response from it. It's bound to a single database and can
/// only be created from the client.
///
/// You generally do not much with this object other than passing it to
/// `Cmd` objects.
impl Connection {
/// Sends an already encoded (packed) command into the TCP socket and
/// does not read a response. This is useful for commands like
/// `MONITOR` which yield multiple items. This needs to be used with
/// care because it changes the state of the connection.
pub fn send_packed_command(&mut self, cmd: &[u8]) -> RedisResult<()> {
self.con.send_bytes(cmd)?;
Ok(())
}
/// Fetches a single response from the connection. This is useful
/// if used in combination with `send_packed_command`.
pub fn recv_response(&mut self) -> RedisResult<Value> {
self.con.read_response()
}
/// Sets the write timeout for the connection.
///
/// If the provided value is `None`, then `send_packed_command` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_write_timeout(dur)
}
/// Sets the read timeout for the connection.
///
/// If the provided value is `None`, then `recv_response` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_read_timeout(dur)
}
pub fn as_pubsub<'a>(&'a mut self) -> PubSub<'a> {
// NOTE: The pubsub flag is intentionally not raised at this time since running commands
// within the pubsub state should not try and exit from the pubsub state.
PubSub::new(self)
}
fn exit_pubsub(&mut self) -> RedisResult<()> {
let res = self.clear_active_subscriptions();
if res.is_ok() {
self.pubsub = false;
} else {
// Raise the pubsub flag to indicate the connection is "stuck" in that state.
self.pubsub = true;
}
res
}
/// Get the inner connection out of a PubSub
///
/// Any active subscriptions are unsubscribed. In the event of an error, the connection is
/// dropped.
fn clear_active_subscriptions(&mut self) -> RedisResult<()> {
// Responses to unsubscribe commands return in a 3-tuple with values
// ("unsubscribe" or "punsubscribe", name of subscription removed, count of remaining subs).
// The "count of remaining subs" includes both pattern subscriptions and non pattern
// subscriptions. Thus, to accurately drain all unsubscribe messages received from the
// server, both commands need to be executed at once.
{
// Prepare both unsubscribe commands
let unsubscribe = cmd("UNSUBSCRIBE").get_packed_command();
let punsubscribe = cmd("PUNSUBSCRIBE").get_packed_command();
// Grab a reference to the underlying connection so that we may send
// the commands without immediately blocking for a response.
let con = &mut self.con;
// Execute commands
con.send_bytes(&unsubscribe)?;
con.send_bytes(&punsubscribe)?;
}
// Receive responses
//
// There will be at minimum two responses - 1 for each of punsubscribe and unsubscribe
// commands. There may be more responses if there are active subscriptions. In this case,
// messages are received until the _subscription count_ in the responses reach zero.
let mut received_unsub = false;
let mut received_punsub = false;
loop {
let res: (Vec<u8>, (), isize) = from_redis_value(&self.recv_response()?)?;
match res.0.first().map(|v| *v) {
Some(b'u') => received_unsub = true,
Some(b'p') => received_punsub = true,
_ => (),
}
if received_unsub && received_punsub && res.2 == 0 {
break;
}
}
// Finally, the connection is back in its normal state since all subscriptions were
// cancelled *and* all unsubscribe messages were received.
Ok(())
}
/// Returns the connection status.
///
/// The connection is open until any `read_response` call recieved an
/// invalid response from the server (most likely a closed or dropped
/// connection, otherwise a Redis protocol error). When using unix
/// sockets the connection is open until writing a command failed with a
/// `BrokenPipe` error.
pub fn is_open(&self) -> bool {
self.con.is_open()
}
}
impl ConnectionLike for Connection {
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
con.read_response()
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
let mut rv = vec![];
for idx in 0..(offset + count) {
let item = con.read_response()?;
if idx >= offset {
rv.push(item);
}
}
Ok(rv)
}
fn get_db(&self) -> i64 {
self.db
}
}
/// The pubsub object provides convenient access to the redis pubsub
/// system. Once created you can subscribe and unsubscribe from channels
/// and listen in on messages.
///
/// Example:
///
/// ```rust,no_run
/// # fn do_something() -> redis::RedisResult<()> {
/// let client = redis::Client::open("redis://127.0.0.1/")?;
/// let mut con = client.get_connection()?;
/// let mut pubsub = con.as_pubsub();
/// pubsub.subscribe("channel_1")?;
/// pubsub.subscribe("channel_2")?;
///
/// loop {
/// let msg = pubsub.get_message()?;
/// let payload : String = msg.get_payload()?;
/// println!("channel '{}': {}", msg.get_channel_name(), payload);
/// }
/// # }
/// ```
impl<'a> PubSub<'a> {
fn new(con: &'a mut Connection) -> Self {
Self { con }
}
/// Subscribes to a new channel.
pub fn subscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("SUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Subscribes to a new channel with a pattern.
pub fn psubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel.
pub fn unsubscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("UNSUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel with a pattern.
pub fn punsubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PUNSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Fetches the next message from the pubsub connection. Blocks until
/// a message becomes available. This currently does not provide a
/// wait not to block :(
///
/// The message itself is still generic and can be converted into an
/// appropriate type through the helper methods on it.
pub fn get_message(&mut self) -> RedisResult<Msg> {
loop {
let raw_msg: Vec<Value> = from_redis_value(&self.con.recv_response()?)?;
let mut iter = raw_msg.into_iter();
let msg_type: String = from_redis_value(&unwrap_or!(iter.next(), continue))?;
let mut pattern = None;
let payload;
let channel;
if msg_type == "message" {
channel = unwrap_or!(iter.next(), continue);
payload = unwrap_or!(iter.next(), continue);
} else if msg_type == "pmessage" {
pattern = Some(unwrap_or!(iter.next(), continue));
channel = unwrap_or!(iter.next(), continue);
|
{}
|
conditional_block
|
connection.rs
|
ConnectionInfo>;
}
impl IntoConnectionInfo for ConnectionInfo {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
Ok(self)
}
}
impl<'a> IntoConnectionInfo for &'a str {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
match parse_redis_url(self) {
Ok(u) => u.into_connection_info(),
Err(_) => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
}
}
}
fn url_to_tcp_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: Box::new(ConnectionAddr::Tcp(
match url.host() {
Some(host) => host.to_string(),
None => fail!((ErrorKind::InvalidClientConfig, "Missing hostname")),
},
url.port().unwrap_or(DEFAULT_PORT),
)),
db: match url.path().trim_matches('/') {
"" => 0,
path => unwrap_or!(
path.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
},
passwd: match url.password() {
Some(pw) => match url::percent_encoding::percent_decode(pw.as_bytes()).decode_utf8() {
Ok(decoded) => Some(decoded.into_owned()),
Err(_) => fail!((
ErrorKind::InvalidClientConfig,
"Password is not valid UTF-8 string"
)),
},
None => None,
},
})
}
#[cfg(unix)]
fn url_to_unix_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: Box::new(ConnectionAddr::Unix(unwrap_or!(
url.to_file_path().ok(),
fail!((ErrorKind::InvalidClientConfig, "Missing path"))
))),
db: match url
.query_pairs()
.into_iter()
.filter(|&(ref key, _)| key == "db")
.next()
{
Some((_, db)) => unwrap_or!(
db.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
None => 0,
},
passwd: url.password().and_then(|pw| Some(pw.to_string())),
})
}
#[cfg(not(unix))]
fn url_to_unix_connection_info(_: url::Url) -> RedisResult<ConnectionInfo> {
fail!((
ErrorKind::InvalidClientConfig,
"Unix sockets are not available on this platform."
));
}
impl IntoConnectionInfo for url::Url {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
if self.scheme() == "redis" {
url_to_tcp_connection_info(self)
} else if self.scheme() == "unix" || self.scheme() == "redis+unix" {
url_to_unix_connection_info(self)
} else {
fail!((
ErrorKind::InvalidClientConfig,
"URL provided is not a redis URL"
));
}
}
}
struct TcpConnection {
reader: BufReader<TcpStream>,
open: bool,
}
#[cfg(unix)]
struct UnixConnection {
sock: BufReader<UnixStream>,
open: bool,
}
enum ActualConnection {
Tcp(TcpConnection),
#[cfg(unix)]
Unix(UnixConnection),
}
/// Represents a stateful redis TCP connection.
pub struct Connection {
con: ActualConnection,
db: i64,
/// Flag indicating whether the connection was left in the PubSub state after dropping `PubSub`.
///
/// This flag is checked when attempting to send a command, and if it's raised, we attempt to
/// exit the pubsub state before executing the new request.
pubsub: bool,
}
/// Represents a pubsub connection.
pub struct PubSub<'a> {
con: &'a mut Connection,
}
/// Represents a pubsub message.
pub struct Msg {
payload: Value,
channel: Value,
pattern: Option<Value>,
}
impl ActualConnection {
pub fn new(addr: &ConnectionAddr) -> RedisResult<ActualConnection> {
Ok(match *addr {
ConnectionAddr::Tcp(ref host, ref port) => {
let host: &str = &*host;
let tcp = TcpStream::connect((host, *port))?;
let buffered = BufReader::new(tcp);
ActualConnection::Tcp(TcpConnection {
reader: buffered,
open: true,
})
}
#[cfg(unix)]
ConnectionAddr::Unix(ref path) => ActualConnection::Unix(UnixConnection {
sock: BufReader::new(UnixStream::connect(path)?),
open: true,
}),
#[cfg(not(unix))]
ConnectionAddr::Unix(ref path) => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot connect to unix sockets \
on this platform"
));
}
})
}
pub fn send_bytes(&mut self, bytes: &[u8]) -> RedisResult<Value> {
match *self {
ActualConnection::Tcp(ref mut connection) => {
let res = connection
.reader
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match res {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let result = connection
.sock
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match result {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
}
}
pub fn read_response(&mut self) -> RedisResult<Value> {
let result = Parser::new(match *self {
ActualConnection::Tcp(TcpConnection { ref mut reader,.. }) => reader as &mut BufRead,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref mut sock,.. }) => sock as &mut BufRead,
})
.parse_value();
// shutdown connection on protocol error
match result {
Err(ref e) if e.kind() == ErrorKind::ResponseError => match *self {
ActualConnection::Tcp(ref mut connection) => {
let _ = connection.reader.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let _ = connection.sock.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
},
_ => (),
}
result
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_write_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_write_timeout(dur)?;
}
}
Ok(())
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_read_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_read_timeout(dur)?;
}
}
|
Ok(())
}
pub fn is_open(&self) -> bool {
match *self {
ActualConnection::Tcp(TcpConnection { open,.. }) => open,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { open,.. }) => open,
}
}
}
pub fn connect(connection_info: &ConnectionInfo) -> RedisResult<Connection> {
let con = ActualConnection::new(&connection_info.addr)?;
let mut rv = Connection {
con: con,
db: connection_info.db,
pubsub: false,
};
match connection_info.passwd {
Some(ref passwd) => match cmd("AUTH").arg(&**passwd).query::<Value>(&mut rv) {
Ok(Value::Okay) => {}
_ => {
fail!((
ErrorKind::AuthenticationFailed,
"Password authentication failed"
));
}
},
None => {}
}
if connection_info.db!= 0 {
match cmd("SELECT")
.arg(connection_info.db)
.query::<Value>(&mut rv)
{
Ok(Value::Okay) => {}
_ => fail!((
ErrorKind::ResponseError,
"Redis server refused to switch database"
)),
}
}
Ok(rv)
}
/// Implements the "stateless" part of the connection interface that is used by the
/// different objects in redis-rs. Primarily it obviously applies to `Connection`
/// object but also some other objects implement the interface (for instance
/// whole clients or certain redis results).
///
/// Generally clients and connections (as well as redis results of those) implement
/// this trait. Actual connections provide more functionality which can be used
/// to implement things like `PubSub` but they also can modify the intrinsic
/// state of the TCP connection. This is not possible with `ConnectionLike`
/// implementors because that functionality is not exposed.
pub trait ConnectionLike {
/// Sends an already encoded (packed) command into the TCP socket and
/// reads the single response from it.
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value>;
/// Sends multiple already encoded (packed) command into the TCP socket
/// and reads `count` responses from it. This is used to implement
/// pipelining.
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>>;
/// Returns the database this connection is bound to. Note that this
/// information might be unreliable because it's initially cached and
/// also might be incorrect if the connection like object is not
/// actually connected.
fn get_db(&self) -> i64;
}
/// A connection is an object that represents a single redis connection. It
/// provides basic support for sending encoded commands into a redis connection
/// and to read a response from it. It's bound to a single database and can
/// only be created from the client.
///
/// You generally do not much with this object other than passing it to
/// `Cmd` objects.
impl Connection {
/// Sends an already encoded (packed) command into the TCP socket and
/// does not read a response. This is useful for commands like
/// `MONITOR` which yield multiple items. This needs to be used with
/// care because it changes the state of the connection.
pub fn send_packed_command(&mut self, cmd: &[u8]) -> RedisResult<()> {
self.con.send_bytes(cmd)?;
Ok(())
}
/// Fetches a single response from the connection. This is useful
/// if used in combination with `send_packed_command`.
pub fn recv_response(&mut self) -> RedisResult<Value> {
self.con.read_response()
}
/// Sets the write timeout for the connection.
///
/// If the provided value is `None`, then `send_packed_command` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_write_timeout(dur)
}
/// Sets the read timeout for the connection.
///
/// If the provided value is `None`, then `recv_response` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_read_timeout(dur)
}
pub fn as_pubsub<'a>(&'a mut self) -> PubSub<'a> {
// NOTE: The pubsub flag is intentionally not raised at this time since running commands
// within the pubsub state should not try and exit from the pubsub state.
PubSub::new(self)
}
fn exit_pubsub(&mut self) -> RedisResult<()> {
let res = self.clear_active_subscriptions();
if res.is_ok() {
self.pubsub = false;
} else {
// Raise the pubsub flag to indicate the connection is "stuck" in that state.
self.pubsub = true;
}
res
}
/// Get the inner connection out of a PubSub
///
/// Any active subscriptions are unsubscribed. In the event of an error, the connection is
/// dropped.
fn clear_active_subscriptions(&mut self) -> RedisResult<()> {
// Responses to unsubscribe commands return in a 3-tuple with values
// ("unsubscribe" or "punsubscribe", name of subscription removed, count of remaining subs).
// The "count of remaining subs" includes both pattern subscriptions and non pattern
// subscriptions. Thus, to accurately drain all unsubscribe messages received from the
// server, both commands need to be executed at once.
{
// Prepare both unsubscribe commands
let unsubscribe = cmd("UNSUBSCRIBE").get_packed_command();
let punsubscribe = cmd("PUNSUBSCRIBE").get_packed_command();
// Grab a reference to the underlying connection so that we may send
// the commands without immediately blocking for a response.
let con = &mut self.con;
// Execute commands
con.send_bytes(&unsubscribe)?;
con.send_bytes(&punsubscribe)?;
}
// Receive responses
//
// There will be at minimum two responses - 1 for each of punsubscribe and unsubscribe
// commands. There may be more responses if there are active subscriptions. In this case,
// messages are received until the _subscription count_ in the responses reach zero.
let mut received_unsub = false;
let mut received_punsub = false;
loop {
let res: (Vec<u8>, (), isize) = from_redis_value(&self.recv_response()?)?;
match res.0.first().map(|v| *v) {
Some(b'u') => received_unsub = true,
Some(b'p') => received_punsub = true,
_ => (),
}
if received_unsub && received_punsub && res.2 == 0 {
break;
}
}
// Finally, the connection is back in its normal state since all subscriptions were
// cancelled *and* all unsubscribe messages were received.
Ok(())
}
/// Returns the connection status.
///
/// The connection is open until any `read_response` call recieved an
/// invalid response from the server (most likely a closed or dropped
/// connection, otherwise a Redis protocol error). When using unix
/// sockets the connection is open until writing a command failed with a
/// `BrokenPipe` error.
pub fn is_open(&self) -> bool {
self.con.is_open()
}
}
impl ConnectionLike for Connection {
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
con.read_response()
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
let mut rv = vec![];
for idx in 0..(offset + count) {
let item = con.read_response()?;
if idx >= offset {
rv.push(item);
}
}
Ok(rv)
}
fn get_db(&self) -> i64 {
self.db
}
}
/// The pubsub object provides convenient access to the redis pubsub
/// system. Once created you can subscribe and unsubscribe from channels
/// and listen in on messages.
///
/// Example:
///
/// ```rust,no_run
/// # fn do_something() -> redis::RedisResult<()> {
/// let client = redis::Client::open("redis://127.0.0.1/")?;
/// let mut con = client.get_connection()?;
/// let mut pubsub = con.as_pubsub();
/// pubsub.subscribe("channel_1")?;
/// pubsub.subscribe("channel_2")?;
///
/// loop {
/// let msg = pubsub.get_message()?;
/// let payload : String = msg.get_payload()?;
/// println!("channel '{}': {}", msg.get_channel_name(), payload);
/// }
/// # }
/// ```
impl<'a> PubSub<'a> {
fn new(con: &'a mut Connection) -> Self {
Self { con }
}
/// Subscribes to a new channel.
pub fn subscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("SUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Subscribes to a new channel with a pattern.
pub fn psubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel.
pub fn unsubscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("UNSUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel with a pattern.
pub fn punsubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PUNSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Fetches the next message from the pubsub connection. Blocks until
/// a message becomes available. This currently does not provide a
/// wait not to block :(
///
/// The message itself is still generic and can be converted into an
/// appropriate type through the helper methods on it.
pub fn get_message(&mut self) -> RedisResult<Msg> {
loop {
let raw_msg: Vec<Value> = from_redis_value(&self.con.recv_response()?)?;
let mut iter = raw_msg.into_iter();
let msg_type: String = from_redis_value(&unwrap_or!(iter.next(), continue))?;
let mut pattern = None;
let payload;
let channel;
if msg_type == "message" {
channel = unwrap_or!(iter.next(), continue);
payload = unwrap_or!(iter.next(), continue);
} else if msg_type == "pmessage" {
pattern = Some(unwrap_or!(iter.next(), continue));
channel = unwrap_or!(iter.next(), continue);
|
random_line_split
|
|
connection.rs
|
>;
}
impl IntoConnectionInfo for ConnectionInfo {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
Ok(self)
}
}
impl<'a> IntoConnectionInfo for &'a str {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
match parse_redis_url(self) {
Ok(u) => u.into_connection_info(),
Err(_) => fail!((ErrorKind::InvalidClientConfig, "Redis URL did not parse")),
}
}
}
fn url_to_tcp_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: Box::new(ConnectionAddr::Tcp(
match url.host() {
Some(host) => host.to_string(),
None => fail!((ErrorKind::InvalidClientConfig, "Missing hostname")),
},
url.port().unwrap_or(DEFAULT_PORT),
)),
db: match url.path().trim_matches('/') {
"" => 0,
path => unwrap_or!(
path.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
},
passwd: match url.password() {
Some(pw) => match url::percent_encoding::percent_decode(pw.as_bytes()).decode_utf8() {
Ok(decoded) => Some(decoded.into_owned()),
Err(_) => fail!((
ErrorKind::InvalidClientConfig,
"Password is not valid UTF-8 string"
)),
},
None => None,
},
})
}
#[cfg(unix)]
fn url_to_unix_connection_info(url: url::Url) -> RedisResult<ConnectionInfo> {
Ok(ConnectionInfo {
addr: Box::new(ConnectionAddr::Unix(unwrap_or!(
url.to_file_path().ok(),
fail!((ErrorKind::InvalidClientConfig, "Missing path"))
))),
db: match url
.query_pairs()
.into_iter()
.filter(|&(ref key, _)| key == "db")
.next()
{
Some((_, db)) => unwrap_or!(
db.parse::<i64>().ok(),
fail!((ErrorKind::InvalidClientConfig, "Invalid database number"))
),
None => 0,
},
passwd: url.password().and_then(|pw| Some(pw.to_string())),
})
}
#[cfg(not(unix))]
fn url_to_unix_connection_info(_: url::Url) -> RedisResult<ConnectionInfo> {
fail!((
ErrorKind::InvalidClientConfig,
"Unix sockets are not available on this platform."
));
}
impl IntoConnectionInfo for url::Url {
fn into_connection_info(self) -> RedisResult<ConnectionInfo> {
if self.scheme() == "redis" {
url_to_tcp_connection_info(self)
} else if self.scheme() == "unix" || self.scheme() == "redis+unix" {
url_to_unix_connection_info(self)
} else {
fail!((
ErrorKind::InvalidClientConfig,
"URL provided is not a redis URL"
));
}
}
}
struct TcpConnection {
reader: BufReader<TcpStream>,
open: bool,
}
#[cfg(unix)]
struct UnixConnection {
sock: BufReader<UnixStream>,
open: bool,
}
enum ActualConnection {
Tcp(TcpConnection),
#[cfg(unix)]
Unix(UnixConnection),
}
/// Represents a stateful redis TCP connection.
pub struct Connection {
con: ActualConnection,
db: i64,
/// Flag indicating whether the connection was left in the PubSub state after dropping `PubSub`.
///
/// This flag is checked when attempting to send a command, and if it's raised, we attempt to
/// exit the pubsub state before executing the new request.
pubsub: bool,
}
/// Represents a pubsub connection.
pub struct PubSub<'a> {
con: &'a mut Connection,
}
/// Represents a pubsub message.
pub struct Msg {
payload: Value,
channel: Value,
pattern: Option<Value>,
}
impl ActualConnection {
pub fn new(addr: &ConnectionAddr) -> RedisResult<ActualConnection> {
Ok(match *addr {
ConnectionAddr::Tcp(ref host, ref port) => {
let host: &str = &*host;
let tcp = TcpStream::connect((host, *port))?;
let buffered = BufReader::new(tcp);
ActualConnection::Tcp(TcpConnection {
reader: buffered,
open: true,
})
}
#[cfg(unix)]
ConnectionAddr::Unix(ref path) => ActualConnection::Unix(UnixConnection {
sock: BufReader::new(UnixStream::connect(path)?),
open: true,
}),
#[cfg(not(unix))]
ConnectionAddr::Unix(ref path) => {
fail!((
ErrorKind::InvalidClientConfig,
"Cannot connect to unix sockets \
on this platform"
));
}
})
}
pub fn send_bytes(&mut self, bytes: &[u8]) -> RedisResult<Value> {
match *self {
ActualConnection::Tcp(ref mut connection) => {
let res = connection
.reader
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match res {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let result = connection
.sock
.get_mut()
.write_all(bytes)
.map_err(|e| RedisError::from(e));
match result {
Err(e) => {
if e.is_connection_dropped() {
connection.open = false;
}
Err(e)
}
Ok(_) => Ok(Value::Okay),
}
}
}
}
pub fn read_response(&mut self) -> RedisResult<Value> {
let result = Parser::new(match *self {
ActualConnection::Tcp(TcpConnection { ref mut reader,.. }) => reader as &mut BufRead,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref mut sock,.. }) => sock as &mut BufRead,
})
.parse_value();
// shutdown connection on protocol error
match result {
Err(ref e) if e.kind() == ErrorKind::ResponseError => match *self {
ActualConnection::Tcp(ref mut connection) => {
let _ = connection.reader.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
#[cfg(unix)]
ActualConnection::Unix(ref mut connection) => {
let _ = connection.sock.get_mut().shutdown(net::Shutdown::Both);
connection.open = false;
}
},
_ => (),
}
result
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_write_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_write_timeout(dur)?;
}
}
Ok(())
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
match *self {
ActualConnection::Tcp(TcpConnection { ref reader,.. }) => {
reader.get_ref().set_read_timeout(dur)?;
}
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { ref sock,.. }) => {
sock.get_ref().set_read_timeout(dur)?;
}
}
Ok(())
}
pub fn is_open(&self) -> bool {
match *self {
ActualConnection::Tcp(TcpConnection { open,.. }) => open,
#[cfg(unix)]
ActualConnection::Unix(UnixConnection { open,.. }) => open,
}
}
}
pub fn connect(connection_info: &ConnectionInfo) -> RedisResult<Connection> {
let con = ActualConnection::new(&connection_info.addr)?;
let mut rv = Connection {
con: con,
db: connection_info.db,
pubsub: false,
};
match connection_info.passwd {
Some(ref passwd) => match cmd("AUTH").arg(&**passwd).query::<Value>(&mut rv) {
Ok(Value::Okay) => {}
_ => {
fail!((
ErrorKind::AuthenticationFailed,
"Password authentication failed"
));
}
},
None => {}
}
if connection_info.db!= 0 {
match cmd("SELECT")
.arg(connection_info.db)
.query::<Value>(&mut rv)
{
Ok(Value::Okay) => {}
_ => fail!((
ErrorKind::ResponseError,
"Redis server refused to switch database"
)),
}
}
Ok(rv)
}
/// Implements the "stateless" part of the connection interface that is used by the
/// different objects in redis-rs. Primarily it obviously applies to `Connection`
/// object but also some other objects implement the interface (for instance
/// whole clients or certain redis results).
///
/// Generally clients and connections (as well as redis results of those) implement
/// this trait. Actual connections provide more functionality which can be used
/// to implement things like `PubSub` but they also can modify the intrinsic
/// state of the TCP connection. This is not possible with `ConnectionLike`
/// implementors because that functionality is not exposed.
pub trait ConnectionLike {
/// Sends an already encoded (packed) command into the TCP socket and
/// reads the single response from it.
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value>;
/// Sends multiple already encoded (packed) command into the TCP socket
/// and reads `count` responses from it. This is used to implement
/// pipelining.
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>>;
/// Returns the database this connection is bound to. Note that this
/// information might be unreliable because it's initially cached and
/// also might be incorrect if the connection like object is not
/// actually connected.
fn get_db(&self) -> i64;
}
/// A connection is an object that represents a single redis connection. It
/// provides basic support for sending encoded commands into a redis connection
/// and to read a response from it. It's bound to a single database and can
/// only be created from the client.
///
/// You generally do not much with this object other than passing it to
/// `Cmd` objects.
impl Connection {
/// Sends an already encoded (packed) command into the TCP socket and
/// does not read a response. This is useful for commands like
/// `MONITOR` which yield multiple items. This needs to be used with
/// care because it changes the state of the connection.
pub fn send_packed_command(&mut self, cmd: &[u8]) -> RedisResult<()> {
self.con.send_bytes(cmd)?;
Ok(())
}
/// Fetches a single response from the connection. This is useful
/// if used in combination with `send_packed_command`.
pub fn recv_response(&mut self) -> RedisResult<Value> {
self.con.read_response()
}
/// Sets the write timeout for the connection.
///
/// If the provided value is `None`, then `send_packed_command` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_write_timeout(&self, dur: Option<Duration>) -> RedisResult<()> {
self.con.set_write_timeout(dur)
}
/// Sets the read timeout for the connection.
///
/// If the provided value is `None`, then `recv_response` call will
/// block indefinitely. It is an error to pass the zero `Duration` to this
/// method.
pub fn set_read_timeout(&self, dur: Option<Duration>) -> RedisResult<()>
|
pub fn as_pubsub<'a>(&'a mut self) -> PubSub<'a> {
// NOTE: The pubsub flag is intentionally not raised at this time since running commands
// within the pubsub state should not try and exit from the pubsub state.
PubSub::new(self)
}
fn exit_pubsub(&mut self) -> RedisResult<()> {
let res = self.clear_active_subscriptions();
if res.is_ok() {
self.pubsub = false;
} else {
// Raise the pubsub flag to indicate the connection is "stuck" in that state.
self.pubsub = true;
}
res
}
/// Get the inner connection out of a PubSub
///
/// Any active subscriptions are unsubscribed. In the event of an error, the connection is
/// dropped.
fn clear_active_subscriptions(&mut self) -> RedisResult<()> {
// Responses to unsubscribe commands return in a 3-tuple with values
// ("unsubscribe" or "punsubscribe", name of subscription removed, count of remaining subs).
// The "count of remaining subs" includes both pattern subscriptions and non pattern
// subscriptions. Thus, to accurately drain all unsubscribe messages received from the
// server, both commands need to be executed at once.
{
// Prepare both unsubscribe commands
let unsubscribe = cmd("UNSUBSCRIBE").get_packed_command();
let punsubscribe = cmd("PUNSUBSCRIBE").get_packed_command();
// Grab a reference to the underlying connection so that we may send
// the commands without immediately blocking for a response.
let con = &mut self.con;
// Execute commands
con.send_bytes(&unsubscribe)?;
con.send_bytes(&punsubscribe)?;
}
// Receive responses
//
// There will be at minimum two responses - 1 for each of punsubscribe and unsubscribe
// commands. There may be more responses if there are active subscriptions. In this case,
// messages are received until the _subscription count_ in the responses reach zero.
let mut received_unsub = false;
let mut received_punsub = false;
loop {
let res: (Vec<u8>, (), isize) = from_redis_value(&self.recv_response()?)?;
match res.0.first().map(|v| *v) {
Some(b'u') => received_unsub = true,
Some(b'p') => received_punsub = true,
_ => (),
}
if received_unsub && received_punsub && res.2 == 0 {
break;
}
}
// Finally, the connection is back in its normal state since all subscriptions were
// cancelled *and* all unsubscribe messages were received.
Ok(())
}
/// Returns the connection status.
///
/// The connection is open until any `read_response` call recieved an
/// invalid response from the server (most likely a closed or dropped
/// connection, otherwise a Redis protocol error). When using unix
/// sockets the connection is open until writing a command failed with a
/// `BrokenPipe` error.
pub fn is_open(&self) -> bool {
self.con.is_open()
}
}
impl ConnectionLike for Connection {
fn req_packed_command(&mut self, cmd: &[u8]) -> RedisResult<Value> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
con.read_response()
}
fn req_packed_commands(
&mut self,
cmd: &[u8],
offset: usize,
count: usize,
) -> RedisResult<Vec<Value>> {
if self.pubsub {
self.exit_pubsub()?;
}
let con = &mut self.con;
con.send_bytes(cmd)?;
let mut rv = vec![];
for idx in 0..(offset + count) {
let item = con.read_response()?;
if idx >= offset {
rv.push(item);
}
}
Ok(rv)
}
fn get_db(&self) -> i64 {
self.db
}
}
/// The pubsub object provides convenient access to the redis pubsub
/// system. Once created you can subscribe and unsubscribe from channels
/// and listen in on messages.
///
/// Example:
///
/// ```rust,no_run
/// # fn do_something() -> redis::RedisResult<()> {
/// let client = redis::Client::open("redis://127.0.0.1/")?;
/// let mut con = client.get_connection()?;
/// let mut pubsub = con.as_pubsub();
/// pubsub.subscribe("channel_1")?;
/// pubsub.subscribe("channel_2")?;
///
/// loop {
/// let msg = pubsub.get_message()?;
/// let payload : String = msg.get_payload()?;
/// println!("channel '{}': {}", msg.get_channel_name(), payload);
/// }
/// # }
/// ```
impl<'a> PubSub<'a> {
fn new(con: &'a mut Connection) -> Self {
Self { con }
}
/// Subscribes to a new channel.
pub fn subscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("SUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Subscribes to a new channel with a pattern.
pub fn psubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel.
pub fn unsubscribe<T: ToRedisArgs>(&mut self, channel: T) -> RedisResult<()> {
let _: () = cmd("UNSUBSCRIBE").arg(channel).query(self.con)?;
Ok(())
}
/// Unsubscribes from a channel with a pattern.
pub fn punsubscribe<T: ToRedisArgs>(&mut self, pchannel: T) -> RedisResult<()> {
let _: () = cmd("PUNSUBSCRIBE").arg(pchannel).query(self.con)?;
Ok(())
}
/// Fetches the next message from the pubsub connection. Blocks until
/// a message becomes available. This currently does not provide a
/// wait not to block :(
///
/// The message itself is still generic and can be converted into an
/// appropriate type through the helper methods on it.
pub fn get_message(&mut self) -> RedisResult<Msg> {
loop {
let raw_msg: Vec<Value> = from_redis_value(&self.con.recv_response()?)?;
let mut iter = raw_msg.into_iter();
let msg_type: String = from_redis_value(&unwrap_or!(iter.next(), continue))?;
let mut pattern = None;
let payload;
let channel;
if msg_type == "message" {
channel = unwrap_or!(iter.next(), continue);
payload = unwrap_or!(iter.next(), continue);
} else if msg_type == "pmessage" {
pattern = Some(unwrap_or!(iter.next(), continue));
channel = unwrap_or!(iter.next(), continue);
|
{
self.con.set_read_timeout(dur)
}
|
identifier_body
|
ike.rs
|
/* Copyright (C) 2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// Author: Frank Honza <[email protected]>
extern crate ipsec_parser;
use self::ipsec_parser::*;
use crate::applayer;
use crate::applayer::*;
use crate::core::{self, *};
use crate::ike::ikev1::{handle_ikev1, IkeV1Header, Ikev1Container};
use crate::ike::ikev2::{handle_ikev2, Ikev2Container};
use crate::ike::parser::*;
use nom7::Err;
use std;
use std::collections::HashSet;
use std::ffi::CString;
#[derive(AppLayerEvent)]
pub enum IkeEvent {
MalformedData,
NoEncryption,
WeakCryptoEnc,
WeakCryptoPrf,
WeakCryptoDh,
WeakCryptoAuth,
WeakCryptoNoDh,
WeakCryptoNoAuth,
InvalidProposal,
UnknownProposal,
PayloadExtraData,
MultipleServerProposal,
}
pub struct IkeHeaderWrapper {
pub spi_initiator: String,
pub spi_responder: String,
pub maj_ver: u8,
pub min_ver: u8,
pub msg_id: u32,
pub flags: u8,
pub ikev1_transforms: Vec<Vec<SaAttribute>>,
pub ikev2_transforms: Vec<IkeV2Transform>,
pub ikev1_header: IkeV1Header,
pub ikev2_header: IkeV2Header,
}
impl IkeHeaderWrapper {
pub fn
|
() -> IkeHeaderWrapper {
IkeHeaderWrapper {
spi_initiator: String::new(),
spi_responder: String::new(),
maj_ver: 0,
min_ver: 0,
msg_id: 0,
flags: 0,
ikev1_transforms: Vec::new(),
ikev2_transforms: Vec::new(),
ikev1_header: IkeV1Header::default(),
ikev2_header: IkeV2Header {
init_spi: 0,
resp_spi: 0,
next_payload: IkePayloadType::NoNextPayload,
maj_ver: 0,
min_ver: 0,
exch_type: IkeExchangeType(0),
flags: 0,
msg_id: 0,
length: 0,
},
}
}
}
#[derive(Default)]
pub struct IkePayloadWrapper {
pub ikev1_payload_types: Option<HashSet<u8>>,
pub ikev2_payload_types: Vec<IkePayloadType>,
}
pub struct IKETransaction {
tx_id: u64,
pub ike_version: u8,
pub hdr: IkeHeaderWrapper,
pub payload_types: IkePayloadWrapper,
pub notify_types: Vec<NotifyType>,
/// errors seen during exchange
pub errors: u32,
logged: LoggerFlags,
tx_data: applayer::AppLayerTxData,
}
impl Transaction for IKETransaction {
fn id(&self) -> u64 {
self.tx_id
}
}
impl IKETransaction {
pub fn new() -> IKETransaction {
IKETransaction {
tx_id: 0,
ike_version: 0,
hdr: IkeHeaderWrapper::new(),
payload_types: Default::default(),
notify_types: vec![],
logged: LoggerFlags::new(),
tx_data: applayer::AppLayerTxData::new(),
errors: 0,
}
}
/// Set an event.
pub fn set_event(&mut self, event: IkeEvent) {
self.tx_data.set_event(event as u8);
}
}
#[derive(Default)]
pub struct IKEState {
tx_id: u64,
pub transactions: Vec<IKETransaction>,
pub ikev1_container: Ikev1Container,
pub ikev2_container: Ikev2Container,
}
impl State<IKETransaction> for IKEState {
fn get_transactions(&self) -> &[IKETransaction] {
&self.transactions
}
}
impl IKEState {
// Free a transaction by ID.
fn free_tx(&mut self, tx_id: u64) {
let tx = self
.transactions
.iter()
.position(|tx| tx.tx_id == tx_id + 1);
debug_assert!(tx!= None);
if let Some(idx) = tx {
let _ = self.transactions.remove(idx);
}
}
pub fn get_tx(&mut self, tx_id: u64) -> Option<&mut IKETransaction> {
for tx in &mut self.transactions {
if tx.tx_id == tx_id + 1 {
return Some(tx);
}
}
return None;
}
pub fn new_tx(&mut self) -> IKETransaction {
let mut tx = IKETransaction::new();
self.tx_id += 1;
tx.tx_id = self.tx_id;
return tx;
}
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: IkeEvent) {
if let Some(tx) = self.transactions.last_mut() {
tx.set_event(event);
} else {
SCLogDebug!(
"IKE: trying to set event {} on non-existing transaction",
event as u32
);
}
}
fn handle_input(&mut self, input: &[u8], direction: Direction) -> AppLayerResult {
// We're not interested in empty requests.
if input.len() == 0 {
return AppLayerResult::ok();
}
let mut current = input;
match parse_isakmp_header(current) {
Ok((rem, isakmp_header)) => {
current = rem;
if isakmp_header.maj_ver!= 1 && isakmp_header.maj_ver!= 2 {
SCLogDebug!("Unsupported ISAKMP major_version");
return AppLayerResult::err();
}
if isakmp_header.maj_ver == 1 {
handle_ikev1(self, current, isakmp_header, direction);
} else if isakmp_header.maj_ver == 2 {
handle_ikev2(self, current, isakmp_header, direction);
} else {
return AppLayerResult::err();
}
return AppLayerResult::ok(); // todo either remove outer loop or check header length-field if we have completely read everything
}
Err(Err::Incomplete(_)) => {
SCLogDebug!("Insufficient data while parsing IKE");
return AppLayerResult::err();
}
Err(_) => {
SCLogDebug!("Error while parsing IKE packet");
return AppLayerResult::err();
}
}
}
}
/// Probe to see if this input looks like a request or response.
fn probe(input: &[u8], direction: Direction, rdir: *mut u8) -> bool {
match parse_isakmp_header(input) {
Ok((_, isakmp_header)) => {
if isakmp_header.maj_ver == 1 {
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
} else if isakmp_header.maj_ver == 2 {
if isakmp_header.min_ver!= 0 {
SCLogDebug!(
"ipsec_probe: could be ipsec, but with unsupported/invalid version {}.{}",
isakmp_header.maj_ver,
isakmp_header.min_ver
);
return false;
}
if isakmp_header.exch_type < 34 || isakmp_header.exch_type > 37 {
SCLogDebug!("ipsec_probe: could be ipsec, but with unsupported/invalid exchange type {}",
isakmp_header.exch_type);
return false;
}
if isakmp_header.length as usize!= input.len() {
SCLogDebug!("ipsec_probe: could be ipsec, but length does not match");
return false;
}
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
}
return false;
}
Err(_) => return false,
}
}
// C exports.
/// C entry point for a probing parser.
#[no_mangle]
pub unsafe extern "C" fn rs_ike_probing_parser(
_flow: *const Flow, direction: u8, input: *const u8, input_len: u32, rdir: *mut u8,
) -> AppProto {
if input_len < 28 {
// at least the ISAKMP_HEADER must be there, not ALPROTO_UNKNOWN because over UDP
return ALPROTO_FAILED;
}
if!input.is_null() {
let slice = build_slice!(input, input_len as usize);
if probe(slice, direction.into(), rdir) {
return ALPROTO_IKE;
}
}
return ALPROTO_FAILED;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_new(
_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
) -> *mut std::os::raw::c_void {
let state = IKEState::default();
let boxed = Box::new(state);
return Box::into_raw(boxed) as *mut _;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_free(state: *mut std::os::raw::c_void) {
// Just unbox...
std::mem::drop(Box::from_raw(state as *mut IKEState));
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
let state = cast_pointer!(state, IKEState);
state.free_tx(tx_id);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_request(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToServer);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_response(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToClient);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx(
state: *mut std::os::raw::c_void, tx_id: u64,
) -> *mut std::os::raw::c_void {
let state = cast_pointer!(state, IKEState);
match state.get_tx(tx_id) {
Some(tx) => {
return tx as *const _ as *mut _;
}
None => {
return std::ptr::null_mut();
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
let state = cast_pointer!(state, IKEState);
return state.tx_id;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int {
// This parser uses 1 to signal transaction completion status.
return 1;
}
#[no_mangle]
pub extern "C" fn rs_ike_tx_get_alstate_progress(
_tx: *mut std::os::raw::c_void, _direction: u8,
) -> std::os::raw::c_int {
return 1;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_get_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void,
) -> u32 {
let tx = cast_pointer!(tx, IKETransaction);
return tx.logged.get();
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_set_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void, logged: u32,
) {
let tx = cast_pointer!(tx, IKETransaction);
tx.logged.set(logged);
}
static mut ALPROTO_IKE : AppProto = ALPROTO_UNKNOWN;
// Parser name as a C style string.
const PARSER_NAME: &'static [u8] = b"ike\0";
const PARSER_ALIAS: &'static [u8] = b"ikev2\0";
export_tx_data_get!(rs_ike_get_tx_data, IKETransaction);
#[no_mangle]
pub unsafe extern "C" fn rs_ike_register_parser() {
let default_port = CString::new("500").unwrap();
let parser = RustParser {
name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
default_port : default_port.as_ptr(),
ipproto : core::IPPROTO_UDP,
probe_ts : Some(rs_ike_probing_parser),
probe_tc : Some(rs_ike_probing_parser),
min_depth : 0,
max_depth : 16,
state_new : rs_ike_state_new,
state_free : rs_ike_state_free,
tx_free : rs_ike_state_tx_free,
parse_ts : rs_ike_parse_request,
parse_tc : rs_ike_parse_response,
get_tx_count : rs_ike_state_get_tx_count,
get_tx : rs_ike_state_get_tx,
tx_comp_st_ts : 1,
tx_comp_st_tc : 1,
tx_get_progress : rs_ike_tx_get_alstate_progress,
get_eventinfo : Some(IkeEvent::get_event_info),
get_eventinfo_byid : Some(IkeEvent::get_event_info_by_id),
localstorage_new : None,
localstorage_free : None,
get_files : None,
get_tx_iterator : Some(applayer::state_get_tx_iterator::<IKEState, IKETransaction>),
get_tx_data : rs_ike_get_tx_data,
apply_tx_config : None,
flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
truncate : None,
get_frame_id_by_name: None,
get_frame_name_by_id: None,
};
let ip_proto_str = CString::new("udp").unwrap();
if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
ALPROTO_IKE = alproto;
if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let _ = AppLayerRegisterParser(&parser, alproto);
}
AppLayerRegisterParserAlias(
PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
PARSER_ALIAS.as_ptr() as *const std::os::raw::c_char,
);
SCLogDebug!("Rust IKE parser registered.");
} else {
SCLogDebug!("Protocol detector and parser disabled for IKE.");
}
}
|
new
|
identifier_name
|
ike.rs
|
/* Copyright (C) 2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// Author: Frank Honza <[email protected]>
extern crate ipsec_parser;
use self::ipsec_parser::*;
use crate::applayer;
use crate::applayer::*;
use crate::core::{self, *};
use crate::ike::ikev1::{handle_ikev1, IkeV1Header, Ikev1Container};
use crate::ike::ikev2::{handle_ikev2, Ikev2Container};
use crate::ike::parser::*;
use nom7::Err;
use std;
use std::collections::HashSet;
use std::ffi::CString;
#[derive(AppLayerEvent)]
pub enum IkeEvent {
MalformedData,
NoEncryption,
WeakCryptoEnc,
WeakCryptoPrf,
WeakCryptoDh,
WeakCryptoAuth,
WeakCryptoNoDh,
WeakCryptoNoAuth,
InvalidProposal,
UnknownProposal,
PayloadExtraData,
MultipleServerProposal,
}
pub struct IkeHeaderWrapper {
pub spi_initiator: String,
pub spi_responder: String,
pub maj_ver: u8,
pub min_ver: u8,
pub msg_id: u32,
pub flags: u8,
pub ikev1_transforms: Vec<Vec<SaAttribute>>,
pub ikev2_transforms: Vec<IkeV2Transform>,
pub ikev1_header: IkeV1Header,
pub ikev2_header: IkeV2Header,
}
impl IkeHeaderWrapper {
pub fn new() -> IkeHeaderWrapper {
IkeHeaderWrapper {
spi_initiator: String::new(),
spi_responder: String::new(),
maj_ver: 0,
min_ver: 0,
msg_id: 0,
flags: 0,
ikev1_transforms: Vec::new(),
ikev2_transforms: Vec::new(),
ikev1_header: IkeV1Header::default(),
ikev2_header: IkeV2Header {
init_spi: 0,
resp_spi: 0,
next_payload: IkePayloadType::NoNextPayload,
maj_ver: 0,
min_ver: 0,
exch_type: IkeExchangeType(0),
flags: 0,
msg_id: 0,
length: 0,
},
}
}
}
#[derive(Default)]
pub struct IkePayloadWrapper {
pub ikev1_payload_types: Option<HashSet<u8>>,
pub ikev2_payload_types: Vec<IkePayloadType>,
}
pub struct IKETransaction {
tx_id: u64,
pub ike_version: u8,
pub hdr: IkeHeaderWrapper,
pub payload_types: IkePayloadWrapper,
pub notify_types: Vec<NotifyType>,
/// errors seen during exchange
pub errors: u32,
logged: LoggerFlags,
tx_data: applayer::AppLayerTxData,
}
impl Transaction for IKETransaction {
fn id(&self) -> u64 {
self.tx_id
}
}
impl IKETransaction {
pub fn new() -> IKETransaction {
IKETransaction {
tx_id: 0,
ike_version: 0,
hdr: IkeHeaderWrapper::new(),
payload_types: Default::default(),
notify_types: vec![],
logged: LoggerFlags::new(),
tx_data: applayer::AppLayerTxData::new(),
errors: 0,
}
}
/// Set an event.
pub fn set_event(&mut self, event: IkeEvent) {
self.tx_data.set_event(event as u8);
}
}
#[derive(Default)]
pub struct IKEState {
tx_id: u64,
pub transactions: Vec<IKETransaction>,
pub ikev1_container: Ikev1Container,
pub ikev2_container: Ikev2Container,
}
impl State<IKETransaction> for IKEState {
fn get_transactions(&self) -> &[IKETransaction] {
&self.transactions
}
}
impl IKEState {
// Free a transaction by ID.
fn free_tx(&mut self, tx_id: u64) {
let tx = self
.transactions
.iter()
.position(|tx| tx.tx_id == tx_id + 1);
debug_assert!(tx!= None);
if let Some(idx) = tx {
let _ = self.transactions.remove(idx);
}
}
pub fn get_tx(&mut self, tx_id: u64) -> Option<&mut IKETransaction> {
for tx in &mut self.transactions {
if tx.tx_id == tx_id + 1 {
return Some(tx);
}
}
return None;
}
pub fn new_tx(&mut self) -> IKETransaction {
let mut tx = IKETransaction::new();
self.tx_id += 1;
tx.tx_id = self.tx_id;
return tx;
}
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: IkeEvent) {
if let Some(tx) = self.transactions.last_mut() {
tx.set_event(event);
} else {
SCLogDebug!(
"IKE: trying to set event {} on non-existing transaction",
event as u32
);
}
}
fn handle_input(&mut self, input: &[u8], direction: Direction) -> AppLayerResult {
// We're not interested in empty requests.
if input.len() == 0 {
return AppLayerResult::ok();
}
let mut current = input;
match parse_isakmp_header(current) {
Ok((rem, isakmp_header)) => {
current = rem;
if isakmp_header.maj_ver!= 1 && isakmp_header.maj_ver!= 2 {
SCLogDebug!("Unsupported ISAKMP major_version");
return AppLayerResult::err();
}
if isakmp_header.maj_ver == 1 {
handle_ikev1(self, current, isakmp_header, direction);
} else if isakmp_header.maj_ver == 2 {
handle_ikev2(self, current, isakmp_header, direction);
} else {
return AppLayerResult::err();
}
return AppLayerResult::ok(); // todo either remove outer loop or check header length-field if we have completely read everything
}
Err(Err::Incomplete(_)) => {
SCLogDebug!("Insufficient data while parsing IKE");
return AppLayerResult::err();
}
Err(_) => {
SCLogDebug!("Error while parsing IKE packet");
return AppLayerResult::err();
}
}
}
}
/// Probe to see if this input looks like a request or response.
fn probe(input: &[u8], direction: Direction, rdir: *mut u8) -> bool {
match parse_isakmp_header(input) {
Ok((_, isakmp_header)) => {
if isakmp_header.maj_ver == 1
|
else if isakmp_header.maj_ver == 2 {
if isakmp_header.min_ver!= 0 {
SCLogDebug!(
"ipsec_probe: could be ipsec, but with unsupported/invalid version {}.{}",
isakmp_header.maj_ver,
isakmp_header.min_ver
);
return false;
}
if isakmp_header.exch_type < 34 || isakmp_header.exch_type > 37 {
SCLogDebug!("ipsec_probe: could be ipsec, but with unsupported/invalid exchange type {}",
isakmp_header.exch_type);
return false;
}
if isakmp_header.length as usize!= input.len() {
SCLogDebug!("ipsec_probe: could be ipsec, but length does not match");
return false;
}
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
}
return false;
}
Err(_) => return false,
}
}
// C exports.
/// C entry point for a probing parser.
#[no_mangle]
pub unsafe extern "C" fn rs_ike_probing_parser(
_flow: *const Flow, direction: u8, input: *const u8, input_len: u32, rdir: *mut u8,
) -> AppProto {
if input_len < 28 {
// at least the ISAKMP_HEADER must be there, not ALPROTO_UNKNOWN because over UDP
return ALPROTO_FAILED;
}
if!input.is_null() {
let slice = build_slice!(input, input_len as usize);
if probe(slice, direction.into(), rdir) {
return ALPROTO_IKE;
}
}
return ALPROTO_FAILED;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_new(
_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
) -> *mut std::os::raw::c_void {
let state = IKEState::default();
let boxed = Box::new(state);
return Box::into_raw(boxed) as *mut _;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_free(state: *mut std::os::raw::c_void) {
// Just unbox...
std::mem::drop(Box::from_raw(state as *mut IKEState));
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
let state = cast_pointer!(state, IKEState);
state.free_tx(tx_id);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_request(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToServer);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_response(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToClient);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx(
state: *mut std::os::raw::c_void, tx_id: u64,
) -> *mut std::os::raw::c_void {
let state = cast_pointer!(state, IKEState);
match state.get_tx(tx_id) {
Some(tx) => {
return tx as *const _ as *mut _;
}
None => {
return std::ptr::null_mut();
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
let state = cast_pointer!(state, IKEState);
return state.tx_id;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int {
// This parser uses 1 to signal transaction completion status.
return 1;
}
#[no_mangle]
pub extern "C" fn rs_ike_tx_get_alstate_progress(
_tx: *mut std::os::raw::c_void, _direction: u8,
) -> std::os::raw::c_int {
return 1;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_get_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void,
) -> u32 {
let tx = cast_pointer!(tx, IKETransaction);
return tx.logged.get();
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_set_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void, logged: u32,
) {
let tx = cast_pointer!(tx, IKETransaction);
tx.logged.set(logged);
}
static mut ALPROTO_IKE : AppProto = ALPROTO_UNKNOWN;
// Parser name as a C style string.
const PARSER_NAME: &'static [u8] = b"ike\0";
const PARSER_ALIAS: &'static [u8] = b"ikev2\0";
export_tx_data_get!(rs_ike_get_tx_data, IKETransaction);
#[no_mangle]
pub unsafe extern "C" fn rs_ike_register_parser() {
let default_port = CString::new("500").unwrap();
let parser = RustParser {
name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
default_port : default_port.as_ptr(),
ipproto : core::IPPROTO_UDP,
probe_ts : Some(rs_ike_probing_parser),
probe_tc : Some(rs_ike_probing_parser),
min_depth : 0,
max_depth : 16,
state_new : rs_ike_state_new,
state_free : rs_ike_state_free,
tx_free : rs_ike_state_tx_free,
parse_ts : rs_ike_parse_request,
parse_tc : rs_ike_parse_response,
get_tx_count : rs_ike_state_get_tx_count,
get_tx : rs_ike_state_get_tx,
tx_comp_st_ts : 1,
tx_comp_st_tc : 1,
tx_get_progress : rs_ike_tx_get_alstate_progress,
get_eventinfo : Some(IkeEvent::get_event_info),
get_eventinfo_byid : Some(IkeEvent::get_event_info_by_id),
localstorage_new : None,
localstorage_free : None,
get_files : None,
get_tx_iterator : Some(applayer::state_get_tx_iterator::<IKEState, IKETransaction>),
get_tx_data : rs_ike_get_tx_data,
apply_tx_config : None,
flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
truncate : None,
get_frame_id_by_name: None,
get_frame_name_by_id: None,
};
let ip_proto_str = CString::new("udp").unwrap();
if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
ALPROTO_IKE = alproto;
if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let _ = AppLayerRegisterParser(&parser, alproto);
}
AppLayerRegisterParserAlias(
PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
PARSER_ALIAS.as_ptr() as *const std::os::raw::c_char,
);
SCLogDebug!("Rust IKE parser registered.");
} else {
SCLogDebug!("Protocol detector and parser disabled for IKE.");
}
}
|
{
if isakmp_header.resp_spi == 0 && direction != Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
}
|
conditional_block
|
ike.rs
|
/* Copyright (C) 2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// Author: Frank Honza <[email protected]>
extern crate ipsec_parser;
use self::ipsec_parser::*;
use crate::applayer;
use crate::applayer::*;
use crate::core::{self, *};
use crate::ike::ikev1::{handle_ikev1, IkeV1Header, Ikev1Container};
use crate::ike::ikev2::{handle_ikev2, Ikev2Container};
use crate::ike::parser::*;
use nom7::Err;
use std;
use std::collections::HashSet;
use std::ffi::CString;
#[derive(AppLayerEvent)]
pub enum IkeEvent {
MalformedData,
NoEncryption,
WeakCryptoEnc,
WeakCryptoPrf,
WeakCryptoDh,
WeakCryptoAuth,
WeakCryptoNoDh,
WeakCryptoNoAuth,
InvalidProposal,
UnknownProposal,
PayloadExtraData,
MultipleServerProposal,
}
pub struct IkeHeaderWrapper {
pub spi_initiator: String,
pub spi_responder: String,
pub maj_ver: u8,
pub min_ver: u8,
pub msg_id: u32,
pub flags: u8,
pub ikev1_transforms: Vec<Vec<SaAttribute>>,
pub ikev2_transforms: Vec<IkeV2Transform>,
pub ikev1_header: IkeV1Header,
pub ikev2_header: IkeV2Header,
}
impl IkeHeaderWrapper {
pub fn new() -> IkeHeaderWrapper {
IkeHeaderWrapper {
spi_initiator: String::new(),
spi_responder: String::new(),
maj_ver: 0,
min_ver: 0,
msg_id: 0,
flags: 0,
ikev1_transforms: Vec::new(),
ikev2_transforms: Vec::new(),
ikev1_header: IkeV1Header::default(),
ikev2_header: IkeV2Header {
init_spi: 0,
resp_spi: 0,
next_payload: IkePayloadType::NoNextPayload,
maj_ver: 0,
min_ver: 0,
exch_type: IkeExchangeType(0),
flags: 0,
msg_id: 0,
length: 0,
},
}
}
}
#[derive(Default)]
pub struct IkePayloadWrapper {
pub ikev1_payload_types: Option<HashSet<u8>>,
pub ikev2_payload_types: Vec<IkePayloadType>,
}
pub struct IKETransaction {
tx_id: u64,
pub ike_version: u8,
pub hdr: IkeHeaderWrapper,
pub payload_types: IkePayloadWrapper,
pub notify_types: Vec<NotifyType>,
/// errors seen during exchange
pub errors: u32,
logged: LoggerFlags,
tx_data: applayer::AppLayerTxData,
}
impl Transaction for IKETransaction {
fn id(&self) -> u64 {
self.tx_id
}
}
impl IKETransaction {
pub fn new() -> IKETransaction {
IKETransaction {
tx_id: 0,
ike_version: 0,
hdr: IkeHeaderWrapper::new(),
payload_types: Default::default(),
notify_types: vec![],
logged: LoggerFlags::new(),
tx_data: applayer::AppLayerTxData::new(),
errors: 0,
}
}
/// Set an event.
pub fn set_event(&mut self, event: IkeEvent) {
self.tx_data.set_event(event as u8);
}
}
#[derive(Default)]
pub struct IKEState {
tx_id: u64,
pub transactions: Vec<IKETransaction>,
pub ikev1_container: Ikev1Container,
pub ikev2_container: Ikev2Container,
}
impl State<IKETransaction> for IKEState {
fn get_transactions(&self) -> &[IKETransaction] {
&self.transactions
}
}
impl IKEState {
// Free a transaction by ID.
fn free_tx(&mut self, tx_id: u64) {
let tx = self
.transactions
.iter()
.position(|tx| tx.tx_id == tx_id + 1);
debug_assert!(tx!= None);
if let Some(idx) = tx {
let _ = self.transactions.remove(idx);
}
}
pub fn get_tx(&mut self, tx_id: u64) -> Option<&mut IKETransaction> {
for tx in &mut self.transactions {
if tx.tx_id == tx_id + 1 {
return Some(tx);
}
}
return None;
}
pub fn new_tx(&mut self) -> IKETransaction {
let mut tx = IKETransaction::new();
self.tx_id += 1;
tx.tx_id = self.tx_id;
return tx;
}
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: IkeEvent) {
if let Some(tx) = self.transactions.last_mut() {
tx.set_event(event);
} else {
SCLogDebug!(
"IKE: trying to set event {} on non-existing transaction",
event as u32
);
}
}
fn handle_input(&mut self, input: &[u8], direction: Direction) -> AppLayerResult {
// We're not interested in empty requests.
if input.len() == 0 {
return AppLayerResult::ok();
}
let mut current = input;
match parse_isakmp_header(current) {
Ok((rem, isakmp_header)) => {
current = rem;
if isakmp_header.maj_ver!= 1 && isakmp_header.maj_ver!= 2 {
SCLogDebug!("Unsupported ISAKMP major_version");
return AppLayerResult::err();
}
if isakmp_header.maj_ver == 1 {
handle_ikev1(self, current, isakmp_header, direction);
} else if isakmp_header.maj_ver == 2 {
handle_ikev2(self, current, isakmp_header, direction);
} else {
return AppLayerResult::err();
}
return AppLayerResult::ok(); // todo either remove outer loop or check header length-field if we have completely read everything
}
Err(Err::Incomplete(_)) => {
SCLogDebug!("Insufficient data while parsing IKE");
return AppLayerResult::err();
}
Err(_) => {
SCLogDebug!("Error while parsing IKE packet");
return AppLayerResult::err();
}
}
}
}
/// Probe to see if this input looks like a request or response.
fn probe(input: &[u8], direction: Direction, rdir: *mut u8) -> bool {
match parse_isakmp_header(input) {
Ok((_, isakmp_header)) => {
if isakmp_header.maj_ver == 1 {
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
} else if isakmp_header.maj_ver == 2 {
if isakmp_header.min_ver!= 0 {
SCLogDebug!(
"ipsec_probe: could be ipsec, but with unsupported/invalid version {}.{}",
isakmp_header.maj_ver,
isakmp_header.min_ver
);
return false;
}
if isakmp_header.exch_type < 34 || isakmp_header.exch_type > 37 {
SCLogDebug!("ipsec_probe: could be ipsec, but with unsupported/invalid exchange type {}",
isakmp_header.exch_type);
return false;
}
if isakmp_header.length as usize!= input.len() {
SCLogDebug!("ipsec_probe: could be ipsec, but length does not match");
return false;
}
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
}
return false;
}
Err(_) => return false,
}
}
// C exports.
/// C entry point for a probing parser.
#[no_mangle]
pub unsafe extern "C" fn rs_ike_probing_parser(
_flow: *const Flow, direction: u8, input: *const u8, input_len: u32, rdir: *mut u8,
) -> AppProto {
if input_len < 28 {
// at least the ISAKMP_HEADER must be there, not ALPROTO_UNKNOWN because over UDP
return ALPROTO_FAILED;
}
if!input.is_null() {
let slice = build_slice!(input, input_len as usize);
if probe(slice, direction.into(), rdir) {
return ALPROTO_IKE;
}
}
return ALPROTO_FAILED;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_new(
_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
) -> *mut std::os::raw::c_void {
let state = IKEState::default();
let boxed = Box::new(state);
return Box::into_raw(boxed) as *mut _;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_free(state: *mut std::os::raw::c_void) {
// Just unbox...
std::mem::drop(Box::from_raw(state as *mut IKEState));
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
let state = cast_pointer!(state, IKEState);
state.free_tx(tx_id);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_request(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToServer);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_response(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToClient);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx(
state: *mut std::os::raw::c_void, tx_id: u64,
) -> *mut std::os::raw::c_void {
let state = cast_pointer!(state, IKEState);
match state.get_tx(tx_id) {
Some(tx) => {
return tx as *const _ as *mut _;
}
None => {
return std::ptr::null_mut();
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64
|
#[no_mangle]
pub extern "C" fn rs_ike_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int {
// This parser uses 1 to signal transaction completion status.
return 1;
}
#[no_mangle]
pub extern "C" fn rs_ike_tx_get_alstate_progress(
_tx: *mut std::os::raw::c_void, _direction: u8,
) -> std::os::raw::c_int {
return 1;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_get_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void,
) -> u32 {
let tx = cast_pointer!(tx, IKETransaction);
return tx.logged.get();
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_set_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void, logged: u32,
) {
let tx = cast_pointer!(tx, IKETransaction);
tx.logged.set(logged);
}
static mut ALPROTO_IKE : AppProto = ALPROTO_UNKNOWN;
// Parser name as a C style string.
const PARSER_NAME: &'static [u8] = b"ike\0";
const PARSER_ALIAS: &'static [u8] = b"ikev2\0";
export_tx_data_get!(rs_ike_get_tx_data, IKETransaction);
#[no_mangle]
pub unsafe extern "C" fn rs_ike_register_parser() {
let default_port = CString::new("500").unwrap();
let parser = RustParser {
name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
default_port : default_port.as_ptr(),
ipproto : core::IPPROTO_UDP,
probe_ts : Some(rs_ike_probing_parser),
probe_tc : Some(rs_ike_probing_parser),
min_depth : 0,
max_depth : 16,
state_new : rs_ike_state_new,
state_free : rs_ike_state_free,
tx_free : rs_ike_state_tx_free,
parse_ts : rs_ike_parse_request,
parse_tc : rs_ike_parse_response,
get_tx_count : rs_ike_state_get_tx_count,
get_tx : rs_ike_state_get_tx,
tx_comp_st_ts : 1,
tx_comp_st_tc : 1,
tx_get_progress : rs_ike_tx_get_alstate_progress,
get_eventinfo : Some(IkeEvent::get_event_info),
get_eventinfo_byid : Some(IkeEvent::get_event_info_by_id),
localstorage_new : None,
localstorage_free : None,
get_files : None,
get_tx_iterator : Some(applayer::state_get_tx_iterator::<IKEState, IKETransaction>),
get_tx_data : rs_ike_get_tx_data,
apply_tx_config : None,
flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
truncate : None,
get_frame_id_by_name: None,
get_frame_name_by_id: None,
};
let ip_proto_str = CString::new("udp").unwrap();
if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
ALPROTO_IKE = alproto;
if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let _ = AppLayerRegisterParser(&parser, alproto);
}
AppLayerRegisterParserAlias(
PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
PARSER_ALIAS.as_ptr() as *const std::os::raw::c_char,
);
SCLogDebug!("Rust IKE parser registered.");
} else {
SCLogDebug!("Protocol detector and parser disabled for IKE.");
}
}
|
{
let state = cast_pointer!(state, IKEState);
return state.tx_id;
}
|
identifier_body
|
ike.rs
|
/* Copyright (C) 2020 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// Author: Frank Honza <[email protected]>
extern crate ipsec_parser;
use self::ipsec_parser::*;
use crate::applayer;
use crate::applayer::*;
use crate::core::{self, *};
use crate::ike::ikev1::{handle_ikev1, IkeV1Header, Ikev1Container};
use crate::ike::ikev2::{handle_ikev2, Ikev2Container};
use crate::ike::parser::*;
use nom7::Err;
use std;
use std::collections::HashSet;
use std::ffi::CString;
#[derive(AppLayerEvent)]
pub enum IkeEvent {
MalformedData,
NoEncryption,
WeakCryptoEnc,
WeakCryptoPrf,
WeakCryptoDh,
WeakCryptoAuth,
WeakCryptoNoDh,
WeakCryptoNoAuth,
InvalidProposal,
UnknownProposal,
PayloadExtraData,
MultipleServerProposal,
}
pub struct IkeHeaderWrapper {
pub spi_initiator: String,
pub spi_responder: String,
pub maj_ver: u8,
pub min_ver: u8,
pub msg_id: u32,
pub flags: u8,
pub ikev1_transforms: Vec<Vec<SaAttribute>>,
pub ikev2_transforms: Vec<IkeV2Transform>,
pub ikev1_header: IkeV1Header,
pub ikev2_header: IkeV2Header,
}
impl IkeHeaderWrapper {
pub fn new() -> IkeHeaderWrapper {
IkeHeaderWrapper {
spi_initiator: String::new(),
spi_responder: String::new(),
maj_ver: 0,
min_ver: 0,
msg_id: 0,
flags: 0,
ikev1_transforms: Vec::new(),
ikev2_transforms: Vec::new(),
ikev1_header: IkeV1Header::default(),
ikev2_header: IkeV2Header {
init_spi: 0,
resp_spi: 0,
next_payload: IkePayloadType::NoNextPayload,
maj_ver: 0,
min_ver: 0,
exch_type: IkeExchangeType(0),
flags: 0,
msg_id: 0,
length: 0,
},
}
}
}
#[derive(Default)]
pub struct IkePayloadWrapper {
pub ikev1_payload_types: Option<HashSet<u8>>,
pub ikev2_payload_types: Vec<IkePayloadType>,
}
pub struct IKETransaction {
tx_id: u64,
pub ike_version: u8,
pub hdr: IkeHeaderWrapper,
pub payload_types: IkePayloadWrapper,
pub notify_types: Vec<NotifyType>,
/// errors seen during exchange
pub errors: u32,
logged: LoggerFlags,
tx_data: applayer::AppLayerTxData,
}
impl Transaction for IKETransaction {
fn id(&self) -> u64 {
self.tx_id
}
}
impl IKETransaction {
pub fn new() -> IKETransaction {
IKETransaction {
tx_id: 0,
ike_version: 0,
hdr: IkeHeaderWrapper::new(),
payload_types: Default::default(),
notify_types: vec![],
logged: LoggerFlags::new(),
tx_data: applayer::AppLayerTxData::new(),
errors: 0,
}
}
/// Set an event.
pub fn set_event(&mut self, event: IkeEvent) {
self.tx_data.set_event(event as u8);
}
}
#[derive(Default)]
pub struct IKEState {
tx_id: u64,
pub transactions: Vec<IKETransaction>,
pub ikev1_container: Ikev1Container,
pub ikev2_container: Ikev2Container,
}
impl State<IKETransaction> for IKEState {
fn get_transactions(&self) -> &[IKETransaction] {
&self.transactions
}
}
impl IKEState {
// Free a transaction by ID.
fn free_tx(&mut self, tx_id: u64) {
let tx = self
.transactions
.iter()
.position(|tx| tx.tx_id == tx_id + 1);
debug_assert!(tx!= None);
if let Some(idx) = tx {
let _ = self.transactions.remove(idx);
}
}
pub fn get_tx(&mut self, tx_id: u64) -> Option<&mut IKETransaction> {
for tx in &mut self.transactions {
if tx.tx_id == tx_id + 1 {
return Some(tx);
}
}
return None;
}
pub fn new_tx(&mut self) -> IKETransaction {
let mut tx = IKETransaction::new();
self.tx_id += 1;
tx.tx_id = self.tx_id;
return tx;
}
/// Set an event. The event is set on the most recent transaction.
pub fn set_event(&mut self, event: IkeEvent) {
if let Some(tx) = self.transactions.last_mut() {
tx.set_event(event);
} else {
SCLogDebug!(
"IKE: trying to set event {} on non-existing transaction",
event as u32
);
}
}
fn handle_input(&mut self, input: &[u8], direction: Direction) -> AppLayerResult {
// We're not interested in empty requests.
if input.len() == 0 {
return AppLayerResult::ok();
}
let mut current = input;
match parse_isakmp_header(current) {
Ok((rem, isakmp_header)) => {
current = rem;
if isakmp_header.maj_ver!= 1 && isakmp_header.maj_ver!= 2 {
SCLogDebug!("Unsupported ISAKMP major_version");
return AppLayerResult::err();
}
if isakmp_header.maj_ver == 1 {
handle_ikev1(self, current, isakmp_header, direction);
} else if isakmp_header.maj_ver == 2 {
handle_ikev2(self, current, isakmp_header, direction);
} else {
return AppLayerResult::err();
}
return AppLayerResult::ok(); // todo either remove outer loop or check header length-field if we have completely read everything
}
Err(Err::Incomplete(_)) => {
SCLogDebug!("Insufficient data while parsing IKE");
return AppLayerResult::err();
}
Err(_) => {
SCLogDebug!("Error while parsing IKE packet");
return AppLayerResult::err();
}
}
}
}
/// Probe to see if this input looks like a request or response.
fn probe(input: &[u8], direction: Direction, rdir: *mut u8) -> bool {
match parse_isakmp_header(input) {
Ok((_, isakmp_header)) => {
if isakmp_header.maj_ver == 1 {
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
} else if isakmp_header.maj_ver == 2 {
if isakmp_header.min_ver!= 0 {
SCLogDebug!(
"ipsec_probe: could be ipsec, but with unsupported/invalid version {}.{}",
isakmp_header.maj_ver,
isakmp_header.min_ver
);
return false;
}
if isakmp_header.exch_type < 34 || isakmp_header.exch_type > 37 {
SCLogDebug!("ipsec_probe: could be ipsec, but with unsupported/invalid exchange type {}",
isakmp_header.exch_type);
return false;
}
if isakmp_header.length as usize!= input.len() {
SCLogDebug!("ipsec_probe: could be ipsec, but length does not match");
return false;
}
if isakmp_header.resp_spi == 0 && direction!= Direction::ToServer {
unsafe {
*rdir = Direction::ToServer.into();
}
}
return true;
}
return false;
}
Err(_) => return false,
}
}
// C exports.
/// C entry point for a probing parser.
#[no_mangle]
pub unsafe extern "C" fn rs_ike_probing_parser(
_flow: *const Flow, direction: u8, input: *const u8, input_len: u32, rdir: *mut u8,
) -> AppProto {
if input_len < 28 {
// at least the ISAKMP_HEADER must be there, not ALPROTO_UNKNOWN because over UDP
return ALPROTO_FAILED;
}
if!input.is_null() {
let slice = build_slice!(input, input_len as usize);
if probe(slice, direction.into(), rdir) {
return ALPROTO_IKE;
}
}
return ALPROTO_FAILED;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_new(
_orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
) -> *mut std::os::raw::c_void {
let state = IKEState::default();
let boxed = Box::new(state);
return Box::into_raw(boxed) as *mut _;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_free(state: *mut std::os::raw::c_void) {
// Just unbox...
std::mem::drop(Box::from_raw(state as *mut IKEState));
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
let state = cast_pointer!(state, IKEState);
state.free_tx(tx_id);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_request(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToServer);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_parse_response(
_flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
stream_slice: StreamSlice,
_data: *const std::os::raw::c_void,
) -> AppLayerResult {
let state = cast_pointer!(state, IKEState);
return state.handle_input(stream_slice.as_slice(), Direction::ToClient);
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx(
state: *mut std::os::raw::c_void, tx_id: u64,
) -> *mut std::os::raw::c_void {
let state = cast_pointer!(state, IKEState);
match state.get_tx(tx_id) {
Some(tx) => {
return tx as *const _ as *mut _;
}
None => {
return std::ptr::null_mut();
}
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
let state = cast_pointer!(state, IKEState);
return state.tx_id;
}
#[no_mangle]
pub extern "C" fn rs_ike_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int {
// This parser uses 1 to signal transaction completion status.
return 1;
}
#[no_mangle]
pub extern "C" fn rs_ike_tx_get_alstate_progress(
_tx: *mut std::os::raw::c_void, _direction: u8,
) -> std::os::raw::c_int {
return 1;
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_get_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void,
) -> u32 {
let tx = cast_pointer!(tx, IKETransaction);
return tx.logged.get();
}
#[no_mangle]
pub unsafe extern "C" fn rs_ike_tx_set_logged(
_state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void, logged: u32,
) {
let tx = cast_pointer!(tx, IKETransaction);
tx.logged.set(logged);
}
static mut ALPROTO_IKE : AppProto = ALPROTO_UNKNOWN;
// Parser name as a C style string.
const PARSER_NAME: &'static [u8] = b"ike\0";
const PARSER_ALIAS: &'static [u8] = b"ikev2\0";
export_tx_data_get!(rs_ike_get_tx_data, IKETransaction);
#[no_mangle]
pub unsafe extern "C" fn rs_ike_register_parser() {
let default_port = CString::new("500").unwrap();
let parser = RustParser {
name : PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
default_port : default_port.as_ptr(),
ipproto : core::IPPROTO_UDP,
probe_ts : Some(rs_ike_probing_parser),
probe_tc : Some(rs_ike_probing_parser),
min_depth : 0,
max_depth : 16,
state_new : rs_ike_state_new,
state_free : rs_ike_state_free,
tx_free : rs_ike_state_tx_free,
parse_ts : rs_ike_parse_request,
parse_tc : rs_ike_parse_response,
get_tx_count : rs_ike_state_get_tx_count,
get_tx : rs_ike_state_get_tx,
tx_comp_st_ts : 1,
tx_comp_st_tc : 1,
tx_get_progress : rs_ike_tx_get_alstate_progress,
get_eventinfo : Some(IkeEvent::get_event_info),
get_eventinfo_byid : Some(IkeEvent::get_event_info_by_id),
localstorage_new : None,
localstorage_free : None,
get_files : None,
get_tx_iterator : Some(applayer::state_get_tx_iterator::<IKEState, IKETransaction>),
get_tx_data : rs_ike_get_tx_data,
apply_tx_config : None,
flags : APP_LAYER_PARSER_OPT_UNIDIR_TXS,
truncate : None,
get_frame_id_by_name: None,
get_frame_name_by_id: None,
|
if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
ALPROTO_IKE = alproto;
if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 {
let _ = AppLayerRegisterParser(&parser, alproto);
}
AppLayerRegisterParserAlias(
PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
PARSER_ALIAS.as_ptr() as *const std::os::raw::c_char,
);
SCLogDebug!("Rust IKE parser registered.");
} else {
SCLogDebug!("Protocol detector and parser disabled for IKE.");
}
}
|
};
let ip_proto_str = CString::new("udp").unwrap();
|
random_line_split
|
net.rs
|
//! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, AnyRefExt};
use std::boxed::BoxAny;
use std::fmt;
use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAddr, ToSocketAddr, Port};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use uany::UncheckedBoxAnyDowncast;
use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback};
use openssl::ssl::SslVerifyMode::SslVerifyPeer;
use openssl::ssl::SslMethod::Sslv23;
use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed};
use self::HttpStream::{Http, Https};
/// The write-status indicating headers have not been written.
#[allow(missing_copy_implementations)]
pub struct Fresh;
/// The write-status indicating headers have been written.
#[allow(missing_copy_implementations)]
pub struct Streaming;
/// An abstraction to listen for connections on a certain port.
pub trait NetworkListener<S: NetworkStream, A: NetworkAcceptor<S>>: Listener<S, A> {
/// Bind to a socket.
///
/// Note: This does not start listening for connections. You must call
/// `listen()` to do that.
fn bind<To: ToSocketAddr>(addr: To) -> IoResult<Self>;
/// Get the address this Listener ended up listening on.
fn socket_name(&mut self) -> IoResult<SocketAddr>;
}
/// An abstraction to receive `NetworkStream`s.
pub trait NetworkAcceptor<S: NetworkStream>: Acceptor<S> + Clone + Send {
/// Closes the Acceptor, so no more incoming connections will be handled.
fn close(&mut self) -> IoResult<()>;
}
/// An abstraction over streams that a Server can utilize.
pub trait NetworkStream: Stream + Any + StreamClone + Send {
/// Get the remote address of the underlying connection.
fn peer_name(&mut self) -> IoResult<SocketAddr>;
}
#[doc(hidden)]
pub trait StreamClone {
fn clone_box(&self) -> Box<NetworkStream + Send>;
}
impl<T: NetworkStream + Send + Clone> StreamClone for T {
#[inline]
fn clone_box(&self) -> Box<NetworkStream + Send> {
box self.clone()
}
}
/// A connector creates a NetworkStream.
pub trait NetworkConnector<S: NetworkStream> {
/// Connect to a remote address.
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<S>;
}
impl fmt::Show for Box<NetworkStream + Send> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad("Box<NetworkStream>")
}
}
impl Clone for Box<NetworkStream + Send> {
#[inline]
fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() }
}
impl Reader for Box<NetworkStream + Send> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) }
}
impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) }
}
impl<'a> Writer for &'a mut NetworkStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl UncheckedBoxAnyDowncast for Box<NetworkStream + Send> {
unsafe fn downcast_unchecked<T:'static>(self) -> Box<T> {
let to = *mem::transmute::<&Box<NetworkStream + Send>, &raw::TraitObject>(&self);
// Prevent double-free.
mem::forget(self);
mem::transmute(to.data)
}
}
impl<'a> AnyRefExt<'a> for &'a (NetworkStream + 'a) {
#[inline]
fn is<T:'static>(self) -> bool {
self.get_type_id() == TypeId::of::<T>()
}
#[inline]
fn downcast_ref<T:'static>(self) -> Option<&'a T>
|
}
impl BoxAny for Box<NetworkStream + Send> {
fn downcast<T:'static>(self) -> Result<Box<T>, Box<NetworkStream + Send>> {
if self.is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
}
}
}
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener {
inner: TcpListener
}
impl Listener<HttpStream, HttpAcceptor> for HttpListener {
#[inline]
fn listen(self) -> IoResult<HttpAcceptor> {
Ok(HttpAcceptor {
inner: try!(self.inner.listen())
})
}
}
impl NetworkListener<HttpStream, HttpAcceptor> for HttpListener {
#[inline]
fn bind<To: ToSocketAddr>(addr: To) -> IoResult<HttpListener> {
Ok(HttpListener {
inner: try!(TcpListener::bind(addr))
})
}
#[inline]
fn socket_name(&mut self) -> IoResult<SocketAddr> {
self.inner.socket_name()
}
}
/// A `NetworkAcceptor` for `HttpStream`s.
#[deriving(Clone)]
pub struct HttpAcceptor {
inner: TcpAcceptor
}
impl Acceptor<HttpStream> for HttpAcceptor {
#[inline]
fn accept(&mut self) -> IoResult<HttpStream> {
Ok(Http(try!(self.inner.accept())))
}
}
impl NetworkAcceptor<HttpStream> for HttpAcceptor {
#[inline]
fn close(&mut self) -> IoResult<()> {
self.inner.close_accept()
}
}
/// A wrapper around a TcpStream.
#[deriving(Clone)]
pub enum HttpStream {
/// A stream over the HTTP protocol.
Http(TcpStream),
/// A stream over the HTTP protocol, protected by SSL.
Https(SslStream<TcpStream>),
}
impl Reader for HttpStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match *self {
Http(ref mut inner) => inner.read(buf),
Https(ref mut inner) => inner.read(buf)
}
}
}
impl Writer for HttpStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> {
match *self {
Http(ref mut inner) => inner.write(msg),
Https(ref mut inner) => inner.write(msg)
}
}
#[inline]
fn flush(&mut self) -> IoResult<()> {
match *self {
Http(ref mut inner) => inner.flush(),
Https(ref mut inner) => inner.flush(),
}
}
}
impl NetworkStream for HttpStream {
fn peer_name(&mut self) -> IoResult<SocketAddr> {
match *self {
Http(ref mut inner) => inner.peer_name(),
Https(ref mut inner) => inner.get_mut().peer_name()
}
}
}
/// A connector that will produce HttpStreams.
#[allow(missing_copy_implementations)]
pub struct HttpConnector(pub Option<VerifyCallback>);
impl NetworkConnector<HttpStream> for HttpConnector {
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<HttpStream> {
let addr = (host, port);
match scheme {
"http" => {
debug!("http scheme");
Ok(Http(try!(TcpStream::connect(addr))))
},
"https" => {
debug!("https scheme");
let stream = try!(TcpStream::connect(addr));
let mut context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error));
self.0.as_ref().map(|cb| context.set_verify(SslVerifyPeer, Some(*cb)));
let ssl = try!(Ssl::new(&context).map_err(lift_ssl_error));
try!(ssl.set_hostname(host).map_err(lift_ssl_error));
let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error));
Ok(Https(stream))
},
_ => {
Err(IoError {
kind: InvalidInput,
desc: "Invalid scheme for Http",
detail: None
})
}
}
}
}
fn lift_ssl_error(ssl: SslError) -> IoError {
debug!("lift_ssl_error: {}", ssl);
match ssl {
StreamError(err) => err,
SslSessionClosed => IoError {
kind: ConnectionAborted,
desc: "SSL Connection Closed",
detail: None
},
// Unfortunately throw this away. No way to support this
// detail without a better Error abstraction.
OpenSslErrors(errs) => IoError {
kind: OtherIoError,
desc: "Error in OpenSSL",
detail: Some(format!("{}", errs))
}
}
}
#[cfg(test)]
mod tests {
use std::boxed::BoxAny;
use uany::UncheckedBoxAnyDowncast;
use mock::MockStream;
use super::NetworkStream;
#[test]
fn test_downcast_box_stream() {
let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = stream.downcast::<MockStream>().unwrap();
assert_eq!(mock, box MockStream::new());
}
#[test]
fn test_downcast_unchecked_box_stream() {
let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
assert_eq!(mock, box MockStream::new());
}
}
|
{
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
|
identifier_body
|
net.rs
|
//! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, AnyRefExt};
use std::boxed::BoxAny;
use std::fmt;
use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAddr, ToSocketAddr, Port};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use uany::UncheckedBoxAnyDowncast;
use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback};
use openssl::ssl::SslVerifyMode::SslVerifyPeer;
use openssl::ssl::SslMethod::Sslv23;
use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed};
use self::HttpStream::{Http, Https};
/// The write-status indicating headers have not been written.
#[allow(missing_copy_implementations)]
pub struct Fresh;
/// The write-status indicating headers have been written.
#[allow(missing_copy_implementations)]
pub struct Streaming;
/// An abstraction to listen for connections on a certain port.
pub trait NetworkListener<S: NetworkStream, A: NetworkAcceptor<S>>: Listener<S, A> {
/// Bind to a socket.
///
/// Note: This does not start listening for connections. You must call
/// `listen()` to do that.
fn bind<To: ToSocketAddr>(addr: To) -> IoResult<Self>;
/// Get the address this Listener ended up listening on.
fn socket_name(&mut self) -> IoResult<SocketAddr>;
}
/// An abstraction to receive `NetworkStream`s.
pub trait NetworkAcceptor<S: NetworkStream>: Acceptor<S> + Clone + Send {
/// Closes the Acceptor, so no more incoming connections will be handled.
fn close(&mut self) -> IoResult<()>;
}
/// An abstraction over streams that a Server can utilize.
pub trait NetworkStream: Stream + Any + StreamClone + Send {
/// Get the remote address of the underlying connection.
fn peer_name(&mut self) -> IoResult<SocketAddr>;
}
#[doc(hidden)]
pub trait StreamClone {
fn clone_box(&self) -> Box<NetworkStream + Send>;
}
impl<T: NetworkStream + Send + Clone> StreamClone for T {
#[inline]
fn clone_box(&self) -> Box<NetworkStream + Send> {
box self.clone()
}
}
/// A connector creates a NetworkStream.
pub trait NetworkConnector<S: NetworkStream> {
/// Connect to a remote address.
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<S>;
}
impl fmt::Show for Box<NetworkStream + Send> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad("Box<NetworkStream>")
}
}
impl Clone for Box<NetworkStream + Send> {
#[inline]
fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() }
}
impl Reader for Box<NetworkStream + Send> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) }
}
impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn
|
(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) }
}
impl<'a> Writer for &'a mut NetworkStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl UncheckedBoxAnyDowncast for Box<NetworkStream + Send> {
unsafe fn downcast_unchecked<T:'static>(self) -> Box<T> {
let to = *mem::transmute::<&Box<NetworkStream + Send>, &raw::TraitObject>(&self);
// Prevent double-free.
mem::forget(self);
mem::transmute(to.data)
}
}
impl<'a> AnyRefExt<'a> for &'a (NetworkStream + 'a) {
#[inline]
fn is<T:'static>(self) -> bool {
self.get_type_id() == TypeId::of::<T>()
}
#[inline]
fn downcast_ref<T:'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
impl BoxAny for Box<NetworkStream + Send> {
fn downcast<T:'static>(self) -> Result<Box<T>, Box<NetworkStream + Send>> {
if self.is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
}
}
}
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener {
inner: TcpListener
}
impl Listener<HttpStream, HttpAcceptor> for HttpListener {
#[inline]
fn listen(self) -> IoResult<HttpAcceptor> {
Ok(HttpAcceptor {
inner: try!(self.inner.listen())
})
}
}
impl NetworkListener<HttpStream, HttpAcceptor> for HttpListener {
#[inline]
fn bind<To: ToSocketAddr>(addr: To) -> IoResult<HttpListener> {
Ok(HttpListener {
inner: try!(TcpListener::bind(addr))
})
}
#[inline]
fn socket_name(&mut self) -> IoResult<SocketAddr> {
self.inner.socket_name()
}
}
/// A `NetworkAcceptor` for `HttpStream`s.
#[deriving(Clone)]
pub struct HttpAcceptor {
inner: TcpAcceptor
}
impl Acceptor<HttpStream> for HttpAcceptor {
#[inline]
fn accept(&mut self) -> IoResult<HttpStream> {
Ok(Http(try!(self.inner.accept())))
}
}
impl NetworkAcceptor<HttpStream> for HttpAcceptor {
#[inline]
fn close(&mut self) -> IoResult<()> {
self.inner.close_accept()
}
}
/// A wrapper around a TcpStream.
#[deriving(Clone)]
pub enum HttpStream {
/// A stream over the HTTP protocol.
Http(TcpStream),
/// A stream over the HTTP protocol, protected by SSL.
Https(SslStream<TcpStream>),
}
impl Reader for HttpStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match *self {
Http(ref mut inner) => inner.read(buf),
Https(ref mut inner) => inner.read(buf)
}
}
}
impl Writer for HttpStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> {
match *self {
Http(ref mut inner) => inner.write(msg),
Https(ref mut inner) => inner.write(msg)
}
}
#[inline]
fn flush(&mut self) -> IoResult<()> {
match *self {
Http(ref mut inner) => inner.flush(),
Https(ref mut inner) => inner.flush(),
}
}
}
impl NetworkStream for HttpStream {
fn peer_name(&mut self) -> IoResult<SocketAddr> {
match *self {
Http(ref mut inner) => inner.peer_name(),
Https(ref mut inner) => inner.get_mut().peer_name()
}
}
}
/// A connector that will produce HttpStreams.
#[allow(missing_copy_implementations)]
pub struct HttpConnector(pub Option<VerifyCallback>);
impl NetworkConnector<HttpStream> for HttpConnector {
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<HttpStream> {
let addr = (host, port);
match scheme {
"http" => {
debug!("http scheme");
Ok(Http(try!(TcpStream::connect(addr))))
},
"https" => {
debug!("https scheme");
let stream = try!(TcpStream::connect(addr));
let mut context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error));
self.0.as_ref().map(|cb| context.set_verify(SslVerifyPeer, Some(*cb)));
let ssl = try!(Ssl::new(&context).map_err(lift_ssl_error));
try!(ssl.set_hostname(host).map_err(lift_ssl_error));
let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error));
Ok(Https(stream))
},
_ => {
Err(IoError {
kind: InvalidInput,
desc: "Invalid scheme for Http",
detail: None
})
}
}
}
}
fn lift_ssl_error(ssl: SslError) -> IoError {
debug!("lift_ssl_error: {}", ssl);
match ssl {
StreamError(err) => err,
SslSessionClosed => IoError {
kind: ConnectionAborted,
desc: "SSL Connection Closed",
detail: None
},
// Unfortunately throw this away. No way to support this
// detail without a better Error abstraction.
OpenSslErrors(errs) => IoError {
kind: OtherIoError,
desc: "Error in OpenSSL",
detail: Some(format!("{}", errs))
}
}
}
#[cfg(test)]
mod tests {
use std::boxed::BoxAny;
use uany::UncheckedBoxAnyDowncast;
use mock::MockStream;
use super::NetworkStream;
#[test]
fn test_downcast_box_stream() {
let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = stream.downcast::<MockStream>().unwrap();
assert_eq!(mock, box MockStream::new());
}
#[test]
fn test_downcast_unchecked_box_stream() {
let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
assert_eq!(mock, box MockStream::new());
}
}
|
flush
|
identifier_name
|
net.rs
|
//! A collection of traits abstracting over Listeners and Streams.
use std::any::{Any, AnyRefExt};
use std::boxed::BoxAny;
use std::fmt;
use std::intrinsics::TypeId;
use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError,
Stream, Listener, Acceptor};
use std::io::net::ip::{SocketAddr, ToSocketAddr, Port};
use std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor};
use std::mem::{mod, transmute, transmute_copy};
use std::raw::{mod, TraitObject};
use uany::UncheckedBoxAnyDowncast;
use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback};
use openssl::ssl::SslVerifyMode::SslVerifyPeer;
use openssl::ssl::SslMethod::Sslv23;
use openssl::ssl::error::{SslError, StreamError, OpenSslErrors, SslSessionClosed};
use self::HttpStream::{Http, Https};
/// The write-status indicating headers have not been written.
#[allow(missing_copy_implementations)]
pub struct Fresh;
/// The write-status indicating headers have been written.
#[allow(missing_copy_implementations)]
pub struct Streaming;
/// An abstraction to listen for connections on a certain port.
pub trait NetworkListener<S: NetworkStream, A: NetworkAcceptor<S>>: Listener<S, A> {
/// Bind to a socket.
///
/// Note: This does not start listening for connections. You must call
/// `listen()` to do that.
fn bind<To: ToSocketAddr>(addr: To) -> IoResult<Self>;
/// Get the address this Listener ended up listening on.
fn socket_name(&mut self) -> IoResult<SocketAddr>;
}
/// An abstraction to receive `NetworkStream`s.
pub trait NetworkAcceptor<S: NetworkStream>: Acceptor<S> + Clone + Send {
/// Closes the Acceptor, so no more incoming connections will be handled.
fn close(&mut self) -> IoResult<()>;
}
/// An abstraction over streams that a Server can utilize.
pub trait NetworkStream: Stream + Any + StreamClone + Send {
/// Get the remote address of the underlying connection.
fn peer_name(&mut self) -> IoResult<SocketAddr>;
}
#[doc(hidden)]
pub trait StreamClone {
fn clone_box(&self) -> Box<NetworkStream + Send>;
}
impl<T: NetworkStream + Send + Clone> StreamClone for T {
#[inline]
fn clone_box(&self) -> Box<NetworkStream + Send> {
box self.clone()
}
}
/// A connector creates a NetworkStream.
pub trait NetworkConnector<S: NetworkStream> {
/// Connect to a remote address.
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<S>;
}
impl fmt::Show for Box<NetworkStream + Send> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad("Box<NetworkStream>")
}
|
impl Clone for Box<NetworkStream + Send> {
#[inline]
fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() }
}
impl Reader for Box<NetworkStream + Send> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) }
}
impl Writer for Box<NetworkStream + Send> {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl<'a> Reader for &'a mut NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) }
}
impl<'a> Writer for &'a mut NetworkStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(msg) }
#[inline]
fn flush(&mut self) -> IoResult<()> { (**self).flush() }
}
impl UncheckedBoxAnyDowncast for Box<NetworkStream + Send> {
unsafe fn downcast_unchecked<T:'static>(self) -> Box<T> {
let to = *mem::transmute::<&Box<NetworkStream + Send>, &raw::TraitObject>(&self);
// Prevent double-free.
mem::forget(self);
mem::transmute(to.data)
}
}
impl<'a> AnyRefExt<'a> for &'a (NetworkStream + 'a) {
#[inline]
fn is<T:'static>(self) -> bool {
self.get_type_id() == TypeId::of::<T>()
}
#[inline]
fn downcast_ref<T:'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
impl BoxAny for Box<NetworkStream + Send> {
fn downcast<T:'static>(self) -> Result<Box<T>, Box<NetworkStream + Send>> {
if self.is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
}
}
}
/// A `NetworkListener` for `HttpStream`s.
pub struct HttpListener {
inner: TcpListener
}
impl Listener<HttpStream, HttpAcceptor> for HttpListener {
#[inline]
fn listen(self) -> IoResult<HttpAcceptor> {
Ok(HttpAcceptor {
inner: try!(self.inner.listen())
})
}
}
impl NetworkListener<HttpStream, HttpAcceptor> for HttpListener {
#[inline]
fn bind<To: ToSocketAddr>(addr: To) -> IoResult<HttpListener> {
Ok(HttpListener {
inner: try!(TcpListener::bind(addr))
})
}
#[inline]
fn socket_name(&mut self) -> IoResult<SocketAddr> {
self.inner.socket_name()
}
}
/// A `NetworkAcceptor` for `HttpStream`s.
#[deriving(Clone)]
pub struct HttpAcceptor {
inner: TcpAcceptor
}
impl Acceptor<HttpStream> for HttpAcceptor {
#[inline]
fn accept(&mut self) -> IoResult<HttpStream> {
Ok(Http(try!(self.inner.accept())))
}
}
impl NetworkAcceptor<HttpStream> for HttpAcceptor {
#[inline]
fn close(&mut self) -> IoResult<()> {
self.inner.close_accept()
}
}
/// A wrapper around a TcpStream.
#[deriving(Clone)]
pub enum HttpStream {
/// A stream over the HTTP protocol.
Http(TcpStream),
/// A stream over the HTTP protocol, protected by SSL.
Https(SslStream<TcpStream>),
}
impl Reader for HttpStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
match *self {
Http(ref mut inner) => inner.read(buf),
Https(ref mut inner) => inner.read(buf)
}
}
}
impl Writer for HttpStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> IoResult<()> {
match *self {
Http(ref mut inner) => inner.write(msg),
Https(ref mut inner) => inner.write(msg)
}
}
#[inline]
fn flush(&mut self) -> IoResult<()> {
match *self {
Http(ref mut inner) => inner.flush(),
Https(ref mut inner) => inner.flush(),
}
}
}
impl NetworkStream for HttpStream {
fn peer_name(&mut self) -> IoResult<SocketAddr> {
match *self {
Http(ref mut inner) => inner.peer_name(),
Https(ref mut inner) => inner.get_mut().peer_name()
}
}
}
/// A connector that will produce HttpStreams.
#[allow(missing_copy_implementations)]
pub struct HttpConnector(pub Option<VerifyCallback>);
impl NetworkConnector<HttpStream> for HttpConnector {
fn connect(&mut self, host: &str, port: Port, scheme: &str) -> IoResult<HttpStream> {
let addr = (host, port);
match scheme {
"http" => {
debug!("http scheme");
Ok(Http(try!(TcpStream::connect(addr))))
},
"https" => {
debug!("https scheme");
let stream = try!(TcpStream::connect(addr));
let mut context = try!(SslContext::new(Sslv23).map_err(lift_ssl_error));
self.0.as_ref().map(|cb| context.set_verify(SslVerifyPeer, Some(*cb)));
let ssl = try!(Ssl::new(&context).map_err(lift_ssl_error));
try!(ssl.set_hostname(host).map_err(lift_ssl_error));
let stream = try!(SslStream::new(&context, stream).map_err(lift_ssl_error));
Ok(Https(stream))
},
_ => {
Err(IoError {
kind: InvalidInput,
desc: "Invalid scheme for Http",
detail: None
})
}
}
}
}
fn lift_ssl_error(ssl: SslError) -> IoError {
debug!("lift_ssl_error: {}", ssl);
match ssl {
StreamError(err) => err,
SslSessionClosed => IoError {
kind: ConnectionAborted,
desc: "SSL Connection Closed",
detail: None
},
// Unfortunately throw this away. No way to support this
// detail without a better Error abstraction.
OpenSslErrors(errs) => IoError {
kind: OtherIoError,
desc: "Error in OpenSSL",
detail: Some(format!("{}", errs))
}
}
}
#[cfg(test)]
mod tests {
use std::boxed::BoxAny;
use uany::UncheckedBoxAnyDowncast;
use mock::MockStream;
use super::NetworkStream;
#[test]
fn test_downcast_box_stream() {
let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = stream.downcast::<MockStream>().unwrap();
assert_eq!(mock, box MockStream::new());
}
#[test]
fn test_downcast_unchecked_box_stream() {
let stream = box MockStream::new() as Box<NetworkStream + Send>;
let mock = unsafe { stream.downcast_unchecked::<MockStream>() };
assert_eq!(mock, box MockStream::new());
}
}
|
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.