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 |
---|---|---|---|---|
udp-multicast.rs | use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr};
fn main() {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000;
let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 | else {
let socket = UdpSocket::bind((any, 0)).expect("Could not bind socket");
socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)).expect("Failed to write data");
}
}
| {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group");
socket.recv_from(&mut buffer).expect("Failed to write to server");
print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string"));
} | conditional_block |
udp-multicast.rs | use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr};
fn main() | {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000;
let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group");
socket.recv_from(&mut buffer).expect("Failed to write to server");
print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string"));
} else {
let socket = UdpSocket::bind((any, 0)).expect("Could not bind socket");
socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)).expect("Failed to write data");
}
} | identifier_body |
|
mod.rs | //! Messaging primitives for discovering devices and services.
use std::io;
#[cfg(windows)]
use std::net;
use std::net::SocketAddr;
use net::connector::UdpConnector;
use net::IpVersionMode;
mod notify;
mod search;
mod ssdp;
pub mod listen;
pub mod multicast;
pub use message::multicast::Multicast;
pub use message::search::{SearchRequest, SearchResponse, SearchListener};
pub use message::notify::{NotifyMessage, NotifyListener};
pub use message::listen::Listen;
#[cfg(not(windows))]
use ifaces;
/// Multicast Socket Information
pub const UPNP_MULTICAST_IPV4_ADDR: &'static str = "239.255.255.250";
pub const UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR: &'static str = "FF02::C";
pub const UPNP_MULTICAST_PORT: u16 = 1900;
/// Default TTL For Multicast
pub const UPNP_MULTICAST_TTL: u32 = 2;
/// Enumerates different types of SSDP messages.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum MessageType {
/// A notify message.
Notify,
/// A search message.
Search,
/// A response to a search message.
Response,
}
#[derive(Clone)]
pub struct Config {
pub ipv4_addr: String,
pub ipv6_addr: String,
pub port: u16,
pub ttl: u32,
pub mode: IpVersionMode,
}
impl Config {
pub fn new() -> Self {
Default::default()
}
pub fn set_ipv4_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv4_addr = value.into();
self
}
pub fn set_ipv6_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv6_addr = value.into();
self
}
pub fn set_port(mut self, value: u16) -> Self {
self.port = value;
self
}
pub fn set_ttl(mut self, value: u32) -> Self {
self.ttl = value;
self
}
pub fn set_mode(mut self, value: IpVersionMode) -> Self {
self.mode = value;
self
}
}
impl Default for Config {
fn default() -> Self {
Config {
ipv4_addr: UPNP_MULTICAST_IPV4_ADDR.to_string(),
ipv6_addr: UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR.to_string(),
port: UPNP_MULTICAST_PORT,
ttl: UPNP_MULTICAST_TTL,
mode: IpVersionMode::Any,
}
}
}
/// Generate `UdpConnector` objects for all local `IPv4` interfaces.
fn all_local_connectors(multicast_ttl: Option<u32>, filter: &IpVersionMode) -> io::Result<Vec<UdpConnector>> {
trace!("Fetching all local connectors");
map_local(|&addr| match (filter, addr) {
(&IpVersionMode::V4Only, SocketAddr::V4(n)) |
(&IpVersionMode::Any, SocketAddr::V4(n)) => {
Ok(Some(try!(UdpConnector::new((*n.ip(), 0), multicast_ttl))))
}
(&IpVersionMode::V6Only, SocketAddr::V6(n)) |
(&IpVersionMode::Any, SocketAddr::V6(n)) => Ok(Some(try!(UdpConnector::new(n, multicast_ttl)))),
_ => Ok(None),
})
}
/// Invoke the closure for every local address found on the system
///
/// This method filters out _loopback_ and _global_ addresses.
fn map_local<F, R>(mut f: F) -> io::Result<Vec<R>>
where F: FnMut(&SocketAddr) -> io::Result<Option<R>>
{
let addrs_iter = try!(get_local_addrs());
let mut obj_list = Vec::with_capacity(addrs_iter.len());
for addr in addrs_iter {
trace!("Found {}", addr);
match addr {
SocketAddr::V4(n) if!n.ip().is_loopback() => {
if let Some(x) = try!(f(&addr)) |
}
// Filter all loopback and global IPv6 addresses
SocketAddr::V6(n) if!n.ip().is_loopback() &&!n.ip().is_global() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
_ => (),
}
}
Ok(obj_list)
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(windows)]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let host_iter = try!(net::lookup_host(""));
Ok(host_iter.collect())
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(not(windows))]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let iface_iter = try!(ifaces::Interface::get_all()).into_iter();
Ok(iface_iter.filter(|iface| iface.kind!= ifaces::Kind::Packet)
.filter_map(|iface| iface.addr)
.collect())
}
| {
obj_list.push(x);
} | conditional_block |
mod.rs | //! Messaging primitives for discovering devices and services.
use std::io;
#[cfg(windows)]
use std::net;
use std::net::SocketAddr;
use net::connector::UdpConnector;
use net::IpVersionMode;
mod notify;
mod search;
mod ssdp;
pub mod listen;
pub mod multicast;
pub use message::multicast::Multicast;
pub use message::search::{SearchRequest, SearchResponse, SearchListener};
pub use message::notify::{NotifyMessage, NotifyListener};
pub use message::listen::Listen;
#[cfg(not(windows))]
use ifaces;
/// Multicast Socket Information
pub const UPNP_MULTICAST_IPV4_ADDR: &'static str = "239.255.255.250";
pub const UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR: &'static str = "FF02::C";
pub const UPNP_MULTICAST_PORT: u16 = 1900;
/// Default TTL For Multicast
pub const UPNP_MULTICAST_TTL: u32 = 2;
/// Enumerates different types of SSDP messages.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum MessageType {
/// A notify message.
Notify,
/// A search message.
Search,
/// A response to a search message.
Response,
}
#[derive(Clone)]
pub struct Config {
pub ipv4_addr: String,
pub ipv6_addr: String,
pub port: u16,
pub ttl: u32,
pub mode: IpVersionMode,
}
impl Config {
pub fn new() -> Self {
Default::default()
}
pub fn set_ipv4_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv4_addr = value.into();
self
}
pub fn set_ipv6_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv6_addr = value.into();
self
}
pub fn set_port(mut self, value: u16) -> Self {
self.port = value;
self | self.ttl = value;
self
}
pub fn set_mode(mut self, value: IpVersionMode) -> Self {
self.mode = value;
self
}
}
impl Default for Config {
fn default() -> Self {
Config {
ipv4_addr: UPNP_MULTICAST_IPV4_ADDR.to_string(),
ipv6_addr: UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR.to_string(),
port: UPNP_MULTICAST_PORT,
ttl: UPNP_MULTICAST_TTL,
mode: IpVersionMode::Any,
}
}
}
/// Generate `UdpConnector` objects for all local `IPv4` interfaces.
fn all_local_connectors(multicast_ttl: Option<u32>, filter: &IpVersionMode) -> io::Result<Vec<UdpConnector>> {
trace!("Fetching all local connectors");
map_local(|&addr| match (filter, addr) {
(&IpVersionMode::V4Only, SocketAddr::V4(n)) |
(&IpVersionMode::Any, SocketAddr::V4(n)) => {
Ok(Some(try!(UdpConnector::new((*n.ip(), 0), multicast_ttl))))
}
(&IpVersionMode::V6Only, SocketAddr::V6(n)) |
(&IpVersionMode::Any, SocketAddr::V6(n)) => Ok(Some(try!(UdpConnector::new(n, multicast_ttl)))),
_ => Ok(None),
})
}
/// Invoke the closure for every local address found on the system
///
/// This method filters out _loopback_ and _global_ addresses.
fn map_local<F, R>(mut f: F) -> io::Result<Vec<R>>
where F: FnMut(&SocketAddr) -> io::Result<Option<R>>
{
let addrs_iter = try!(get_local_addrs());
let mut obj_list = Vec::with_capacity(addrs_iter.len());
for addr in addrs_iter {
trace!("Found {}", addr);
match addr {
SocketAddr::V4(n) if!n.ip().is_loopback() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
// Filter all loopback and global IPv6 addresses
SocketAddr::V6(n) if!n.ip().is_loopback() &&!n.ip().is_global() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
_ => (),
}
}
Ok(obj_list)
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(windows)]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let host_iter = try!(net::lookup_host(""));
Ok(host_iter.collect())
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(not(windows))]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let iface_iter = try!(ifaces::Interface::get_all()).into_iter();
Ok(iface_iter.filter(|iface| iface.kind!= ifaces::Kind::Packet)
.filter_map(|iface| iface.addr)
.collect())
} | }
pub fn set_ttl(mut self, value: u32) -> Self { | random_line_split |
mod.rs | //! Messaging primitives for discovering devices and services.
use std::io;
#[cfg(windows)]
use std::net;
use std::net::SocketAddr;
use net::connector::UdpConnector;
use net::IpVersionMode;
mod notify;
mod search;
mod ssdp;
pub mod listen;
pub mod multicast;
pub use message::multicast::Multicast;
pub use message::search::{SearchRequest, SearchResponse, SearchListener};
pub use message::notify::{NotifyMessage, NotifyListener};
pub use message::listen::Listen;
#[cfg(not(windows))]
use ifaces;
/// Multicast Socket Information
pub const UPNP_MULTICAST_IPV4_ADDR: &'static str = "239.255.255.250";
pub const UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR: &'static str = "FF02::C";
pub const UPNP_MULTICAST_PORT: u16 = 1900;
/// Default TTL For Multicast
pub const UPNP_MULTICAST_TTL: u32 = 2;
/// Enumerates different types of SSDP messages.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum MessageType {
/// A notify message.
Notify,
/// A search message.
Search,
/// A response to a search message.
Response,
}
#[derive(Clone)]
pub struct Config {
pub ipv4_addr: String,
pub ipv6_addr: String,
pub port: u16,
pub ttl: u32,
pub mode: IpVersionMode,
}
impl Config {
pub fn new() -> Self {
Default::default()
}
pub fn set_ipv4_addr<S: Into<String>>(mut self, value: S) -> Self |
pub fn set_ipv6_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv6_addr = value.into();
self
}
pub fn set_port(mut self, value: u16) -> Self {
self.port = value;
self
}
pub fn set_ttl(mut self, value: u32) -> Self {
self.ttl = value;
self
}
pub fn set_mode(mut self, value: IpVersionMode) -> Self {
self.mode = value;
self
}
}
impl Default for Config {
fn default() -> Self {
Config {
ipv4_addr: UPNP_MULTICAST_IPV4_ADDR.to_string(),
ipv6_addr: UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR.to_string(),
port: UPNP_MULTICAST_PORT,
ttl: UPNP_MULTICAST_TTL,
mode: IpVersionMode::Any,
}
}
}
/// Generate `UdpConnector` objects for all local `IPv4` interfaces.
fn all_local_connectors(multicast_ttl: Option<u32>, filter: &IpVersionMode) -> io::Result<Vec<UdpConnector>> {
trace!("Fetching all local connectors");
map_local(|&addr| match (filter, addr) {
(&IpVersionMode::V4Only, SocketAddr::V4(n)) |
(&IpVersionMode::Any, SocketAddr::V4(n)) => {
Ok(Some(try!(UdpConnector::new((*n.ip(), 0), multicast_ttl))))
}
(&IpVersionMode::V6Only, SocketAddr::V6(n)) |
(&IpVersionMode::Any, SocketAddr::V6(n)) => Ok(Some(try!(UdpConnector::new(n, multicast_ttl)))),
_ => Ok(None),
})
}
/// Invoke the closure for every local address found on the system
///
/// This method filters out _loopback_ and _global_ addresses.
fn map_local<F, R>(mut f: F) -> io::Result<Vec<R>>
where F: FnMut(&SocketAddr) -> io::Result<Option<R>>
{
let addrs_iter = try!(get_local_addrs());
let mut obj_list = Vec::with_capacity(addrs_iter.len());
for addr in addrs_iter {
trace!("Found {}", addr);
match addr {
SocketAddr::V4(n) if!n.ip().is_loopback() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
// Filter all loopback and global IPv6 addresses
SocketAddr::V6(n) if!n.ip().is_loopback() &&!n.ip().is_global() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
_ => (),
}
}
Ok(obj_list)
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(windows)]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let host_iter = try!(net::lookup_host(""));
Ok(host_iter.collect())
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(not(windows))]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let iface_iter = try!(ifaces::Interface::get_all()).into_iter();
Ok(iface_iter.filter(|iface| iface.kind!= ifaces::Kind::Packet)
.filter_map(|iface| iface.addr)
.collect())
}
| {
self.ipv4_addr = value.into();
self
} | identifier_body |
mod.rs | //! Messaging primitives for discovering devices and services.
use std::io;
#[cfg(windows)]
use std::net;
use std::net::SocketAddr;
use net::connector::UdpConnector;
use net::IpVersionMode;
mod notify;
mod search;
mod ssdp;
pub mod listen;
pub mod multicast;
pub use message::multicast::Multicast;
pub use message::search::{SearchRequest, SearchResponse, SearchListener};
pub use message::notify::{NotifyMessage, NotifyListener};
pub use message::listen::Listen;
#[cfg(not(windows))]
use ifaces;
/// Multicast Socket Information
pub const UPNP_MULTICAST_IPV4_ADDR: &'static str = "239.255.255.250";
pub const UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR: &'static str = "FF02::C";
pub const UPNP_MULTICAST_PORT: u16 = 1900;
/// Default TTL For Multicast
pub const UPNP_MULTICAST_TTL: u32 = 2;
/// Enumerates different types of SSDP messages.
#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
pub enum MessageType {
/// A notify message.
Notify,
/// A search message.
Search,
/// A response to a search message.
Response,
}
#[derive(Clone)]
pub struct Config {
pub ipv4_addr: String,
pub ipv6_addr: String,
pub port: u16,
pub ttl: u32,
pub mode: IpVersionMode,
}
impl Config {
pub fn new() -> Self {
Default::default()
}
pub fn set_ipv4_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv4_addr = value.into();
self
}
pub fn set_ipv6_addr<S: Into<String>>(mut self, value: S) -> Self {
self.ipv6_addr = value.into();
self
}
pub fn set_port(mut self, value: u16) -> Self {
self.port = value;
self
}
pub fn set_ttl(mut self, value: u32) -> Self {
self.ttl = value;
self
}
pub fn set_mode(mut self, value: IpVersionMode) -> Self {
self.mode = value;
self
}
}
impl Default for Config {
fn default() -> Self {
Config {
ipv4_addr: UPNP_MULTICAST_IPV4_ADDR.to_string(),
ipv6_addr: UPNP_MULTICAST_IPV6_LINK_LOCAL_ADDR.to_string(),
port: UPNP_MULTICAST_PORT,
ttl: UPNP_MULTICAST_TTL,
mode: IpVersionMode::Any,
}
}
}
/// Generate `UdpConnector` objects for all local `IPv4` interfaces.
fn all_local_connectors(multicast_ttl: Option<u32>, filter: &IpVersionMode) -> io::Result<Vec<UdpConnector>> {
trace!("Fetching all local connectors");
map_local(|&addr| match (filter, addr) {
(&IpVersionMode::V4Only, SocketAddr::V4(n)) |
(&IpVersionMode::Any, SocketAddr::V4(n)) => {
Ok(Some(try!(UdpConnector::new((*n.ip(), 0), multicast_ttl))))
}
(&IpVersionMode::V6Only, SocketAddr::V6(n)) |
(&IpVersionMode::Any, SocketAddr::V6(n)) => Ok(Some(try!(UdpConnector::new(n, multicast_ttl)))),
_ => Ok(None),
})
}
/// Invoke the closure for every local address found on the system
///
/// This method filters out _loopback_ and _global_ addresses.
fn map_local<F, R>(mut f: F) -> io::Result<Vec<R>>
where F: FnMut(&SocketAddr) -> io::Result<Option<R>>
{
let addrs_iter = try!(get_local_addrs());
let mut obj_list = Vec::with_capacity(addrs_iter.len());
for addr in addrs_iter {
trace!("Found {}", addr);
match addr {
SocketAddr::V4(n) if!n.ip().is_loopback() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
// Filter all loopback and global IPv6 addresses
SocketAddr::V6(n) if!n.ip().is_loopback() &&!n.ip().is_global() => {
if let Some(x) = try!(f(&addr)) {
obj_list.push(x);
}
}
_ => (),
}
}
Ok(obj_list)
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(windows)]
fn get_local_addrs() -> io::Result<Vec<SocketAddr>> {
let host_iter = try!(net::lookup_host(""));
Ok(host_iter.collect())
}
/// Generate a list of some object R constructed from all local `Ipv4Addr` objects.
///
/// If any of the `SocketAddr`'s fail to resolve, this function will not return an error.
#[cfg(not(windows))]
fn | () -> io::Result<Vec<SocketAddr>> {
let iface_iter = try!(ifaces::Interface::get_all()).into_iter();
Ok(iface_iter.filter(|iface| iface.kind!= ifaces::Kind::Packet)
.filter_map(|iface| iface.addr)
.collect())
}
| get_local_addrs | identifier_name |
win.rs | use std::fs;
use std::path::Path;
use app_dirs::{self, AppDataType};
use util::*;
const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll";
const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll";
const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll";
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_MN_DLL_DL_HASH: [u8; 48] = [
0x2d, 0x27, 0x17, 0x03, 0x95, 0x97, 0xde, 0x0b, 0xf4, 0x88, 0x14, 0xad, 0xee, 0x90, 0xa2, 0xb8,
0xac, 0xfd, 0x9d, 0xab, 0x29, 0xf3, 0x7a, 0x64, 0xbf, 0x94, 0x8f, 0xb5, 0x5f, 0xcf, 0x9c, 0xa7,
0x8f, 0xb0, 0x5f, 0x92, 0x22, 0x27, 0x31, 0x65, 0xe2, 0x3c, 0x5c, 0xa2, 0xab, 0x87, 0x4d, 0x21,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_GL_DLL_DL_HASH: [u8; 48] = [
0xbc, 0x81, 0x45, 0xc4, 0x7d, 0x3c, 0xa6, 0x96, 0x5c, 0xe5, 0x19, 0x2e, 0x2a, 0xd7, 0xe6, 0xe7,
0x26, 0x26, 0xdd, 0x8c, 0x3b, 0xe9, 0x6a, 0xa9, 0x30, 0x75, 0x69, 0x36, 0x1f, 0x30, 0x34, 0x5b,
0x7b, 0x11, 0x24, 0xfb, 0x1d, 0x09, 0x2c, 0x0a, 0xdd, 0xb3, 0x82, 0x0b, 0x53, 0xa3, 0x8a, 0x78,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_D9_DLL_DL_HASH: [u8; 48] = [
0xeb, 0x58, 0x44, 0x85, 0x9a, 0x39, 0xd6, 0x85, 0x3c, 0x1f, 0x14, 0x9c, 0xe0, 0x51, 0x16, 0x79,
0x1d, 0x2a, 0x45, 0x7a, 0x7f, 0x98, 0x41, 0xed, 0x07, 0xec, 0xdc, 0x1a, 0xc7, 0xc5, 0xad, 0xcb,
0x34, 0xd6, 0x30, 0x50, 0xbe, 0xe5, 0xad, 0xa5, 0x8e, 0xbd, 0x25, 0xb5, 0x02, 0xe7, 0x28, 0x24,
];
pub fn install() -> Result<()> {
info!("Backing up Nvidia Cg…");
backup_cg().chain_err(|| "Failed to backup Cg")?;
let cg_dir = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if!cg_dir.exists() {
info!("Downloading Nvidia Cg…");
let result = download_cg(&cg_dir);
if result.is_err() {
fs::remove_dir_all(&cg_dir)?;
}
result?;
} else {
info!("Nvidia Cg is already cached!")
}
info!("Updating Nvidia Cg…\n");
update_cg(&cg_dir).chain_err(|| "Failed to update Cg")?;
Ok(())
}
pub fn remove() -> Result<()> {
let cg_backup_path = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if!cg_backup_path.exists() {
return Err("No Cg backup found!".into());
}
info!("Restoring Nvidia Cg…");
update_cg(&cg_backup_path)?;
fs::remove_dir_all(&cg_backup_path)?;
info!("Removing Nvidia Cg backup…");
let cg_cache_path = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if cg_cache_path.exists() {
info!("Removing Nvidia Cg download cache…");
fs::remove_dir_all(cg_cache_path)?;
}
Ok(())
}
fn download_cg(cg_dir: &Path) -> Result<()> {
fs::create_dir(&cg_dir)?;
download(
&cg_dir.join("Cg.dll"),
CG_MN_DLL_DL,
Some(&CG_MN_DLL_DL_HASH),
)?;
download(
&cg_dir.join("CgGL.dll"),
CG_GL_DLL_DL,
Some(&CG_GL_DLL_DL_HASH),
)?;
download(
&cg_dir.join("cgD3D9.dll"),
CG_D9_DLL_DL,
Some(&CG_D9_DLL_DL_HASH),
)?;
Ok(())
}
#[test]
fn download_cg_ | tempdir::TempDir;
let target = TempDir::new("lolupdater-cg-target").unwrap();
download_cg(&target.path().join("cg")).unwrap();
}
fn backup_cg() -> Result<()> {
let cg_backup = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if cg_backup.exists() {
info!("Skipping NVIDIA Cg backup! (Already exists)");
} else {
fs::create_dir(&cg_backup)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
&cg_backup.join("Cg.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
&cg_backup.join("CgGL.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
&cg_backup.join("CgD3D9.dll"),
)?;
}
Ok(())
}
fn update_cg(cg_dir: &Path) -> Result<()> {
update_file(
&cg_dir.join("Cg.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
update_file(
&cg_dir.join("Cg.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
Ok(())
}
| works() {
use | identifier_name |
win.rs | use std::fs;
use std::path::Path;
use app_dirs::{self, AppDataType};
use util::*;
const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll";
const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll";
const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll";
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_MN_DLL_DL_HASH: [u8; 48] = [
0x2d, 0x27, 0x17, 0x03, 0x95, 0x97, 0xde, 0x0b, 0xf4, 0x88, 0x14, 0xad, 0xee, 0x90, 0xa2, 0xb8,
0xac, 0xfd, 0x9d, 0xab, 0x29, 0xf3, 0x7a, 0x64, 0xbf, 0x94, 0x8f, 0xb5, 0x5f, 0xcf, 0x9c, 0xa7,
0x8f, 0xb0, 0x5f, 0x92, 0x22, 0x27, 0x31, 0x65, 0xe2, 0x3c, 0x5c, 0xa2, 0xab, 0x87, 0x4d, 0x21,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_GL_DLL_DL_HASH: [u8; 48] = [
0xbc, 0x81, 0x45, 0xc4, 0x7d, 0x3c, 0xa6, 0x96, 0x5c, 0xe5, 0x19, 0x2e, 0x2a, 0xd7, 0xe6, 0xe7,
0x26, 0x26, 0xdd, 0x8c, 0x3b, 0xe9, 0x6a, 0xa9, 0x30, 0x75, 0x69, 0x36, 0x1f, 0x30, 0x34, 0x5b,
0x7b, 0x11, 0x24, 0xfb, 0x1d, 0x09, 0x2c, 0x0a, 0xdd, 0xb3, 0x82, 0x0b, 0x53, 0xa3, 0x8a, 0x78,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_D9_DLL_DL_HASH: [u8; 48] = [
0xeb, 0x58, 0x44, 0x85, 0x9a, 0x39, 0xd6, 0x85, 0x3c, 0x1f, 0x14, 0x9c, 0xe0, 0x51, 0x16, 0x79,
0x1d, 0x2a, 0x45, 0x7a, 0x7f, 0x98, 0x41, 0xed, 0x07, 0xec, 0xdc, 0x1a, 0xc7, 0xc5, 0xad, 0xcb,
0x34, 0xd6, 0x30, 0x50, 0xbe, 0xe5, 0xad, 0xa5, 0x8e, 0xbd, 0x25, 0xb5, 0x02, 0xe7, 0x28, 0x24,
];
pub fn install() -> Result<()> {
info!("Backing up Nvidia Cg…");
backup_cg().chain_err(|| "Failed to backup Cg")?;
let cg_dir = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if!cg_dir.exists() {
info!("Downloading Nvidia Cg…");
let result = download_cg(&cg_dir);
if result.is_err() {
fs::remove_dir_all(&cg_dir)?;
}
result?;
} else {
info!("Nvidia Cg is already cached!")
}
info!("Updating Nvidia Cg…\n");
update_cg(&cg_dir).chain_err(|| "Failed to update Cg")?;
Ok(())
}
pub fn remove() -> Result<()> {
let cg_backup_path = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if!cg_backup_path.exists() {
| nfo!("Restoring Nvidia Cg…");
update_cg(&cg_backup_path)?;
fs::remove_dir_all(&cg_backup_path)?;
info!("Removing Nvidia Cg backup…");
let cg_cache_path = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if cg_cache_path.exists() {
info!("Removing Nvidia Cg download cache…");
fs::remove_dir_all(cg_cache_path)?;
}
Ok(())
}
fn download_cg(cg_dir: &Path) -> Result<()> {
fs::create_dir(&cg_dir)?;
download(
&cg_dir.join("Cg.dll"),
CG_MN_DLL_DL,
Some(&CG_MN_DLL_DL_HASH),
)?;
download(
&cg_dir.join("CgGL.dll"),
CG_GL_DLL_DL,
Some(&CG_GL_DLL_DL_HASH),
)?;
download(
&cg_dir.join("cgD3D9.dll"),
CG_D9_DLL_DL,
Some(&CG_D9_DLL_DL_HASH),
)?;
Ok(())
}
#[test]
fn download_cg_works() {
use tempdir::TempDir;
let target = TempDir::new("lolupdater-cg-target").unwrap();
download_cg(&target.path().join("cg")).unwrap();
}
fn backup_cg() -> Result<()> {
let cg_backup = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if cg_backup.exists() {
info!("Skipping NVIDIA Cg backup! (Already exists)");
} else {
fs::create_dir(&cg_backup)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
&cg_backup.join("Cg.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
&cg_backup.join("CgGL.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
&cg_backup.join("CgD3D9.dll"),
)?;
}
Ok(())
}
fn update_cg(cg_dir: &Path) -> Result<()> {
update_file(
&cg_dir.join("Cg.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
update_file(
&cg_dir.join("Cg.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
Ok(())
}
| return Err("No Cg backup found!".into());
}
i | conditional_block |
win.rs | use std::fs;
use std::path::Path;
use app_dirs::{self, AppDataType};
use util::*;
const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll";
const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll";
const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll";
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_MN_DLL_DL_HASH: [u8; 48] = [
0x2d, 0x27, 0x17, 0x03, 0x95, 0x97, 0xde, 0x0b, 0xf4, 0x88, 0x14, 0xad, 0xee, 0x90, 0xa2, 0xb8,
0xac, 0xfd, 0x9d, 0xab, 0x29, 0xf3, 0x7a, 0x64, 0xbf, 0x94, 0x8f, 0xb5, 0x5f, 0xcf, 0x9c, 0xa7,
0x8f, 0xb0, 0x5f, 0x92, 0x22, 0x27, 0x31, 0x65, 0xe2, 0x3c, 0x5c, 0xa2, 0xab, 0x87, 0x4d, 0x21,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_GL_DLL_DL_HASH: [u8; 48] = [
0xbc, 0x81, 0x45, 0xc4, 0x7d, 0x3c, 0xa6, 0x96, 0x5c, 0xe5, 0x19, 0x2e, 0x2a, 0xd7, 0xe6, 0xe7,
0x26, 0x26, 0xdd, 0x8c, 0x3b, 0xe9, 0x6a, 0xa9, 0x30, 0x75, 0x69, 0x36, 0x1f, 0x30, 0x34, 0x5b,
0x7b, 0x11, 0x24, 0xfb, 0x1d, 0x09, 0x2c, 0x0a, 0xdd, 0xb3, 0x82, 0x0b, 0x53, 0xa3, 0x8a, 0x78,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_D9_DLL_DL_HASH: [u8; 48] = [
0xeb, 0x58, 0x44, 0x85, 0x9a, 0x39, 0xd6, 0x85, 0x3c, 0x1f, 0x14, 0x9c, 0xe0, 0x51, 0x16, 0x79,
0x1d, 0x2a, 0x45, 0x7a, 0x7f, 0x98, 0x41, 0xed, 0x07, 0xec, 0xdc, 0x1a, 0xc7, 0xc5, 0xad, 0xcb,
0x34, 0xd6, 0x30, 0x50, 0xbe, 0xe5, 0xad, 0xa5, 0x8e, 0xbd, 0x25, 0xb5, 0x02, 0xe7, 0x28, 0x24,
];
pub fn install() -> Result<()> {
info!("Backing up Nvidia Cg…");
backup_cg().chain_err(|| "Failed to backup Cg")?;
let cg_dir = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if!cg_dir.exists() {
info!("Downloading Nvidia Cg…");
let result = download_cg(&cg_dir);
if result.is_err() {
fs::remove_dir_all(&cg_dir)?;
}
result?;
} else {
info!("Nvidia Cg is already cached!")
}
info!("Updating Nvidia Cg…\n");
update_cg(&cg_dir).chain_err(|| "Failed to update Cg")?;
Ok(())
}
pub fn remove() -> Result<()> {
let cg_backup_path = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if!cg_backup_path.exists() {
return Err("No Cg backup found!".into());
}
info!("Restoring Nvidia Cg…");
update_cg(&cg_backup_path)?;
fs::remove_dir_all(&cg_backup_path)?;
info!("Removing Nvidia Cg backup…");
let cg_cache_path = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if cg_cache_path.exists() {
info!("Removing Nvidia Cg download cache…");
fs::remove_dir_all(cg_cache_path)?;
}
Ok(())
}
fn download_cg(cg_dir: &Path) -> Result<()> {
fs::create_dir(&cg_dir)?;
download(
&cg_dir.join("Cg.dll"),
CG_MN_DLL_DL,
Some(&CG_MN_DLL_DL_HASH),
)?;
download(
&cg_dir.join("CgGL.dll"),
CG_GL_DLL_DL,
Some(&CG_GL_DLL_DL_HASH),
)?;
download(
&cg_dir.join("cgD3D9.dll"),
CG_D9_DLL_DL,
Some(&CG_D9_DLL_DL_HASH),
)?;
Ok(())
}
#[test]
fn download_cg_works() {
use tempdir::TempDir;
let target = TempDir::new("lolupdater-cg-target").unwrap();
download_cg(&target.path().join("cg")).unwrap();
}
fn backup_cg() -> Result<()> {
let cg_backup = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if cg_backup.exists() {
info!("Skipping NVIDIA Cg backup! (Already exists)");
} else {
fs::create_dir(&cg_backup)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
&cg_backup.join("Cg.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
&cg_backup.join("CgGL.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
&cg_backup.join("CgD3D9.dll"),
)?;
}
Ok(())
}
fn update_cg(cg_dir: &Path) -> Result<()> {
update_file(
&cg_dir.join("Cg.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
update_file(
&cg_dir.join("Cg.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"), | &LOLSLN_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
Ok(())
} | random_line_split |
|
win.rs | use std::fs;
use std::path::Path;
use app_dirs::{self, AppDataType};
use util::*;
const CG_MN_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cg.dll";
const CG_GL_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgGL.dll";
const CG_D9_DLL_DL: &str = "https://mobasuite.com/downloads/macos/cgD3D9.dll";
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_MN_DLL_DL_HASH: [u8; 48] = [
0x2d, 0x27, 0x17, 0x03, 0x95, 0x97, 0xde, 0x0b, 0xf4, 0x88, 0x14, 0xad, 0xee, 0x90, 0xa2, 0xb8,
0xac, 0xfd, 0x9d, 0xab, 0x29, 0xf3, 0x7a, 0x64, 0xbf, 0x94, 0x8f, 0xb5, 0x5f, 0xcf, 0x9c, 0xa7,
0x8f, 0xb0, 0x5f, 0x92, 0x22, 0x27, 0x31, 0x65, 0xe2, 0x3c, 0x5c, 0xa2, 0xab, 0x87, 0x4d, 0x21,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_GL_DLL_DL_HASH: [u8; 48] = [
0xbc, 0x81, 0x45, 0xc4, 0x7d, 0x3c, 0xa6, 0x96, 0x5c, 0xe5, 0x19, 0x2e, 0x2a, 0xd7, 0xe6, 0xe7,
0x26, 0x26, 0xdd, 0x8c, 0x3b, 0xe9, 0x6a, 0xa9, 0x30, 0x75, 0x69, 0x36, 0x1f, 0x30, 0x34, 0x5b,
0x7b, 0x11, 0x24, 0xfb, 0x1d, 0x09, 0x2c, 0x0a, 0xdd, 0xb3, 0x82, 0x0b, 0x53, 0xa3, 0x8a, 0x78,
];
#[cfg_attr(rustfmt, rustfmt_skip)]
const CG_D9_DLL_DL_HASH: [u8; 48] = [
0xeb, 0x58, 0x44, 0x85, 0x9a, 0x39, 0xd6, 0x85, 0x3c, 0x1f, 0x14, 0x9c, 0xe0, 0x51, 0x16, 0x79,
0x1d, 0x2a, 0x45, 0x7a, 0x7f, 0x98, 0x41, 0xed, 0x07, 0xec, 0xdc, 0x1a, 0xc7, 0xc5, 0xad, 0xcb,
0x34, 0xd6, 0x30, 0x50, 0xbe, 0xe5, 0xad, 0xa5, 0x8e, 0xbd, 0x25, 0xb5, 0x02, 0xe7, 0x28, 0x24,
];
pub fn install() -> Result<()> {
info!("Backing up Nvidia Cg…");
backup_cg().chain_err(|| "Failed to backup Cg")?;
let cg_dir = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if!cg_dir.exists() {
info!("Downloading Nvidia Cg…");
let result = download_cg(&cg_dir);
if result.is_err() {
fs::remove_dir_all(&cg_dir)?;
}
result?;
} else {
info!("Nvidia Cg is already cached!")
}
info!("Updating Nvidia Cg…\n");
update_cg(&cg_dir).chain_err(|| "Failed to update Cg")?;
Ok(())
}
pub fn remove() -> Result<()> {
let cg_backup_path = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if!cg_backup_path.exists() {
return Err("No Cg backup found!".into());
}
info!("Restoring Nvidia Cg…");
update_cg(&cg_backup_path)?;
fs::remove_dir_all(&cg_backup_path)?;
info!("Removing Nvidia Cg backup…");
let cg_cache_path = app_dirs::get_app_dir(AppDataType::UserCache, &APP_INFO, "Cg")?;
if cg_cache_path.exists() {
info!("Removing Nvidia Cg download cache…");
fs::remove_dir_all(cg_cache_path)?;
}
Ok(())
}
fn download_cg(cg_dir: &Path) -> Result<()> {
fs::create_dir(&cg_dir)?;
download(
&cg_dir.join("Cg.dll"),
CG_MN_DLL_DL,
Some(&CG_MN_DLL_DL_HASH),
)?;
download(
&cg_dir.join("CgGL.dll"),
CG_GL_DLL_DL,
Some(&CG_GL_DLL_DL_HASH),
)?;
download(
&cg_dir.join("cgD3D9.dll"),
CG_D9_DLL_DL,
Some(&CG_D9_DLL_DL_HASH),
)?;
Ok(())
}
#[test]
fn download_cg_works() {
use tempdir::TempDir;
let target = TempDir::new("lolupdater-cg-target").unwrap();
download_cg(&target.path().join("cg")).unwrap();
}
fn backup_cg() -> Result<()> {
let cg |
fn update_
cg(cg_dir: &Path) -> Result<()> {
update_file(
&cg_dir.join("Cg.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
update_file(
&cg_dir.join("Cg.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
)?;
update_file(
&cg_dir.join("CgGL.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
)?;
update_file(
&cg_dir.join("cgD3D9.dll"),
&LOLSLN_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
)?;
Ok(())
}
| _backup = app_dirs::get_app_dir(AppDataType::UserData, &APP_INFO, "Backups/Cg")?;
if cg_backup.exists() {
info!("Skipping NVIDIA Cg backup! (Already exists)");
} else {
fs::create_dir(&cg_backup)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("Cg.dll"),
&cg_backup.join("Cg.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("CgGL.dll"),
&cg_backup.join("CgGL.dll"),
)?;
update_file(
&LOLP_GC_PATH.with(|k| k.clone()).join("cgD3D9.dll"),
&cg_backup.join("CgD3D9.dll"),
)?;
}
Ok(())
} | identifier_body |
guess-the-number.rs | use std::string::String;
use std::fs::File;
use std::io::{Read, BufRead};
static mut TRIES_LEFT: i32 = 5;
static mut RAND_INT: i32 = -1;
static mut GUESS: i32 = -1;
fn main() {
unsafe {
// Open /dev/random
let mut devrandom = File::open("/dev/random").unwrap();
// Create a 1 byte large buffer
let mut randombyte: [u8; 1] = [0];
// Read exactly 1 byte from /dev/random1 byte wide buffer
devrandom.read_exact(&mut randombyte).unwrap();
// Clamp it to 0-100 with modulo
RAND_INT = (randombyte[0] as i32) % 100;
// Get a handle to STDIN
let stdin = std::io::stdin();
let mut handle = stdin.lock();
// Create string to hold STDIN input
let mut input = String::new();
loop {
if TRIES_LEFT == 0 {
println!("Sorry, dude, but you lost. Better luck next time.");
println!("The number you wanted was {}", RAND_INT);
break;
}
println!("Make a guess: ");
input.truncate(0); // clear any previous input
handle.read_line(&mut input).unwrap();
GUESS = match input.trim().parse() {
Ok(integer) => integer,
Err(_) => {
println!("That's no integer, buddy.");
continue;
}
};
if GUESS < 0 || GUESS > 100 {
println!("I can't believe you've done this! That's not in 0-100");
continue;
}
// If we have a valid guess now, it counts as a try | TRIES_LEFT -= 1;
if GUESS == RAND_INT {
println!("🎉 YOU WIN 🎉");
break;
} else if GUESS > RAND_INT {
println!("Too high, guy.");
} else {
println!("Too low, bro.");
}
}
}
} | random_line_split |
|
guess-the-number.rs | use std::string::String;
use std::fs::File;
use std::io::{Read, BufRead};
static mut TRIES_LEFT: i32 = 5;
static mut RAND_INT: i32 = -1;
static mut GUESS: i32 = -1;
fn main() | println!("The number you wanted was {}", RAND_INT);
break;
}
println!("Make a guess: ");
input.truncate(0); // clear any previous input
handle.read_line(&mut input).unwrap();
GUESS = match input.trim().parse() {
Ok(integer) => integer,
Err(_) => {
println!("That's no integer, buddy.");
continue;
}
};
if GUESS < 0 || GUESS > 100 {
println!("I can't believe you've done this! That's not in 0-100");
continue;
}
// If we have a valid guess now, it counts as a try
TRIES_LEFT -= 1;
if GUESS == RAND_INT {
println!("🎉 YOU WIN 🎉");
break;
} else if GUESS > RAND_INT {
println!("Too high, guy.");
} else {
println!("Too low, bro.");
}
}
}
}
| {
unsafe {
// Open /dev/random
let mut devrandom = File::open("/dev/random").unwrap();
// Create a 1 byte large buffer
let mut randombyte: [u8; 1] = [0];
// Read exactly 1 byte from /dev/random1 byte wide buffer
devrandom.read_exact(&mut randombyte).unwrap();
// Clamp it to 0-100 with modulo
RAND_INT = (randombyte[0] as i32) % 100;
// Get a handle to STDIN
let stdin = std::io::stdin();
let mut handle = stdin.lock();
// Create string to hold STDIN input
let mut input = String::new();
loop {
if TRIES_LEFT == 0 {
println!("Sorry, dude, but you lost. Better luck next time."); | identifier_body |
guess-the-number.rs | use std::string::String;
use std::fs::File;
use std::io::{Read, BufRead};
static mut TRIES_LEFT: i32 = 5;
static mut RAND_INT: i32 = -1;
static mut GUESS: i32 = -1;
fn | () {
unsafe {
// Open /dev/random
let mut devrandom = File::open("/dev/random").unwrap();
// Create a 1 byte large buffer
let mut randombyte: [u8; 1] = [0];
// Read exactly 1 byte from /dev/random1 byte wide buffer
devrandom.read_exact(&mut randombyte).unwrap();
// Clamp it to 0-100 with modulo
RAND_INT = (randombyte[0] as i32) % 100;
// Get a handle to STDIN
let stdin = std::io::stdin();
let mut handle = stdin.lock();
// Create string to hold STDIN input
let mut input = String::new();
loop {
if TRIES_LEFT == 0 {
println!("Sorry, dude, but you lost. Better luck next time.");
println!("The number you wanted was {}", RAND_INT);
break;
}
println!("Make a guess: ");
input.truncate(0); // clear any previous input
handle.read_line(&mut input).unwrap();
GUESS = match input.trim().parse() {
Ok(integer) => integer,
Err(_) => {
println!("That's no integer, buddy.");
continue;
}
};
if GUESS < 0 || GUESS > 100 {
println!("I can't believe you've done this! That's not in 0-100");
continue;
}
// If we have a valid guess now, it counts as a try
TRIES_LEFT -= 1;
if GUESS == RAND_INT {
println!("🎉 YOU WIN 🎉");
break;
} else if GUESS > RAND_INT {
println!("Too high, guy.");
} else {
println!("Too low, bro.");
}
}
}
}
| main | identifier_name |
account.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/>.
//! Single account in the system.
use util::*;
use pod_account::*;
use rlp::*;
use lru_cache::LruCache;
use basic_account::BasicAccount;
use std::cell::{RefCell, Cell};
const STORAGE_CACHE_ITEMS: usize = 8192;
/// Single account in the system.
/// Keeps track of changes to the code and storage.
/// The changes are applied in `commit_storage` and `commit_code`
pub struct Account {
// Balance of the account.
balance: U256,
// Nonce of the account.
nonce: U256,
// Trie-backed storage.
storage_root: H256,
// LRU Cache of the trie-backed storage.
// This is limited to `STORAGE_CACHE_ITEMS` recent queries
storage_cache: RefCell<LruCache<H256, H256>>,
// Modified storage. Accumulates changes to storage made in `set_storage`
// Takes precedence over `storage_cache`.
storage_changes: HashMap<H256, H256>,
// Code hash of the account.
code_hash: H256,
// Size of the accoun code.
code_size: Option<usize>,
// Code cache of the account.
code_cache: Arc<Bytes>,
// Account code new or has been modified.
code_filth: Filth,
// Cached address hash.
address_hash: Cell<Option<H256>>,
}
impl From<BasicAccount> for Account {
fn from(basic: BasicAccount) -> Self {
Account {
balance: basic.balance,
nonce: basic.nonce,
storage_root: basic.storage_root,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: basic.code_hash,
code_size: None,
code_cache: Arc::new(vec![]),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
}
impl Account {
#[cfg(test)]
/// General constructor.
pub fn new(balance: U256, nonce: U256, storage: HashMap<H256, H256>, code: Bytes) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: storage,
code_hash: code.sha3(),
code_size: Some(code.len()),
code_cache: Arc::new(code),
code_filth: Filth::Dirty,
address_hash: Cell::new(None),
}
}
fn empty_storage_cache() -> RefCell<LruCache<H256, H256>> {
RefCell::new(LruCache::new(STORAGE_CACHE_ITEMS))
}
/// General constructor.
pub fn from_pod(pod: PodAccount) -> Account {
Account {
balance: pod.balance,
nonce: pod.nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: pod.storage.into_iter().collect(),
code_hash: pod.code.as_ref().map_or(SHA3_EMPTY, |c| c.sha3()),
code_filth: Filth::Dirty,
code_size: Some(pod.code.as_ref().map_or(0, |c| c.len())),
code_cache: Arc::new(pod.code.map_or_else(|| { warn!("POD account with unknown code is being created! Assuming no code."); vec![] }, |c| c)),
address_hash: Cell::new(None),
}
}
/// Create a new account with the given balance.
pub fn new_basic(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: Some(0),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Create a new account from RLP.
pub fn from_rlp(rlp: &[u8]) -> Account {
let basic: BasicAccount = ::rlp::decode(rlp);
basic.into()
}
/// Create a new contract account.
/// NOTE: make sure you use `init_code` on this before `commit`ing.
pub fn new_contract(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: None,
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Set this account's code to the given code.
/// NOTE: Account should have been created with `new_contract()`
pub fn init_code(&mut self, code: Bytes) {
self.code_hash = code.sha3();
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Dirty;
}
/// Reset this account's code to the given code.
pub fn reset_code(&mut self, code: Bytes) {
self.init_code(code);
}
/// Set (and cache) the contents of the trie's storage at `key` to `value`.
pub fn set_storage(&mut self, key: H256, value: H256) {
self.storage_changes.insert(key, value);
}
/// Get (and cache) the contents of the trie's storage at `key`.
/// Takes modifed storage into account.
pub fn storage_at(&self, db: &HashDB, key: &H256) -> H256 {
if let Some(value) = self.cached_storage_at(key) {
return value;
}
let db = SecTrieDB::new(db, &self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
let item: U256 = match db.get_with(key, ::rlp::decode) {
Ok(x) => x.unwrap_or_else(U256::zero),
Err(e) => panic!("Encountered potential DB corruption: {}", e),
};
let value: H256 = item.into();
self.storage_cache.borrow_mut().insert(key.clone(), value.clone());
value
}
/// Get cached storage value if any. Returns `None` if the
/// key is not in the cache.
pub fn cached_storage_at(&self, key: &H256) -> Option<H256> {
if let Some(value) = self.storage_changes.get(key) {
return Some(value.clone())
}
if let Some(value) = self.storage_cache.borrow_mut().get_mut(key) {
return Some(value.clone())
}
None
}
/// return the balance associated with this account.
pub fn balance(&self) -> &U256 { &self.balance }
/// return the nonce associated with this account.
pub fn nonce(&self) -> &U256 { &self.nonce }
/// return the code hash associated with this account.
pub fn code_hash(&self) -> H256 {
self.code_hash.clone()
}
/// return the code hash associated with this account.
pub fn address_hash(&self, address: &Address) -> H256 {
let hash = self.address_hash.get();
hash.unwrap_or_else(|| {
let hash = address.sha3();
self.address_hash.set(Some(hash.clone()));
hash
})
}
/// returns the account's code. If `None` then the code cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code(&self) -> Option<Arc<Bytes>> {
if self.code_hash!= SHA3_EMPTY && self.code_cache.is_empty() {
return None;
}
Some(self.code_cache.clone())
}
/// returns the account's code size. If `None` then the code cache or code size cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code_size(&self) -> Option<usize> {
self.code_size.clone()
}
#[cfg(test)]
/// Provide a byte array which hashes to the `code_hash`. returns the hash as a result.
pub fn note_code(&mut self, code: Bytes) -> Result<(), H256> {
let h = code.sha3();
if self.code_hash == h {
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
Ok(())
} else {
Err(h)
}
}
/// Is `code_cache` valid; such that code is going to return Some?
pub fn is_cached(&self) -> bool {
!self.code_cache.is_empty() || (self.code_cache.is_empty() && self.code_hash == SHA3_EMPTY)
}
/// Provide a database to get `code_hash`. Should not be called if it is a contract without code.
pub fn cache_code(&mut self, db: &HashDB) -> Option<Arc<Bytes>> {
// TODO: fill out self.code_cache;
trace!("Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
if self.is_cached() { return Some(self.code_cache.clone()) }
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
self.code_cache = Arc::new(x.to_vec());
Some(self.code_cache.clone())
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
None
},
}
}
/// Provide code to cache. For correctness, should be the correct code for the
/// account.
pub fn cache_given_code(&mut self, code: Arc<Bytes>) {
trace!("Account::cache_given_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size = Some(code.len());
self.code_cache = code;
}
/// Provide a database to get `code_size`. Should not be called if it is a contract without code.
pub fn cache_code_size(&mut self, db: &HashDB) -> bool {
// TODO: fill out self.code_cache;
trace!("Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size.is_some() ||
if self.code_hash!= SHA3_EMPTY {
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
true
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
false
},
}
} else {
false
}
}
/// Determine whether there are any un-`commit()`-ed storage-setting operations.
pub fn storage_is_clean(&self) -> bool { self.storage_changes.is_empty() }
/// Check if account has zero nonce, balance, no code and no storage.
///
/// NOTE: Will panic if `!self.storage_is_clean()`
pub fn is_empty(&self) -> bool {
assert!(self.storage_is_clean(), "Account::is_empty() may only legally be called when storage is clean.");
self.is_null() && self.storage_root == SHA3_NULL_RLP
}
/// Check if account has zero nonce, balance, no code.
pub fn is_null(&self) -> bool {
self.balance.is_zero() &&
self.nonce.is_zero() &&
self.code_hash == SHA3_EMPTY
}
/// Return the storage root associated with this account or None if it has been altered via the overlay.
pub fn storage_root(&self) -> Option<&H256> { if self.storage_is_clean() {Some(&self.storage_root)} else {None} }
/// Return the storage overlay.
pub fn storage_changes(&self) -> &HashMap<H256, H256> { &self.storage_changes }
/// Increment the nonce of the account by one.
pub fn inc_nonce(&mut self) {
self.nonce = self.nonce + U256::from(1u8);
}
/// Increase account balance.
pub fn add_balance(&mut self, x: &U256) {
self.balance = self.balance + *x;
}
/// Decrease account balance.
/// Panics if balance is less than `x`
pub fn sub_balance(&mut self, x: &U256) {
assert!(self.balance >= *x);
self.balance = self.balance - *x;
}
/// Commit the `storage_changes` to the backing DB and update `storage_root`.
pub fn commit_storage(&mut self, trie_factory: &TrieFactory, db: &mut HashDB) {
let mut t = trie_factory.from_existing(db, &mut self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
for (k, v) in self.storage_changes.drain() {
// cast key and value to trait type,
// so we can call overloaded `to_bytes` method
let res = match v.is_zero() {
true => t.remove(&k),
false => t.insert(&k, &encode(&U256::from(&*v))),
};
if let Err(e) = res {
warn!("Encountered potential DB corruption: {}", e);
}
self.storage_cache.borrow_mut().insert(k, v);
}
}
/// Commit any unsaved code. `code_hash` will always return the hash of the `code_cache` after this.
pub fn commit_code(&mut self, db: &mut HashDB) {
trace!("Commiting code of {:?} - {:?}, {:?}", self, self.code_filth == Filth::Dirty, self.code_cache.is_empty());
match (self.code_filth == Filth::Dirty, self.code_cache.is_empty()) {
(true, true) => {
self.code_size = Some(0);
self.code_filth = Filth::Clean;
},
(true, false) => {
db.emplace(self.code_hash.clone(), DBValue::from_slice(&*self.code_cache));
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Clean;
},
(false, _) => {},
}
}
/// Export to RLP.
pub fn rlp(&self) -> Bytes {
let mut stream = RlpStream::new_list(4);
stream.append(&self.nonce);
stream.append(&self.balance);
stream.append(&self.storage_root);
stream.append(&self.code_hash);
stream.out()
}
/// Clone basic account data
pub fn | (&self) -> Account {
Account {
balance: self.balance.clone(),
nonce: self.nonce.clone(),
storage_root: self.storage_root.clone(),
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: self.code_hash.clone(),
code_size: self.code_size.clone(),
code_cache: self.code_cache.clone(),
code_filth: self.code_filth,
address_hash: self.address_hash.clone(),
}
}
/// Clone account data and dirty storage keys
pub fn clone_dirty(&self) -> Account {
let mut account = self.clone_basic();
account.storage_changes = self.storage_changes.clone();
account.code_cache = self.code_cache.clone();
account
}
/// Clone account data, dirty storage keys and cached storage keys.
pub fn clone_all(&self) -> Account {
let mut account = self.clone_dirty();
account.storage_cache = self.storage_cache.clone();
account
}
/// Replace self with the data from other account merging storage cache.
/// Basic account data and all modifications are overwritten
/// with new values.
pub fn overwrite_with(&mut self, other: Account) {
self.balance = other.balance;
self.nonce = other.nonce;
self.storage_root = other.storage_root;
self.code_hash = other.code_hash;
self.code_filth = other.code_filth;
self.code_cache = other.code_cache;
self.code_size = other.code_size;
self.address_hash = other.address_hash;
let mut cache = self.storage_cache.borrow_mut();
for (k, v) in other.storage_cache.into_inner() {
cache.insert(k.clone(), v.clone()); //TODO: cloning should not be required here
}
self.storage_changes = other.storage_changes;
}
}
// light client storage proof.
impl Account {
/// Prove a storage key's existence or nonexistence in the account's storage
/// trie.
/// `storage_key` is the hash of the desired storage key, meaning
/// this will only work correctly under a secure trie.
/// Returns a merkle proof of the storage trie node with all nodes before `from_level`
/// omitted.
pub fn prove_storage(&self, db: &HashDB, storage_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> {
use util::trie::{Trie, TrieDB};
use util::trie::recorder::Recorder;
let mut recorder = Recorder::with_depth(from_level);
let trie = TrieDB::new(db, &self.storage_root)?;
let _ = trie.get_with(&storage_key, &mut recorder)?;
Ok(recorder.drain().into_iter().map(|r| r.data).collect())
}
}
impl fmt::Debug for Account {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", PodAccount::from_account(self))
}
}
#[cfg(test)]
mod tests {
use rlp::{UntrustedRlp, RlpType, View, Compressible};
use util::*;
use super::*;
use account_db::*;
#[test]
fn account_compress() {
let raw = Account::new_basic(2.into(), 4.into()).rlp();
let rlp = UntrustedRlp::new(&raw);
let compact_vec = rlp.compress(RlpType::Snapshot).to_vec();
assert!(raw.len() > compact_vec.len());
let again_raw = UntrustedRlp::new(&compact_vec).decompress(RlpType::Snapshot);
assert_eq!(raw, again_raw.to_vec());
}
#[test]
fn storage_at() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64)));
a.commit_storage(&Default::default(), &mut db);
a.init_code(vec![]);
a.commit_code(&mut db);
a.rlp()
};
let a = Account::from_rlp(&rlp);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x01u64))), H256::new());
}
#[test]
fn note_code() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.init_code(vec![0x55, 0x44, 0xffu8]);
a.commit_code(&mut db);
a.rlp()
};
let mut a = Account::from_rlp(&rlp);
assert!(a.cache_code(&db.immutable()).is_some());
let mut a = Account::from_rlp(&rlp);
assert_eq!(a.note_code(vec![0x55, 0x44, 0xffu8]), Ok(()));
}
#[test]
fn commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
assert_eq!(a.storage_root(), None);
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_remove_commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0.into());
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
assert_eq!(a.code_size(), Some(3));
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
}
#[test]
fn reset_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_filth, Filth::Clean);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
a.reset_code(vec![0x55]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "37bf2238b11b68cdc8382cece82651b59d3c3988873b6e0f33d79694aa45f1be");
}
#[test]
fn rlpio() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
let b = Account::from_rlp(&a.rlp());
assert_eq!(a.balance(), b.balance());
assert_eq!(a.nonce(), b.nonce());
assert_eq!(a.code_hash(), b.code_hash());
assert_eq!(a.storage_root(), b.storage_root());
}
#[test]
fn new_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
assert_eq!(a.balance(), &U256::from(69u8));
assert_eq!(a.nonce(), &U256::from(0u8));
assert_eq!(a.code_hash(), SHA3_EMPTY);
assert_eq!(a.storage_root().unwrap(), &SHA3_NULL_RLP);
}
#[test]
fn create_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
}
}
| clone_basic | identifier_name |
account.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/>.
//! Single account in the system.
use util::*;
use pod_account::*;
use rlp::*;
use lru_cache::LruCache;
use basic_account::BasicAccount;
use std::cell::{RefCell, Cell};
const STORAGE_CACHE_ITEMS: usize = 8192;
/// Single account in the system.
/// Keeps track of changes to the code and storage.
/// The changes are applied in `commit_storage` and `commit_code`
pub struct Account {
// Balance of the account.
balance: U256,
// Nonce of the account.
nonce: U256,
// Trie-backed storage.
storage_root: H256,
// LRU Cache of the trie-backed storage.
// This is limited to `STORAGE_CACHE_ITEMS` recent queries
storage_cache: RefCell<LruCache<H256, H256>>,
// Modified storage. Accumulates changes to storage made in `set_storage`
// Takes precedence over `storage_cache`.
storage_changes: HashMap<H256, H256>,
// Code hash of the account.
code_hash: H256,
// Size of the accoun code.
code_size: Option<usize>,
// Code cache of the account.
code_cache: Arc<Bytes>,
// Account code new or has been modified.
code_filth: Filth,
// Cached address hash.
address_hash: Cell<Option<H256>>,
}
impl From<BasicAccount> for Account {
fn from(basic: BasicAccount) -> Self {
Account {
balance: basic.balance,
nonce: basic.nonce,
storage_root: basic.storage_root,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: basic.code_hash,
code_size: None,
code_cache: Arc::new(vec![]),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
}
impl Account {
#[cfg(test)]
/// General constructor.
pub fn new(balance: U256, nonce: U256, storage: HashMap<H256, H256>, code: Bytes) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: storage,
code_hash: code.sha3(),
code_size: Some(code.len()),
code_cache: Arc::new(code),
code_filth: Filth::Dirty,
address_hash: Cell::new(None),
}
}
fn empty_storage_cache() -> RefCell<LruCache<H256, H256>> {
RefCell::new(LruCache::new(STORAGE_CACHE_ITEMS))
}
/// General constructor.
pub fn from_pod(pod: PodAccount) -> Account {
Account {
balance: pod.balance,
nonce: pod.nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: pod.storage.into_iter().collect(),
code_hash: pod.code.as_ref().map_or(SHA3_EMPTY, |c| c.sha3()),
code_filth: Filth::Dirty,
code_size: Some(pod.code.as_ref().map_or(0, |c| c.len())),
code_cache: Arc::new(pod.code.map_or_else(|| { warn!("POD account with unknown code is being created! Assuming no code."); vec![] }, |c| c)),
address_hash: Cell::new(None),
}
}
/// Create a new account with the given balance.
pub fn new_basic(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: Some(0),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Create a new account from RLP.
pub fn from_rlp(rlp: &[u8]) -> Account {
let basic: BasicAccount = ::rlp::decode(rlp);
basic.into()
}
/// Create a new contract account.
/// NOTE: make sure you use `init_code` on this before `commit`ing.
pub fn new_contract(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: None,
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Set this account's code to the given code.
/// NOTE: Account should have been created with `new_contract()`
pub fn init_code(&mut self, code: Bytes) {
self.code_hash = code.sha3();
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Dirty;
}
/// Reset this account's code to the given code.
pub fn reset_code(&mut self, code: Bytes) {
self.init_code(code);
}
/// Set (and cache) the contents of the trie's storage at `key` to `value`.
pub fn set_storage(&mut self, key: H256, value: H256) {
self.storage_changes.insert(key, value);
}
/// Get (and cache) the contents of the trie's storage at `key`.
/// Takes modifed storage into account.
pub fn storage_at(&self, db: &HashDB, key: &H256) -> H256 {
if let Some(value) = self.cached_storage_at(key) {
return value;
}
let db = SecTrieDB::new(db, &self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
let item: U256 = match db.get_with(key, ::rlp::decode) {
Ok(x) => x.unwrap_or_else(U256::zero),
Err(e) => panic!("Encountered potential DB corruption: {}", e),
};
let value: H256 = item.into();
self.storage_cache.borrow_mut().insert(key.clone(), value.clone());
value
}
/// Get cached storage value if any. Returns `None` if the
/// key is not in the cache.
pub fn cached_storage_at(&self, key: &H256) -> Option<H256> {
if let Some(value) = self.storage_changes.get(key) {
return Some(value.clone())
}
if let Some(value) = self.storage_cache.borrow_mut().get_mut(key) {
return Some(value.clone())
}
None
}
/// return the balance associated with this account.
pub fn balance(&self) -> &U256 { &self.balance }
/// return the nonce associated with this account.
pub fn nonce(&self) -> &U256 { &self.nonce }
/// return the code hash associated with this account.
pub fn code_hash(&self) -> H256 {
self.code_hash.clone()
}
/// return the code hash associated with this account.
pub fn address_hash(&self, address: &Address) -> H256 {
let hash = self.address_hash.get();
hash.unwrap_or_else(|| {
let hash = address.sha3();
self.address_hash.set(Some(hash.clone()));
hash
})
}
/// returns the account's code. If `None` then the code cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code(&self) -> Option<Arc<Bytes>> {
if self.code_hash!= SHA3_EMPTY && self.code_cache.is_empty() {
return None;
}
Some(self.code_cache.clone())
}
/// returns the account's code size. If `None` then the code cache or code size cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code_size(&self) -> Option<usize> {
self.code_size.clone()
}
#[cfg(test)]
/// Provide a byte array which hashes to the `code_hash`. returns the hash as a result.
pub fn note_code(&mut self, code: Bytes) -> Result<(), H256> {
let h = code.sha3();
if self.code_hash == h {
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
Ok(())
} else {
Err(h)
}
}
/// Is `code_cache` valid; such that code is going to return Some?
pub fn is_cached(&self) -> bool {
!self.code_cache.is_empty() || (self.code_cache.is_empty() && self.code_hash == SHA3_EMPTY)
}
/// Provide a database to get `code_hash`. Should not be called if it is a contract without code.
pub fn cache_code(&mut self, db: &HashDB) -> Option<Arc<Bytes>> {
// TODO: fill out self.code_cache;
trace!("Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
if self.is_cached() { return Some(self.code_cache.clone()) }
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
self.code_cache = Arc::new(x.to_vec());
Some(self.code_cache.clone())
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
None
},
}
}
/// Provide code to cache. For correctness, should be the correct code for the
/// account.
pub fn cache_given_code(&mut self, code: Arc<Bytes>) {
trace!("Account::cache_given_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size = Some(code.len());
self.code_cache = code;
}
/// Provide a database to get `code_size`. Should not be called if it is a contract without code.
pub fn cache_code_size(&mut self, db: &HashDB) -> bool {
// TODO: fill out self.code_cache;
trace!("Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size.is_some() ||
if self.code_hash!= SHA3_EMPTY {
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
true
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
false
},
}
} else {
false
}
}
/// Determine whether there are any un-`commit()`-ed storage-setting operations.
pub fn storage_is_clean(&self) -> bool { self.storage_changes.is_empty() }
/// Check if account has zero nonce, balance, no code and no storage.
///
/// NOTE: Will panic if `!self.storage_is_clean()`
pub fn is_empty(&self) -> bool {
assert!(self.storage_is_clean(), "Account::is_empty() may only legally be called when storage is clean.");
self.is_null() && self.storage_root == SHA3_NULL_RLP
}
/// Check if account has zero nonce, balance, no code.
pub fn is_null(&self) -> bool {
self.balance.is_zero() &&
self.nonce.is_zero() &&
self.code_hash == SHA3_EMPTY
}
/// Return the storage root associated with this account or None if it has been altered via the overlay.
pub fn storage_root(&self) -> Option<&H256> { if self.storage_is_clean() {Some(&self.storage_root)} else {None} }
/// Return the storage overlay.
pub fn storage_changes(&self) -> &HashMap<H256, H256> { &self.storage_changes }
/// Increment the nonce of the account by one.
pub fn inc_nonce(&mut self) |
/// Increase account balance.
pub fn add_balance(&mut self, x: &U256) {
self.balance = self.balance + *x;
}
/// Decrease account balance.
/// Panics if balance is less than `x`
pub fn sub_balance(&mut self, x: &U256) {
assert!(self.balance >= *x);
self.balance = self.balance - *x;
}
/// Commit the `storage_changes` to the backing DB and update `storage_root`.
pub fn commit_storage(&mut self, trie_factory: &TrieFactory, db: &mut HashDB) {
let mut t = trie_factory.from_existing(db, &mut self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
for (k, v) in self.storage_changes.drain() {
// cast key and value to trait type,
// so we can call overloaded `to_bytes` method
let res = match v.is_zero() {
true => t.remove(&k),
false => t.insert(&k, &encode(&U256::from(&*v))),
};
if let Err(e) = res {
warn!("Encountered potential DB corruption: {}", e);
}
self.storage_cache.borrow_mut().insert(k, v);
}
}
/// Commit any unsaved code. `code_hash` will always return the hash of the `code_cache` after this.
pub fn commit_code(&mut self, db: &mut HashDB) {
trace!("Commiting code of {:?} - {:?}, {:?}", self, self.code_filth == Filth::Dirty, self.code_cache.is_empty());
match (self.code_filth == Filth::Dirty, self.code_cache.is_empty()) {
(true, true) => {
self.code_size = Some(0);
self.code_filth = Filth::Clean;
},
(true, false) => {
db.emplace(self.code_hash.clone(), DBValue::from_slice(&*self.code_cache));
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Clean;
},
(false, _) => {},
}
}
/// Export to RLP.
pub fn rlp(&self) -> Bytes {
let mut stream = RlpStream::new_list(4);
stream.append(&self.nonce);
stream.append(&self.balance);
stream.append(&self.storage_root);
stream.append(&self.code_hash);
stream.out()
}
/// Clone basic account data
pub fn clone_basic(&self) -> Account {
Account {
balance: self.balance.clone(),
nonce: self.nonce.clone(),
storage_root: self.storage_root.clone(),
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: self.code_hash.clone(),
code_size: self.code_size.clone(),
code_cache: self.code_cache.clone(),
code_filth: self.code_filth,
address_hash: self.address_hash.clone(),
}
}
/// Clone account data and dirty storage keys
pub fn clone_dirty(&self) -> Account {
let mut account = self.clone_basic();
account.storage_changes = self.storage_changes.clone();
account.code_cache = self.code_cache.clone();
account
}
/// Clone account data, dirty storage keys and cached storage keys.
pub fn clone_all(&self) -> Account {
let mut account = self.clone_dirty();
account.storage_cache = self.storage_cache.clone();
account
}
/// Replace self with the data from other account merging storage cache.
/// Basic account data and all modifications are overwritten
/// with new values.
pub fn overwrite_with(&mut self, other: Account) {
self.balance = other.balance;
self.nonce = other.nonce;
self.storage_root = other.storage_root;
self.code_hash = other.code_hash;
self.code_filth = other.code_filth;
self.code_cache = other.code_cache;
self.code_size = other.code_size;
self.address_hash = other.address_hash;
let mut cache = self.storage_cache.borrow_mut();
for (k, v) in other.storage_cache.into_inner() {
cache.insert(k.clone(), v.clone()); //TODO: cloning should not be required here
}
self.storage_changes = other.storage_changes;
}
}
// light client storage proof.
impl Account {
/// Prove a storage key's existence or nonexistence in the account's storage
/// trie.
/// `storage_key` is the hash of the desired storage key, meaning
/// this will only work correctly under a secure trie.
/// Returns a merkle proof of the storage trie node with all nodes before `from_level`
/// omitted.
pub fn prove_storage(&self, db: &HashDB, storage_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> {
use util::trie::{Trie, TrieDB};
use util::trie::recorder::Recorder;
let mut recorder = Recorder::with_depth(from_level);
let trie = TrieDB::new(db, &self.storage_root)?;
let _ = trie.get_with(&storage_key, &mut recorder)?;
Ok(recorder.drain().into_iter().map(|r| r.data).collect())
}
}
impl fmt::Debug for Account {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", PodAccount::from_account(self))
}
}
#[cfg(test)]
mod tests {
use rlp::{UntrustedRlp, RlpType, View, Compressible};
use util::*;
use super::*;
use account_db::*;
#[test]
fn account_compress() {
let raw = Account::new_basic(2.into(), 4.into()).rlp();
let rlp = UntrustedRlp::new(&raw);
let compact_vec = rlp.compress(RlpType::Snapshot).to_vec();
assert!(raw.len() > compact_vec.len());
let again_raw = UntrustedRlp::new(&compact_vec).decompress(RlpType::Snapshot);
assert_eq!(raw, again_raw.to_vec());
}
#[test]
fn storage_at() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64)));
a.commit_storage(&Default::default(), &mut db);
a.init_code(vec![]);
a.commit_code(&mut db);
a.rlp()
};
let a = Account::from_rlp(&rlp);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x01u64))), H256::new());
}
#[test]
fn note_code() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.init_code(vec![0x55, 0x44, 0xffu8]);
a.commit_code(&mut db);
a.rlp()
};
let mut a = Account::from_rlp(&rlp);
assert!(a.cache_code(&db.immutable()).is_some());
let mut a = Account::from_rlp(&rlp);
assert_eq!(a.note_code(vec![0x55, 0x44, 0xffu8]), Ok(()));
}
#[test]
fn commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
assert_eq!(a.storage_root(), None);
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_remove_commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0.into());
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
assert_eq!(a.code_size(), Some(3));
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
}
#[test]
fn reset_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_filth, Filth::Clean);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
a.reset_code(vec![0x55]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "37bf2238b11b68cdc8382cece82651b59d3c3988873b6e0f33d79694aa45f1be");
}
#[test]
fn rlpio() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
let b = Account::from_rlp(&a.rlp());
assert_eq!(a.balance(), b.balance());
assert_eq!(a.nonce(), b.nonce());
assert_eq!(a.code_hash(), b.code_hash());
assert_eq!(a.storage_root(), b.storage_root());
}
#[test]
fn new_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
assert_eq!(a.balance(), &U256::from(69u8));
assert_eq!(a.nonce(), &U256::from(0u8));
assert_eq!(a.code_hash(), SHA3_EMPTY);
assert_eq!(a.storage_root().unwrap(), &SHA3_NULL_RLP);
}
#[test]
fn create_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
}
}
| {
self.nonce = self.nonce + U256::from(1u8);
} | identifier_body |
account.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/>.
//! Single account in the system.
use util::*;
use pod_account::*;
use rlp::*;
use lru_cache::LruCache;
use basic_account::BasicAccount;
use std::cell::{RefCell, Cell};
const STORAGE_CACHE_ITEMS: usize = 8192;
/// Single account in the system.
/// Keeps track of changes to the code and storage.
/// The changes are applied in `commit_storage` and `commit_code`
pub struct Account {
// Balance of the account.
balance: U256,
// Nonce of the account.
nonce: U256,
// Trie-backed storage.
storage_root: H256,
// LRU Cache of the trie-backed storage.
// This is limited to `STORAGE_CACHE_ITEMS` recent queries
storage_cache: RefCell<LruCache<H256, H256>>,
// Modified storage. Accumulates changes to storage made in `set_storage`
// Takes precedence over `storage_cache`.
storage_changes: HashMap<H256, H256>,
// Code hash of the account.
code_hash: H256,
// Size of the accoun code.
code_size: Option<usize>,
// Code cache of the account.
code_cache: Arc<Bytes>,
// Account code new or has been modified.
code_filth: Filth,
// Cached address hash.
address_hash: Cell<Option<H256>>,
}
impl From<BasicAccount> for Account {
fn from(basic: BasicAccount) -> Self {
Account {
balance: basic.balance,
nonce: basic.nonce,
storage_root: basic.storage_root,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: basic.code_hash,
code_size: None,
code_cache: Arc::new(vec![]),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
}
impl Account {
#[cfg(test)]
/// General constructor.
pub fn new(balance: U256, nonce: U256, storage: HashMap<H256, H256>, code: Bytes) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: storage,
code_hash: code.sha3(),
code_size: Some(code.len()),
code_cache: Arc::new(code),
code_filth: Filth::Dirty,
address_hash: Cell::new(None),
}
}
fn empty_storage_cache() -> RefCell<LruCache<H256, H256>> {
RefCell::new(LruCache::new(STORAGE_CACHE_ITEMS))
}
/// General constructor.
pub fn from_pod(pod: PodAccount) -> Account {
Account {
balance: pod.balance,
nonce: pod.nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: pod.storage.into_iter().collect(),
code_hash: pod.code.as_ref().map_or(SHA3_EMPTY, |c| c.sha3()),
code_filth: Filth::Dirty,
code_size: Some(pod.code.as_ref().map_or(0, |c| c.len())),
code_cache: Arc::new(pod.code.map_or_else(|| { warn!("POD account with unknown code is being created! Assuming no code."); vec![] }, |c| c)),
address_hash: Cell::new(None),
}
}
/// Create a new account with the given balance.
pub fn new_basic(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: Some(0),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Create a new account from RLP.
pub fn from_rlp(rlp: &[u8]) -> Account {
let basic: BasicAccount = ::rlp::decode(rlp);
basic.into()
}
/// Create a new contract account.
/// NOTE: make sure you use `init_code` on this before `commit`ing.
pub fn new_contract(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: None,
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Set this account's code to the given code.
/// NOTE: Account should have been created with `new_contract()`
pub fn init_code(&mut self, code: Bytes) {
self.code_hash = code.sha3();
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Dirty;
}
/// Reset this account's code to the given code.
pub fn reset_code(&mut self, code: Bytes) {
self.init_code(code);
}
/// Set (and cache) the contents of the trie's storage at `key` to `value`.
pub fn set_storage(&mut self, key: H256, value: H256) {
self.storage_changes.insert(key, value);
}
/// Get (and cache) the contents of the trie's storage at `key`.
/// Takes modifed storage into account.
pub fn storage_at(&self, db: &HashDB, key: &H256) -> H256 {
if let Some(value) = self.cached_storage_at(key) {
return value;
}
let db = SecTrieDB::new(db, &self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
let item: U256 = match db.get_with(key, ::rlp::decode) {
Ok(x) => x.unwrap_or_else(U256::zero),
Err(e) => panic!("Encountered potential DB corruption: {}", e),
};
let value: H256 = item.into();
self.storage_cache.borrow_mut().insert(key.clone(), value.clone());
value
}
/// Get cached storage value if any. Returns `None` if the
/// key is not in the cache.
pub fn cached_storage_at(&self, key: &H256) -> Option<H256> {
if let Some(value) = self.storage_changes.get(key) {
return Some(value.clone())
}
if let Some(value) = self.storage_cache.borrow_mut().get_mut(key) {
return Some(value.clone())
}
None
}
/// return the balance associated with this account.
pub fn balance(&self) -> &U256 { &self.balance }
/// return the nonce associated with this account.
pub fn nonce(&self) -> &U256 { &self.nonce }
/// return the code hash associated with this account.
pub fn code_hash(&self) -> H256 {
self.code_hash.clone()
}
/// return the code hash associated with this account.
pub fn address_hash(&self, address: &Address) -> H256 {
let hash = self.address_hash.get();
hash.unwrap_or_else(|| {
let hash = address.sha3();
self.address_hash.set(Some(hash.clone()));
hash
})
}
/// returns the account's code. If `None` then the code cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code(&self) -> Option<Arc<Bytes>> {
if self.code_hash!= SHA3_EMPTY && self.code_cache.is_empty() {
return None;
}
Some(self.code_cache.clone())
}
/// returns the account's code size. If `None` then the code cache or code size cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code_size(&self) -> Option<usize> {
self.code_size.clone()
}
#[cfg(test)]
/// Provide a byte array which hashes to the `code_hash`. returns the hash as a result.
pub fn note_code(&mut self, code: Bytes) -> Result<(), H256> {
let h = code.sha3();
if self.code_hash == h {
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
Ok(())
} else {
Err(h)
}
}
/// Is `code_cache` valid; such that code is going to return Some?
pub fn is_cached(&self) -> bool {
!self.code_cache.is_empty() || (self.code_cache.is_empty() && self.code_hash == SHA3_EMPTY)
}
/// Provide a database to get `code_hash`. Should not be called if it is a contract without code.
pub fn cache_code(&mut self, db: &HashDB) -> Option<Arc<Bytes>> {
// TODO: fill out self.code_cache;
trace!("Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
if self.is_cached() { return Some(self.code_cache.clone()) }
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
self.code_cache = Arc::new(x.to_vec());
Some(self.code_cache.clone())
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
None
},
}
}
/// Provide code to cache. For correctness, should be the correct code for the
/// account.
pub fn cache_given_code(&mut self, code: Arc<Bytes>) {
trace!("Account::cache_given_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size = Some(code.len());
self.code_cache = code;
}
/// Provide a database to get `code_size`. Should not be called if it is a contract without code.
pub fn cache_code_size(&mut self, db: &HashDB) -> bool {
// TODO: fill out self.code_cache;
trace!("Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size.is_some() ||
if self.code_hash!= SHA3_EMPTY {
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
true
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
false
},
}
} else {
false
}
}
/// Determine whether there are any un-`commit()`-ed storage-setting operations.
pub fn storage_is_clean(&self) -> bool { self.storage_changes.is_empty() }
/// Check if account has zero nonce, balance, no code and no storage.
///
/// NOTE: Will panic if `!self.storage_is_clean()`
pub fn is_empty(&self) -> bool {
assert!(self.storage_is_clean(), "Account::is_empty() may only legally be called when storage is clean.");
self.is_null() && self.storage_root == SHA3_NULL_RLP
}
/// Check if account has zero nonce, balance, no code.
pub fn is_null(&self) -> bool {
self.balance.is_zero() &&
self.nonce.is_zero() &&
self.code_hash == SHA3_EMPTY
}
/// Return the storage root associated with this account or None if it has been altered via the overlay.
pub fn storage_root(&self) -> Option<&H256> { if self.storage_is_clean() {Some(&self.storage_root)} else {None} }
/// Return the storage overlay.
pub fn storage_changes(&self) -> &HashMap<H256, H256> { &self.storage_changes }
/// Increment the nonce of the account by one.
pub fn inc_nonce(&mut self) {
self.nonce = self.nonce + U256::from(1u8);
}
/// Increase account balance.
pub fn add_balance(&mut self, x: &U256) {
self.balance = self.balance + *x;
}
/// Decrease account balance.
/// Panics if balance is less than `x`
pub fn sub_balance(&mut self, x: &U256) {
assert!(self.balance >= *x);
self.balance = self.balance - *x;
}
/// Commit the `storage_changes` to the backing DB and update `storage_root`.
pub fn commit_storage(&mut self, trie_factory: &TrieFactory, db: &mut HashDB) {
let mut t = trie_factory.from_existing(db, &mut self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
for (k, v) in self.storage_changes.drain() {
// cast key and value to trait type,
// so we can call overloaded `to_bytes` method
let res = match v.is_zero() {
true => t.remove(&k),
false => t.insert(&k, &encode(&U256::from(&*v))),
};
if let Err(e) = res {
warn!("Encountered potential DB corruption: {}", e);
}
self.storage_cache.borrow_mut().insert(k, v);
}
}
/// Commit any unsaved code. `code_hash` will always return the hash of the `code_cache` after this.
pub fn commit_code(&mut self, db: &mut HashDB) {
trace!("Commiting code of {:?} - {:?}, {:?}", self, self.code_filth == Filth::Dirty, self.code_cache.is_empty());
match (self.code_filth == Filth::Dirty, self.code_cache.is_empty()) {
(true, true) => {
self.code_size = Some(0);
self.code_filth = Filth::Clean;
},
(true, false) => {
db.emplace(self.code_hash.clone(), DBValue::from_slice(&*self.code_cache));
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Clean;
},
(false, _) => {},
}
}
/// Export to RLP.
pub fn rlp(&self) -> Bytes {
let mut stream = RlpStream::new_list(4);
stream.append(&self.nonce);
stream.append(&self.balance);
stream.append(&self.storage_root);
stream.append(&self.code_hash);
stream.out()
}
/// Clone basic account data
pub fn clone_basic(&self) -> Account {
Account {
balance: self.balance.clone(),
nonce: self.nonce.clone(),
storage_root: self.storage_root.clone(),
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: self.code_hash.clone(),
code_size: self.code_size.clone(),
code_cache: self.code_cache.clone(),
code_filth: self.code_filth,
address_hash: self.address_hash.clone(),
}
}
/// Clone account data and dirty storage keys
pub fn clone_dirty(&self) -> Account {
let mut account = self.clone_basic();
account.storage_changes = self.storage_changes.clone();
account.code_cache = self.code_cache.clone();
account
}
/// Clone account data, dirty storage keys and cached storage keys.
pub fn clone_all(&self) -> Account {
let mut account = self.clone_dirty();
account.storage_cache = self.storage_cache.clone();
account
}
/// Replace self with the data from other account merging storage cache.
/// Basic account data and all modifications are overwritten
/// with new values.
pub fn overwrite_with(&mut self, other: Account) {
self.balance = other.balance;
self.nonce = other.nonce;
self.storage_root = other.storage_root;
self.code_hash = other.code_hash;
self.code_filth = other.code_filth;
self.code_cache = other.code_cache;
self.code_size = other.code_size;
self.address_hash = other.address_hash;
let mut cache = self.storage_cache.borrow_mut();
for (k, v) in other.storage_cache.into_inner() {
cache.insert(k.clone(), v.clone()); //TODO: cloning should not be required here
}
self.storage_changes = other.storage_changes;
}
}
// light client storage proof.
impl Account {
/// Prove a storage key's existence or nonexistence in the account's storage
/// trie.
/// `storage_key` is the hash of the desired storage key, meaning
/// this will only work correctly under a secure trie.
/// Returns a merkle proof of the storage trie node with all nodes before `from_level`
/// omitted.
pub fn prove_storage(&self, db: &HashDB, storage_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> {
use util::trie::{Trie, TrieDB};
use util::trie::recorder::Recorder;
let mut recorder = Recorder::with_depth(from_level);
let trie = TrieDB::new(db, &self.storage_root)?;
let _ = trie.get_with(&storage_key, &mut recorder)?;
Ok(recorder.drain().into_iter().map(|r| r.data).collect())
}
}
impl fmt::Debug for Account {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", PodAccount::from_account(self))
}
}
#[cfg(test)]
mod tests {
use rlp::{UntrustedRlp, RlpType, View, Compressible};
use util::*;
use super::*;
use account_db::*;
#[test]
fn account_compress() {
let raw = Account::new_basic(2.into(), 4.into()).rlp();
let rlp = UntrustedRlp::new(&raw);
let compact_vec = rlp.compress(RlpType::Snapshot).to_vec();
assert!(raw.len() > compact_vec.len());
let again_raw = UntrustedRlp::new(&compact_vec).decompress(RlpType::Snapshot);
assert_eq!(raw, again_raw.to_vec());
}
#[test] | let mut a = Account::new_contract(69.into(), 0.into());
a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64)));
a.commit_storage(&Default::default(), &mut db);
a.init_code(vec![]);
a.commit_code(&mut db);
a.rlp()
};
let a = Account::from_rlp(&rlp);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x01u64))), H256::new());
}
#[test]
fn note_code() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.init_code(vec![0x55, 0x44, 0xffu8]);
a.commit_code(&mut db);
a.rlp()
};
let mut a = Account::from_rlp(&rlp);
assert!(a.cache_code(&db.immutable()).is_some());
let mut a = Account::from_rlp(&rlp);
assert_eq!(a.note_code(vec![0x55, 0x44, 0xffu8]), Ok(()));
}
#[test]
fn commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
assert_eq!(a.storage_root(), None);
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_remove_commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0.into());
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
assert_eq!(a.code_size(), Some(3));
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
}
#[test]
fn reset_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_filth, Filth::Clean);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
a.reset_code(vec![0x55]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "37bf2238b11b68cdc8382cece82651b59d3c3988873b6e0f33d79694aa45f1be");
}
#[test]
fn rlpio() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
let b = Account::from_rlp(&a.rlp());
assert_eq!(a.balance(), b.balance());
assert_eq!(a.nonce(), b.nonce());
assert_eq!(a.code_hash(), b.code_hash());
assert_eq!(a.storage_root(), b.storage_root());
}
#[test]
fn new_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
assert_eq!(a.balance(), &U256::from(69u8));
assert_eq!(a.nonce(), &U256::from(0u8));
assert_eq!(a.code_hash(), SHA3_EMPTY);
assert_eq!(a.storage_root().unwrap(), &SHA3_NULL_RLP);
}
#[test]
fn create_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
}
} | fn storage_at() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = { | random_line_split |
account.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/>.
//! Single account in the system.
use util::*;
use pod_account::*;
use rlp::*;
use lru_cache::LruCache;
use basic_account::BasicAccount;
use std::cell::{RefCell, Cell};
const STORAGE_CACHE_ITEMS: usize = 8192;
/// Single account in the system.
/// Keeps track of changes to the code and storage.
/// The changes are applied in `commit_storage` and `commit_code`
pub struct Account {
// Balance of the account.
balance: U256,
// Nonce of the account.
nonce: U256,
// Trie-backed storage.
storage_root: H256,
// LRU Cache of the trie-backed storage.
// This is limited to `STORAGE_CACHE_ITEMS` recent queries
storage_cache: RefCell<LruCache<H256, H256>>,
// Modified storage. Accumulates changes to storage made in `set_storage`
// Takes precedence over `storage_cache`.
storage_changes: HashMap<H256, H256>,
// Code hash of the account.
code_hash: H256,
// Size of the accoun code.
code_size: Option<usize>,
// Code cache of the account.
code_cache: Arc<Bytes>,
// Account code new or has been modified.
code_filth: Filth,
// Cached address hash.
address_hash: Cell<Option<H256>>,
}
impl From<BasicAccount> for Account {
fn from(basic: BasicAccount) -> Self {
Account {
balance: basic.balance,
nonce: basic.nonce,
storage_root: basic.storage_root,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: basic.code_hash,
code_size: None,
code_cache: Arc::new(vec![]),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
}
impl Account {
#[cfg(test)]
/// General constructor.
pub fn new(balance: U256, nonce: U256, storage: HashMap<H256, H256>, code: Bytes) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: storage,
code_hash: code.sha3(),
code_size: Some(code.len()),
code_cache: Arc::new(code),
code_filth: Filth::Dirty,
address_hash: Cell::new(None),
}
}
fn empty_storage_cache() -> RefCell<LruCache<H256, H256>> {
RefCell::new(LruCache::new(STORAGE_CACHE_ITEMS))
}
/// General constructor.
pub fn from_pod(pod: PodAccount) -> Account {
Account {
balance: pod.balance,
nonce: pod.nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: pod.storage.into_iter().collect(),
code_hash: pod.code.as_ref().map_or(SHA3_EMPTY, |c| c.sha3()),
code_filth: Filth::Dirty,
code_size: Some(pod.code.as_ref().map_or(0, |c| c.len())),
code_cache: Arc::new(pod.code.map_or_else(|| { warn!("POD account with unknown code is being created! Assuming no code."); vec![] }, |c| c)),
address_hash: Cell::new(None),
}
}
/// Create a new account with the given balance.
pub fn new_basic(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: Some(0),
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Create a new account from RLP.
pub fn from_rlp(rlp: &[u8]) -> Account {
let basic: BasicAccount = ::rlp::decode(rlp);
basic.into()
}
/// Create a new contract account.
/// NOTE: make sure you use `init_code` on this before `commit`ing.
pub fn new_contract(balance: U256, nonce: U256) -> Account {
Account {
balance: balance,
nonce: nonce,
storage_root: SHA3_NULL_RLP,
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: SHA3_EMPTY,
code_cache: Arc::new(vec![]),
code_size: None,
code_filth: Filth::Clean,
address_hash: Cell::new(None),
}
}
/// Set this account's code to the given code.
/// NOTE: Account should have been created with `new_contract()`
pub fn init_code(&mut self, code: Bytes) {
self.code_hash = code.sha3();
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Dirty;
}
/// Reset this account's code to the given code.
pub fn reset_code(&mut self, code: Bytes) {
self.init_code(code);
}
/// Set (and cache) the contents of the trie's storage at `key` to `value`.
pub fn set_storage(&mut self, key: H256, value: H256) {
self.storage_changes.insert(key, value);
}
/// Get (and cache) the contents of the trie's storage at `key`.
/// Takes modifed storage into account.
pub fn storage_at(&self, db: &HashDB, key: &H256) -> H256 {
if let Some(value) = self.cached_storage_at(key) {
return value;
}
let db = SecTrieDB::new(db, &self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
let item: U256 = match db.get_with(key, ::rlp::decode) {
Ok(x) => x.unwrap_or_else(U256::zero),
Err(e) => panic!("Encountered potential DB corruption: {}", e),
};
let value: H256 = item.into();
self.storage_cache.borrow_mut().insert(key.clone(), value.clone());
value
}
/// Get cached storage value if any. Returns `None` if the
/// key is not in the cache.
pub fn cached_storage_at(&self, key: &H256) -> Option<H256> {
if let Some(value) = self.storage_changes.get(key) {
return Some(value.clone())
}
if let Some(value) = self.storage_cache.borrow_mut().get_mut(key) {
return Some(value.clone())
}
None
}
/// return the balance associated with this account.
pub fn balance(&self) -> &U256 { &self.balance }
/// return the nonce associated with this account.
pub fn nonce(&self) -> &U256 { &self.nonce }
/// return the code hash associated with this account.
pub fn code_hash(&self) -> H256 {
self.code_hash.clone()
}
/// return the code hash associated with this account.
pub fn address_hash(&self, address: &Address) -> H256 {
let hash = self.address_hash.get();
hash.unwrap_or_else(|| {
let hash = address.sha3();
self.address_hash.set(Some(hash.clone()));
hash
})
}
/// returns the account's code. If `None` then the code cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code(&self) -> Option<Arc<Bytes>> {
if self.code_hash!= SHA3_EMPTY && self.code_cache.is_empty() {
return None;
}
Some(self.code_cache.clone())
}
/// returns the account's code size. If `None` then the code cache or code size cache isn't available -
/// get someone who knows to call `note_code`.
pub fn code_size(&self) -> Option<usize> {
self.code_size.clone()
}
#[cfg(test)]
/// Provide a byte array which hashes to the `code_hash`. returns the hash as a result.
pub fn note_code(&mut self, code: Bytes) -> Result<(), H256> {
let h = code.sha3();
if self.code_hash == h {
self.code_cache = Arc::new(code);
self.code_size = Some(self.code_cache.len());
Ok(())
} else {
Err(h)
}
}
/// Is `code_cache` valid; such that code is going to return Some?
pub fn is_cached(&self) -> bool {
!self.code_cache.is_empty() || (self.code_cache.is_empty() && self.code_hash == SHA3_EMPTY)
}
/// Provide a database to get `code_hash`. Should not be called if it is a contract without code.
pub fn cache_code(&mut self, db: &HashDB) -> Option<Arc<Bytes>> {
// TODO: fill out self.code_cache;
trace!("Account::cache_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
if self.is_cached() { return Some(self.code_cache.clone()) }
match db.get(&self.code_hash) {
Some(x) => | ,
_ => {
warn!("Failed reverse get of {}", self.code_hash);
None
},
}
}
/// Provide code to cache. For correctness, should be the correct code for the
/// account.
pub fn cache_given_code(&mut self, code: Arc<Bytes>) {
trace!("Account::cache_given_code: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size = Some(code.len());
self.code_cache = code;
}
/// Provide a database to get `code_size`. Should not be called if it is a contract without code.
pub fn cache_code_size(&mut self, db: &HashDB) -> bool {
// TODO: fill out self.code_cache;
trace!("Account::cache_code_size: ic={}; self.code_hash={:?}, self.code_cache={}", self.is_cached(), self.code_hash, self.code_cache.pretty());
self.code_size.is_some() ||
if self.code_hash!= SHA3_EMPTY {
match db.get(&self.code_hash) {
Some(x) => {
self.code_size = Some(x.len());
true
},
_ => {
warn!("Failed reverse get of {}", self.code_hash);
false
},
}
} else {
false
}
}
/// Determine whether there are any un-`commit()`-ed storage-setting operations.
pub fn storage_is_clean(&self) -> bool { self.storage_changes.is_empty() }
/// Check if account has zero nonce, balance, no code and no storage.
///
/// NOTE: Will panic if `!self.storage_is_clean()`
pub fn is_empty(&self) -> bool {
assert!(self.storage_is_clean(), "Account::is_empty() may only legally be called when storage is clean.");
self.is_null() && self.storage_root == SHA3_NULL_RLP
}
/// Check if account has zero nonce, balance, no code.
pub fn is_null(&self) -> bool {
self.balance.is_zero() &&
self.nonce.is_zero() &&
self.code_hash == SHA3_EMPTY
}
/// Return the storage root associated with this account or None if it has been altered via the overlay.
pub fn storage_root(&self) -> Option<&H256> { if self.storage_is_clean() {Some(&self.storage_root)} else {None} }
/// Return the storage overlay.
pub fn storage_changes(&self) -> &HashMap<H256, H256> { &self.storage_changes }
/// Increment the nonce of the account by one.
pub fn inc_nonce(&mut self) {
self.nonce = self.nonce + U256::from(1u8);
}
/// Increase account balance.
pub fn add_balance(&mut self, x: &U256) {
self.balance = self.balance + *x;
}
/// Decrease account balance.
/// Panics if balance is less than `x`
pub fn sub_balance(&mut self, x: &U256) {
assert!(self.balance >= *x);
self.balance = self.balance - *x;
}
/// Commit the `storage_changes` to the backing DB and update `storage_root`.
pub fn commit_storage(&mut self, trie_factory: &TrieFactory, db: &mut HashDB) {
let mut t = trie_factory.from_existing(db, &mut self.storage_root)
.expect("Account storage_root initially set to zero (valid) and only altered by SecTrieDBMut. \
SecTrieDBMut would not set it to an invalid state root. Therefore the root is valid and DB creation \
using it will not fail.");
for (k, v) in self.storage_changes.drain() {
// cast key and value to trait type,
// so we can call overloaded `to_bytes` method
let res = match v.is_zero() {
true => t.remove(&k),
false => t.insert(&k, &encode(&U256::from(&*v))),
};
if let Err(e) = res {
warn!("Encountered potential DB corruption: {}", e);
}
self.storage_cache.borrow_mut().insert(k, v);
}
}
/// Commit any unsaved code. `code_hash` will always return the hash of the `code_cache` after this.
pub fn commit_code(&mut self, db: &mut HashDB) {
trace!("Commiting code of {:?} - {:?}, {:?}", self, self.code_filth == Filth::Dirty, self.code_cache.is_empty());
match (self.code_filth == Filth::Dirty, self.code_cache.is_empty()) {
(true, true) => {
self.code_size = Some(0);
self.code_filth = Filth::Clean;
},
(true, false) => {
db.emplace(self.code_hash.clone(), DBValue::from_slice(&*self.code_cache));
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Clean;
},
(false, _) => {},
}
}
/// Export to RLP.
pub fn rlp(&self) -> Bytes {
let mut stream = RlpStream::new_list(4);
stream.append(&self.nonce);
stream.append(&self.balance);
stream.append(&self.storage_root);
stream.append(&self.code_hash);
stream.out()
}
/// Clone basic account data
pub fn clone_basic(&self) -> Account {
Account {
balance: self.balance.clone(),
nonce: self.nonce.clone(),
storage_root: self.storage_root.clone(),
storage_cache: Self::empty_storage_cache(),
storage_changes: HashMap::new(),
code_hash: self.code_hash.clone(),
code_size: self.code_size.clone(),
code_cache: self.code_cache.clone(),
code_filth: self.code_filth,
address_hash: self.address_hash.clone(),
}
}
/// Clone account data and dirty storage keys
pub fn clone_dirty(&self) -> Account {
let mut account = self.clone_basic();
account.storage_changes = self.storage_changes.clone();
account.code_cache = self.code_cache.clone();
account
}
/// Clone account data, dirty storage keys and cached storage keys.
pub fn clone_all(&self) -> Account {
let mut account = self.clone_dirty();
account.storage_cache = self.storage_cache.clone();
account
}
/// Replace self with the data from other account merging storage cache.
/// Basic account data and all modifications are overwritten
/// with new values.
pub fn overwrite_with(&mut self, other: Account) {
self.balance = other.balance;
self.nonce = other.nonce;
self.storage_root = other.storage_root;
self.code_hash = other.code_hash;
self.code_filth = other.code_filth;
self.code_cache = other.code_cache;
self.code_size = other.code_size;
self.address_hash = other.address_hash;
let mut cache = self.storage_cache.borrow_mut();
for (k, v) in other.storage_cache.into_inner() {
cache.insert(k.clone(), v.clone()); //TODO: cloning should not be required here
}
self.storage_changes = other.storage_changes;
}
}
// light client storage proof.
impl Account {
/// Prove a storage key's existence or nonexistence in the account's storage
/// trie.
/// `storage_key` is the hash of the desired storage key, meaning
/// this will only work correctly under a secure trie.
/// Returns a merkle proof of the storage trie node with all nodes before `from_level`
/// omitted.
pub fn prove_storage(&self, db: &HashDB, storage_key: H256, from_level: u32) -> Result<Vec<Bytes>, Box<TrieError>> {
use util::trie::{Trie, TrieDB};
use util::trie::recorder::Recorder;
let mut recorder = Recorder::with_depth(from_level);
let trie = TrieDB::new(db, &self.storage_root)?;
let _ = trie.get_with(&storage_key, &mut recorder)?;
Ok(recorder.drain().into_iter().map(|r| r.data).collect())
}
}
impl fmt::Debug for Account {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", PodAccount::from_account(self))
}
}
#[cfg(test)]
mod tests {
use rlp::{UntrustedRlp, RlpType, View, Compressible};
use util::*;
use super::*;
use account_db::*;
#[test]
fn account_compress() {
let raw = Account::new_basic(2.into(), 4.into()).rlp();
let rlp = UntrustedRlp::new(&raw);
let compact_vec = rlp.compress(RlpType::Snapshot).to_vec();
assert!(raw.len() > compact_vec.len());
let again_raw = UntrustedRlp::new(&compact_vec).decompress(RlpType::Snapshot);
assert_eq!(raw, again_raw.to_vec());
}
#[test]
fn storage_at() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.set_storage(H256::from(&U256::from(0x00u64)), H256::from(&U256::from(0x1234u64)));
a.commit_storage(&Default::default(), &mut db);
a.init_code(vec![]);
a.commit_code(&mut db);
a.rlp()
};
let a = Account::from_rlp(&rlp);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x00u64))), H256::from(&U256::from(0x1234u64)));
assert_eq!(a.storage_at(&db.immutable(), &H256::from(&U256::from(0x01u64))), H256::new());
}
#[test]
fn note_code() {
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
let rlp = {
let mut a = Account::new_contract(69.into(), 0.into());
a.init_code(vec![0x55, 0x44, 0xffu8]);
a.commit_code(&mut db);
a.rlp()
};
let mut a = Account::from_rlp(&rlp);
assert!(a.cache_code(&db.immutable()).is_some());
let mut a = Account::from_rlp(&rlp);
assert_eq!(a.note_code(vec![0x55, 0x44, 0xffu8]), Ok(()));
}
#[test]
fn commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
assert_eq!(a.storage_root(), None);
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_remove_commit_storage() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.set_storage(0.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0x1234.into());
a.commit_storage(&Default::default(), &mut db);
a.set_storage(1.into(), 0.into());
a.commit_storage(&Default::default(), &mut db);
assert_eq!(a.storage_root().unwrap().hex(), "c57e1afb758b07f8d2c8f13a3b6e44fa5ff94ab266facc5a4fd3f062426e50b2");
}
#[test]
fn commit_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
assert_eq!(a.code_size(), Some(3));
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
}
#[test]
fn reset_code() {
let mut a = Account::new_contract(69.into(), 0.into());
let mut db = MemoryDB::new();
let mut db = AccountDBMut::new(&mut db, &Address::new());
a.init_code(vec![0x55, 0x44, 0xffu8]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_filth, Filth::Clean);
assert_eq!(a.code_hash().hex(), "af231e631776a517ca23125370d542873eca1fb4d613ed9b5d5335a46ae5b7eb");
a.reset_code(vec![0x55]);
assert_eq!(a.code_filth, Filth::Dirty);
a.commit_code(&mut db);
assert_eq!(a.code_hash().hex(), "37bf2238b11b68cdc8382cece82651b59d3c3988873b6e0f33d79694aa45f1be");
}
#[test]
fn rlpio() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
let b = Account::from_rlp(&a.rlp());
assert_eq!(a.balance(), b.balance());
assert_eq!(a.nonce(), b.nonce());
assert_eq!(a.code_hash(), b.code_hash());
assert_eq!(a.storage_root(), b.storage_root());
}
#[test]
fn new_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
assert_eq!(a.balance(), &U256::from(69u8));
assert_eq!(a.nonce(), &U256::from(0u8));
assert_eq!(a.code_hash(), SHA3_EMPTY);
assert_eq!(a.storage_root().unwrap(), &SHA3_NULL_RLP);
}
#[test]
fn create_account() {
let a = Account::new(U256::from(69u8), U256::from(0u8), HashMap::new(), Bytes::new());
assert_eq!(a.rlp().to_hex(), "f8448045a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470");
}
}
| {
self.code_size = Some(x.len());
self.code_cache = Arc::new(x.to_vec());
Some(self.code_cache.clone())
} | conditional_block |
fsu-moves-and-copies.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue 4691: Ensure that functional-struct-updates operates
// correctly and moves rather than copy when appropriate.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::marker::NoCopy as NP;
struct ncint { np: NP, v: int }
fn ncint(v: int) -> ncint { ncint { np: NP, v: v } }
struct NoFoo { copied: int, nocopy: ncint, }
impl NoFoo {
fn new(x:int,y:int) -> NoFoo { NoFoo { copied: x, nocopy: ncint(y) } }
}
struct MoveFoo { copied: int, moved: Box<int>, }
impl MoveFoo {
fn new(x:int,y:int) -> MoveFoo { MoveFoo { copied: x, moved: box y } }
}
struct DropNoFoo { inner: NoFoo }
impl DropNoFoo {
fn new(x:int,y:int) -> DropNoFoo { DropNoFoo { inner: NoFoo::new(x,y) } }
}
impl Drop for DropNoFoo { fn drop(&mut self) { } }
struct DropMoveFoo { inner: MoveFoo }
impl DropMoveFoo {
fn new(x:int,y:int) -> DropMoveFoo { DropMoveFoo { inner: MoveFoo::new(x,y) } }
}
impl Drop for DropMoveFoo { fn drop(&mut self) { } }
fn test0() {
// just copy implicitly copyable fields from `f`, no moves
// (and thus it is okay that these are Drop; compare against
// compile-fail test: borrowck-struct-update-with-dtor.rs).
// Case 1: Nocopyable
let f = DropNoFoo::new(1, 2);
let b = DropNoFoo { inner: NoFoo { nocopy: ncint(3),..f.inner }};
let c = DropNoFoo { inner: NoFoo { nocopy: ncint(4),..f.inner }};
assert_eq!(f.inner.copied, 1);
assert_eq!(f.inner.nocopy.v, 2);
assert_eq!(b.inner.copied, 1);
assert_eq!(b.inner.nocopy.v, 3);
assert_eq!(c.inner.copied, 1);
assert_eq!(c.inner.nocopy.v, 4);
// Case 2: Owned
let f = DropMoveFoo::new(5, 6);
let b = DropMoveFoo { inner: MoveFoo { moved: box 7,..f.inner }};
let c = DropMoveFoo { inner: MoveFoo { moved: box 8,..f.inner }};
assert_eq!(f.inner.copied, 5);
assert_eq!(*f.inner.moved, 6);
assert_eq!(b.inner.copied, 5);
assert_eq!(*b.inner.moved, 7);
assert_eq!(c.inner.copied, 5);
assert_eq!(*c.inner.moved, 8);
}
fn test1() { | let b = MoveFoo {moved: box 13,..f};
let c = MoveFoo {copied: 14,..f};
assert_eq!(b.copied, 11);
assert_eq!(*b.moved, 13);
assert_eq!(c.copied, 14);
assert_eq!(*c.moved, 12);
}
fn test2() {
// move non-copyable field
let f = NoFoo::new(21, 22);
let b = NoFoo {nocopy: ncint(23),..f};
let c = NoFoo {copied: 24,..f};
assert_eq!(b.copied, 21);
assert_eq!(b.nocopy.v, 23);
assert_eq!(c.copied, 24);
assert_eq!(c.nocopy.v, 22);
}
pub fn main() {
test0();
test1();
test2();
} | // copying move-by-default fields from `f`, so it moves:
let f = MoveFoo::new(11, 12);
| random_line_split |
fsu-moves-and-copies.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue 4691: Ensure that functional-struct-updates operates
// correctly and moves rather than copy when appropriate.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::marker::NoCopy as NP;
struct ncint { np: NP, v: int }
fn ncint(v: int) -> ncint { ncint { np: NP, v: v } }
struct NoFoo { copied: int, nocopy: ncint, }
impl NoFoo {
fn new(x:int,y:int) -> NoFoo { NoFoo { copied: x, nocopy: ncint(y) } }
}
struct MoveFoo { copied: int, moved: Box<int>, }
impl MoveFoo {
fn new(x:int,y:int) -> MoveFoo { MoveFoo { copied: x, moved: box y } }
}
struct DropNoFoo { inner: NoFoo }
impl DropNoFoo {
fn new(x:int,y:int) -> DropNoFoo { DropNoFoo { inner: NoFoo::new(x,y) } }
}
impl Drop for DropNoFoo { fn drop(&mut self) { } }
struct DropMoveFoo { inner: MoveFoo }
impl DropMoveFoo {
fn new(x:int,y:int) -> DropMoveFoo |
}
impl Drop for DropMoveFoo { fn drop(&mut self) { } }
fn test0() {
// just copy implicitly copyable fields from `f`, no moves
// (and thus it is okay that these are Drop; compare against
// compile-fail test: borrowck-struct-update-with-dtor.rs).
// Case 1: Nocopyable
let f = DropNoFoo::new(1, 2);
let b = DropNoFoo { inner: NoFoo { nocopy: ncint(3),..f.inner }};
let c = DropNoFoo { inner: NoFoo { nocopy: ncint(4),..f.inner }};
assert_eq!(f.inner.copied, 1);
assert_eq!(f.inner.nocopy.v, 2);
assert_eq!(b.inner.copied, 1);
assert_eq!(b.inner.nocopy.v, 3);
assert_eq!(c.inner.copied, 1);
assert_eq!(c.inner.nocopy.v, 4);
// Case 2: Owned
let f = DropMoveFoo::new(5, 6);
let b = DropMoveFoo { inner: MoveFoo { moved: box 7,..f.inner }};
let c = DropMoveFoo { inner: MoveFoo { moved: box 8,..f.inner }};
assert_eq!(f.inner.copied, 5);
assert_eq!(*f.inner.moved, 6);
assert_eq!(b.inner.copied, 5);
assert_eq!(*b.inner.moved, 7);
assert_eq!(c.inner.copied, 5);
assert_eq!(*c.inner.moved, 8);
}
fn test1() {
// copying move-by-default fields from `f`, so it moves:
let f = MoveFoo::new(11, 12);
let b = MoveFoo {moved: box 13,..f};
let c = MoveFoo {copied: 14,..f};
assert_eq!(b.copied, 11);
assert_eq!(*b.moved, 13);
assert_eq!(c.copied, 14);
assert_eq!(*c.moved, 12);
}
fn test2() {
// move non-copyable field
let f = NoFoo::new(21, 22);
let b = NoFoo {nocopy: ncint(23),..f};
let c = NoFoo {copied: 24,..f};
assert_eq!(b.copied, 21);
assert_eq!(b.nocopy.v, 23);
assert_eq!(c.copied, 24);
assert_eq!(c.nocopy.v, 22);
}
pub fn main() {
test0();
test1();
test2();
}
| { DropMoveFoo { inner: MoveFoo::new(x,y) } } | identifier_body |
fsu-moves-and-copies.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue 4691: Ensure that functional-struct-updates operates
// correctly and moves rather than copy when appropriate.
#![allow(unknown_features)]
#![feature(box_syntax)]
use std::marker::NoCopy as NP;
struct ncint { np: NP, v: int }
fn ncint(v: int) -> ncint { ncint { np: NP, v: v } }
struct NoFoo { copied: int, nocopy: ncint, }
impl NoFoo {
fn new(x:int,y:int) -> NoFoo { NoFoo { copied: x, nocopy: ncint(y) } }
}
struct MoveFoo { copied: int, moved: Box<int>, }
impl MoveFoo {
fn | (x:int,y:int) -> MoveFoo { MoveFoo { copied: x, moved: box y } }
}
struct DropNoFoo { inner: NoFoo }
impl DropNoFoo {
fn new(x:int,y:int) -> DropNoFoo { DropNoFoo { inner: NoFoo::new(x,y) } }
}
impl Drop for DropNoFoo { fn drop(&mut self) { } }
struct DropMoveFoo { inner: MoveFoo }
impl DropMoveFoo {
fn new(x:int,y:int) -> DropMoveFoo { DropMoveFoo { inner: MoveFoo::new(x,y) } }
}
impl Drop for DropMoveFoo { fn drop(&mut self) { } }
fn test0() {
// just copy implicitly copyable fields from `f`, no moves
// (and thus it is okay that these are Drop; compare against
// compile-fail test: borrowck-struct-update-with-dtor.rs).
// Case 1: Nocopyable
let f = DropNoFoo::new(1, 2);
let b = DropNoFoo { inner: NoFoo { nocopy: ncint(3),..f.inner }};
let c = DropNoFoo { inner: NoFoo { nocopy: ncint(4),..f.inner }};
assert_eq!(f.inner.copied, 1);
assert_eq!(f.inner.nocopy.v, 2);
assert_eq!(b.inner.copied, 1);
assert_eq!(b.inner.nocopy.v, 3);
assert_eq!(c.inner.copied, 1);
assert_eq!(c.inner.nocopy.v, 4);
// Case 2: Owned
let f = DropMoveFoo::new(5, 6);
let b = DropMoveFoo { inner: MoveFoo { moved: box 7,..f.inner }};
let c = DropMoveFoo { inner: MoveFoo { moved: box 8,..f.inner }};
assert_eq!(f.inner.copied, 5);
assert_eq!(*f.inner.moved, 6);
assert_eq!(b.inner.copied, 5);
assert_eq!(*b.inner.moved, 7);
assert_eq!(c.inner.copied, 5);
assert_eq!(*c.inner.moved, 8);
}
fn test1() {
// copying move-by-default fields from `f`, so it moves:
let f = MoveFoo::new(11, 12);
let b = MoveFoo {moved: box 13,..f};
let c = MoveFoo {copied: 14,..f};
assert_eq!(b.copied, 11);
assert_eq!(*b.moved, 13);
assert_eq!(c.copied, 14);
assert_eq!(*c.moved, 12);
}
fn test2() {
// move non-copyable field
let f = NoFoo::new(21, 22);
let b = NoFoo {nocopy: ncint(23),..f};
let c = NoFoo {copied: 24,..f};
assert_eq!(b.copied, 21);
assert_eq!(b.nocopy.v, 23);
assert_eq!(c.copied, 24);
assert_eq!(c.nocopy.v, 22);
}
pub fn main() {
test0();
test1();
test2();
}
| new | identifier_name |
tiles.rs | use super::Tile;
use colors;
use pixset;
use pixset::PixLike;
use units;
pub struct Tiles<P: PixLike> {
size: units::Size2D,
pub tiles: Vec<Tile<P>>, // TODO impl Index
}
impl<P> Tiles<P>
where
P: pixset::PixLike,
{
pub fn new(size: units::Size2D) -> Self {
let tiles = {
// TODO area
let length = (size.width * size.height) as usize;
let mut ts = Vec::with_capacity(length);
for _ in 0..length {
let t = Tile::new();
ts.push(t);
}
ts
};
Tiles {
size: size,
tiles: tiles,
}
}
#[allow(dead_code)]
pub fn clear(&mut self) {
for t in self.tiles.iter_mut() {
t.clear();
}
}
pub fn | (&mut self, loc: units::ScreenTile2D, pix: P, fg: colors::Rgb, bg: colors::Rgb) {
// TODO asserts
let idx = (self.size.width * loc.y + loc.x) as usize;
self.tiles[idx].pix = pix;
self.tiles[idx].fg = fg;
self.tiles[idx].bg = bg;
}
}
| set | identifier_name |
tiles.rs | use super::Tile;
use colors;
use pixset;
use pixset::PixLike;
use units;
pub struct Tiles<P: PixLike> {
size: units::Size2D,
pub tiles: Vec<Tile<P>>, // TODO impl Index
}
impl<P> Tiles<P>
where
P: pixset::PixLike,
{
pub fn new(size: units::Size2D) -> Self {
let tiles = {
// TODO area
let length = (size.width * size.height) as usize;
let mut ts = Vec::with_capacity(length);
for _ in 0..length {
let t = Tile::new();
ts.push(t);
}
ts
};
Tiles {
size: size,
tiles: tiles,
}
}
| }
}
pub fn set(&mut self, loc: units::ScreenTile2D, pix: P, fg: colors::Rgb, bg: colors::Rgb) {
// TODO asserts
let idx = (self.size.width * loc.y + loc.x) as usize;
self.tiles[idx].pix = pix;
self.tiles[idx].fg = fg;
self.tiles[idx].bg = bg;
}
} | #[allow(dead_code)]
pub fn clear(&mut self) {
for t in self.tiles.iter_mut() {
t.clear(); | random_line_split |
ffi.rs | //! Useful tools for C FFI
use std::ffi::CString;
use std::os::raw::{c_char, c_int};
use std::ptr;
/// Call a main-like function with an argument vector
///
/// # Safety
///
/// Safety depends on the safety of the target FFI function.
pub unsafe fn run_with_args<S: AsRef<str>, Argv: IntoIterator<Item = S>>(
func: unsafe extern "C" fn(c_int, *mut *mut c_char) -> c_int,
args: Argv,
) -> i32 {
// 1. First clone the string values into safe storage.
let cstring_buffer: Vec<_> = args
.into_iter()
.map(|arg| CString::new(arg.as_ref()).expect("String to CString conversion failed"))
.collect();
// 2. Total number of args is fixed.
let argc = cstring_buffer.len() as c_int;
// 3. Prepare raw vector
let mut c_char_buffer: Vec<*mut c_char> = Vec::new();
for cstring in &cstring_buffer { | }
c_char_buffer.push(ptr::null_mut());
let c_argv = c_char_buffer.as_mut_ptr();
// 4. Now call the function
func(argc, c_argv) as i32
} | c_char_buffer.push(cstring.as_bytes_with_nul().as_ptr() as *mut c_char); | random_line_split |
ffi.rs | //! Useful tools for C FFI
use std::ffi::CString;
use std::os::raw::{c_char, c_int};
use std::ptr;
/// Call a main-like function with an argument vector
///
/// # Safety
///
/// Safety depends on the safety of the target FFI function.
pub unsafe fn run_with_args<S: AsRef<str>, Argv: IntoIterator<Item = S>>(
func: unsafe extern "C" fn(c_int, *mut *mut c_char) -> c_int,
args: Argv,
) -> i32 | func(argc, c_argv) as i32
}
| {
// 1. First clone the string values into safe storage.
let cstring_buffer: Vec<_> = args
.into_iter()
.map(|arg| CString::new(arg.as_ref()).expect("String to CString conversion failed"))
.collect();
// 2. Total number of args is fixed.
let argc = cstring_buffer.len() as c_int;
// 3. Prepare raw vector
let mut c_char_buffer: Vec<*mut c_char> = Vec::new();
for cstring in &cstring_buffer {
c_char_buffer.push(cstring.as_bytes_with_nul().as_ptr() as *mut c_char);
}
c_char_buffer.push(ptr::null_mut());
let c_argv = c_char_buffer.as_mut_ptr();
// 4. Now call the function | identifier_body |
ffi.rs | //! Useful tools for C FFI
use std::ffi::CString;
use std::os::raw::{c_char, c_int};
use std::ptr;
/// Call a main-like function with an argument vector
///
/// # Safety
///
/// Safety depends on the safety of the target FFI function.
pub unsafe fn | <S: AsRef<str>, Argv: IntoIterator<Item = S>>(
func: unsafe extern "C" fn(c_int, *mut *mut c_char) -> c_int,
args: Argv,
) -> i32 {
// 1. First clone the string values into safe storage.
let cstring_buffer: Vec<_> = args
.into_iter()
.map(|arg| CString::new(arg.as_ref()).expect("String to CString conversion failed"))
.collect();
// 2. Total number of args is fixed.
let argc = cstring_buffer.len() as c_int;
// 3. Prepare raw vector
let mut c_char_buffer: Vec<*mut c_char> = Vec::new();
for cstring in &cstring_buffer {
c_char_buffer.push(cstring.as_bytes_with_nul().as_ptr() as *mut c_char);
}
c_char_buffer.push(ptr::null_mut());
let c_argv = c_char_buffer.as_mut_ptr();
// 4. Now call the function
func(argc, c_argv) as i32
}
| run_with_args | identifier_name |
translate_to_glib.rs | use crate::{
analysis::{function_parameters::TransformationType, ref_mode::RefMode},
library::Transfer,
};
pub trait TranslateToGlib {
fn translate_to_glib(&self) -> String;
}
impl TranslateToGlib for TransformationType {
fn translate_to_glib(&self) -> String {
use self::TransformationType::*;
match *self {
ToGlibDirect { ref name } => name.clone(),
ToGlibScalar { ref name,.. } => format!("{}{}", name, ".to_glib()"),
ToGlibPointer {
ref name,
instance_parameter,
transfer,
ref_mode,
ref to_glib_extra,
ref pointer_cast,
ref explicit_target_type,
in_trait,
nullable,
} => {
let (left, right) = to_glib_xxx(transfer, ref_mode, explicit_target_type);
let to_glib_extra = if nullable &&!to_glib_extra.is_empty() {
format!(".map(|p| p{})", to_glib_extra)
} else {
to_glib_extra.clone()
};
if instance_parameter {
format!(
"{}self{}{}{}",
left,
if in_trait { to_glib_extra } else { "".into() },
right,
pointer_cast
)
} else {
format!("{}{}{}{}{}", left, name, to_glib_extra, right, pointer_cast)
}
}
ToGlibBorrow => "/*Not applicable conversion Borrow*/".to_owned(),
ToGlibUnknown { ref name } => format!("/*Unknown conversion*/{}", name),
ToSome(ref name) => format!("Some({})", name),
IntoRaw(ref name) => format!("Box_::into_raw({}) as *mut _", name),
_ => unreachable!("Unexpected transformation type {:?}", self),
}
}
}
fn to_glib_xxx(
transfer: Transfer,
ref_mode: RefMode,
explicit_target_type: &str,
) -> (String, &'static str) | }
}
Full => ("".into(), ".to_glib_full()"),
Container => ("".into(), ".to_glib_container().0"),
}
}
| {
use self::Transfer::*;
match transfer {
None => {
match ref_mode {
RefMode::None => ("".into(), ".to_glib_none_mut().0"), //unreachable!(),
RefMode::ByRef => {
if explicit_target_type.is_empty() {
("".into(), ".to_glib_none().0")
} else {
(
format!("ToGlibPtr::<{}>::to_glib_none(", explicit_target_type),
").0",
)
}
}
RefMode::ByRefMut => ("".into(), ".to_glib_none_mut().0"),
RefMode::ByRefImmut => ("mut_override(".into(), ".to_glib_none().0)"),
RefMode::ByRefConst => ("const_override(".into(), ".to_glib_none().0)"),
RefMode::ByRefFake => ("".into(), ""), //unreachable!(), | identifier_body |
translate_to_glib.rs | use crate::{
analysis::{function_parameters::TransformationType, ref_mode::RefMode},
library::Transfer,
};
pub trait TranslateToGlib {
fn translate_to_glib(&self) -> String;
}
impl TranslateToGlib for TransformationType {
fn translate_to_glib(&self) -> String {
use self::TransformationType::*;
match *self {
ToGlibDirect { ref name } => name.clone(),
ToGlibScalar { ref name,.. } => format!("{}{}", name, ".to_glib()"),
ToGlibPointer {
ref name,
instance_parameter,
transfer,
ref_mode,
ref to_glib_extra,
ref pointer_cast,
ref explicit_target_type,
in_trait,
nullable,
} => { | format!(".map(|p| p{})", to_glib_extra)
} else {
to_glib_extra.clone()
};
if instance_parameter {
format!(
"{}self{}{}{}",
left,
if in_trait { to_glib_extra } else { "".into() },
right,
pointer_cast
)
} else {
format!("{}{}{}{}{}", left, name, to_glib_extra, right, pointer_cast)
}
}
ToGlibBorrow => "/*Not applicable conversion Borrow*/".to_owned(),
ToGlibUnknown { ref name } => format!("/*Unknown conversion*/{}", name),
ToSome(ref name) => format!("Some({})", name),
IntoRaw(ref name) => format!("Box_::into_raw({}) as *mut _", name),
_ => unreachable!("Unexpected transformation type {:?}", self),
}
}
}
fn to_glib_xxx(
transfer: Transfer,
ref_mode: RefMode,
explicit_target_type: &str,
) -> (String, &'static str) {
use self::Transfer::*;
match transfer {
None => {
match ref_mode {
RefMode::None => ("".into(), ".to_glib_none_mut().0"), //unreachable!(),
RefMode::ByRef => {
if explicit_target_type.is_empty() {
("".into(), ".to_glib_none().0")
} else {
(
format!("ToGlibPtr::<{}>::to_glib_none(", explicit_target_type),
").0",
)
}
}
RefMode::ByRefMut => ("".into(), ".to_glib_none_mut().0"),
RefMode::ByRefImmut => ("mut_override(".into(), ".to_glib_none().0)"),
RefMode::ByRefConst => ("const_override(".into(), ".to_glib_none().0)"),
RefMode::ByRefFake => ("".into(), ""), //unreachable!(),
}
}
Full => ("".into(), ".to_glib_full()"),
Container => ("".into(), ".to_glib_container().0"),
}
} | let (left, right) = to_glib_xxx(transfer, ref_mode, explicit_target_type);
let to_glib_extra = if nullable && !to_glib_extra.is_empty() { | random_line_split |
translate_to_glib.rs | use crate::{
analysis::{function_parameters::TransformationType, ref_mode::RefMode},
library::Transfer,
};
pub trait TranslateToGlib {
fn translate_to_glib(&self) -> String;
}
impl TranslateToGlib for TransformationType {
fn translate_to_glib(&self) -> String {
use self::TransformationType::*;
match *self {
ToGlibDirect { ref name } => name.clone(),
ToGlibScalar { ref name,.. } => format!("{}{}", name, ".to_glib()"),
ToGlibPointer {
ref name,
instance_parameter,
transfer,
ref_mode,
ref to_glib_extra,
ref pointer_cast,
ref explicit_target_type,
in_trait,
nullable,
} => {
let (left, right) = to_glib_xxx(transfer, ref_mode, explicit_target_type);
let to_glib_extra = if nullable &&!to_glib_extra.is_empty() {
format!(".map(|p| p{})", to_glib_extra)
} else {
to_glib_extra.clone()
};
if instance_parameter {
format!(
"{}self{}{}{}",
left,
if in_trait { to_glib_extra } else { "".into() },
right,
pointer_cast
)
} else {
format!("{}{}{}{}{}", left, name, to_glib_extra, right, pointer_cast)
}
}
ToGlibBorrow => "/*Not applicable conversion Borrow*/".to_owned(),
ToGlibUnknown { ref name } => format!("/*Unknown conversion*/{}", name),
ToSome(ref name) => format!("Some({})", name),
IntoRaw(ref name) => format!("Box_::into_raw({}) as *mut _", name),
_ => unreachable!("Unexpected transformation type {:?}", self),
}
}
}
fn | (
transfer: Transfer,
ref_mode: RefMode,
explicit_target_type: &str,
) -> (String, &'static str) {
use self::Transfer::*;
match transfer {
None => {
match ref_mode {
RefMode::None => ("".into(), ".to_glib_none_mut().0"), //unreachable!(),
RefMode::ByRef => {
if explicit_target_type.is_empty() {
("".into(), ".to_glib_none().0")
} else {
(
format!("ToGlibPtr::<{}>::to_glib_none(", explicit_target_type),
").0",
)
}
}
RefMode::ByRefMut => ("".into(), ".to_glib_none_mut().0"),
RefMode::ByRefImmut => ("mut_override(".into(), ".to_glib_none().0)"),
RefMode::ByRefConst => ("const_override(".into(), ".to_glib_none().0)"),
RefMode::ByRefFake => ("".into(), ""), //unreachable!(),
}
}
Full => ("".into(), ".to_glib_full()"),
Container => ("".into(), ".to_glib_container().0"),
}
}
| to_glib_xxx | identifier_name |
weak.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Task-local reference counted smart pointers with weak pointer support
use mem::transmute;
use ops::Drop;
use cmp::{Eq, Ord};
use clone::{Clone, DeepClone};
use heap::free;
use ptr::read_ptr;
use option::{Option, Some, None};
use kinds::marker::NoSend;
struct RcBox<T> {
value: T,
strong: uint,
weak: uint,
no_send: NoSend
}
#[unsafe_no_drop_flag]
pub struct Strong<T> {
ptr: *mut RcBox<T>
}
impl<T> Strong<T> {
pub fn new(value: T) -> Strong<T> {
unsafe {
// The `Strong` pointers share a single `weak` reference count. This prevents the
// premature deallocation of the box when the last weak pointer is freed.
Strong { ptr: transmute(~RcBox { value: value, strong: 1, weak: 1, no_send: NoSend }) }
}
}
#[inline(always)]
pub fn borrow<'a>(&'a self) -> &'a T {
unsafe { &(*self.ptr).value }
}
pub fn downgrade(&self) -> Weak<T> |
}
#[unsafe_destructor]
impl<T> Drop for Strong<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).strong -= 1;
if (*self.ptr).strong == 0 {
read_ptr(self.borrow()); // destroy the contained object
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
}
impl<T> Clone for Strong<T> {
#[inline]
fn clone(&self) -> Strong<T> {
unsafe {
(*self.ptr).strong += 1;
Strong { ptr: self.ptr }
}
}
}
impl<T: DeepClone> DeepClone for Strong<T> {
#[inline]
fn deep_clone(&self) -> Strong<T> {
Strong::new(self.borrow().deep_clone())
}
}
impl<T: Eq> Eq for Strong<T> {
#[inline(always)]
fn eq(&self, other: &Strong<T>) -> bool { *self.borrow() == *other.borrow() }
#[inline(always)]
fn ne(&self, other: &Strong<T>) -> bool { *self.borrow()!= *other.borrow() }
}
impl<T: Ord> Ord for Strong<T> {
#[inline(always)]
fn lt(&self, other: &Strong<T>) -> bool { *self.borrow() < *other.borrow() }
#[inline(always)]
fn le(&self, other: &Strong<T>) -> bool { *self.borrow() <= *other.borrow() }
#[inline(always)]
fn gt(&self, other: &Strong<T>) -> bool { *self.borrow() > *other.borrow() }
#[inline(always)]
fn ge(&self, other: &Strong<T>) -> bool { *self.borrow() >= *other.borrow() }
}
#[unsafe_no_drop_flag]
pub struct Weak<T> {
ptr: *mut RcBox<T>
}
impl<T> Weak<T> {
pub fn upgrade(&self) -> Option<Strong<T>> {
unsafe {
if (*self.ptr).strong == 0 {
None
} else {
(*self.ptr).strong += 1;
Some(Strong { ptr: self.ptr })
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for Weak<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
}
| {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
} | identifier_body |
weak.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Task-local reference counted smart pointers with weak pointer support
use mem::transmute;
use ops::Drop;
use cmp::{Eq, Ord};
use clone::{Clone, DeepClone};
use heap::free;
use ptr::read_ptr;
use option::{Option, Some, None};
use kinds::marker::NoSend;
struct RcBox<T> {
value: T,
strong: uint,
weak: uint,
no_send: NoSend
}
#[unsafe_no_drop_flag]
pub struct Strong<T> {
ptr: *mut RcBox<T>
}
impl<T> Strong<T> {
pub fn new(value: T) -> Strong<T> {
unsafe {
// The `Strong` pointers share a single `weak` reference count. This prevents the
// premature deallocation of the box when the last weak pointer is freed.
Strong { ptr: transmute(~RcBox { value: value, strong: 1, weak: 1, no_send: NoSend }) }
}
}
#[inline(always)]
pub fn borrow<'a>(&'a self) -> &'a T {
unsafe { &(*self.ptr).value }
}
pub fn downgrade(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Strong<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).strong -= 1;
if (*self.ptr).strong == 0 {
read_ptr(self.borrow()); // destroy the contained object
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
}
impl<T> Clone for Strong<T> {
#[inline]
fn clone(&self) -> Strong<T> {
unsafe {
(*self.ptr).strong += 1;
Strong { ptr: self.ptr }
}
}
}
impl<T: DeepClone> DeepClone for Strong<T> {
#[inline]
fn deep_clone(&self) -> Strong<T> {
Strong::new(self.borrow().deep_clone())
}
}
impl<T: Eq> Eq for Strong<T> {
#[inline(always)]
fn eq(&self, other: &Strong<T>) -> bool { *self.borrow() == *other.borrow() }
#[inline(always)]
fn ne(&self, other: &Strong<T>) -> bool { *self.borrow()!= *other.borrow() }
}
impl<T: Ord> Ord for Strong<T> {
#[inline(always)]
fn lt(&self, other: &Strong<T>) -> bool { *self.borrow() < *other.borrow() }
#[inline(always)]
fn le(&self, other: &Strong<T>) -> bool { *self.borrow() <= *other.borrow() }
#[inline(always)]
fn gt(&self, other: &Strong<T>) -> bool { *self.borrow() > *other.borrow() }
#[inline(always)]
fn ge(&self, other: &Strong<T>) -> bool { *self.borrow() >= *other.borrow() }
}
#[unsafe_no_drop_flag]
pub struct Weak<T> {
ptr: *mut RcBox<T>
}
impl<T> Weak<T> {
pub fn upgrade(&self) -> Option<Strong<T>> {
unsafe {
if (*self.ptr).strong == 0 {
None
} else |
}
}
}
#[unsafe_destructor]
impl<T> Drop for Weak<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
}
| {
(*self.ptr).strong += 1;
Some(Strong { ptr: self.ptr })
} | conditional_block |
weak.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Task-local reference counted smart pointers with weak pointer support
use mem::transmute;
use ops::Drop;
use cmp::{Eq, Ord};
use clone::{Clone, DeepClone};
use heap::free;
use ptr::read_ptr;
use option::{Option, Some, None};
use kinds::marker::NoSend;
struct RcBox<T> {
value: T,
strong: uint,
weak: uint,
no_send: NoSend
}
#[unsafe_no_drop_flag]
pub struct Strong<T> {
ptr: *mut RcBox<T>
}
impl<T> Strong<T> {
pub fn new(value: T) -> Strong<T> {
unsafe {
// The `Strong` pointers share a single `weak` reference count. This prevents the
// premature deallocation of the box when the last weak pointer is freed.
Strong { ptr: transmute(~RcBox { value: value, strong: 1, weak: 1, no_send: NoSend }) }
}
}
#[inline(always)]
pub fn borrow<'a>(&'a self) -> &'a T {
unsafe { &(*self.ptr).value }
}
pub fn downgrade(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Strong<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).strong -= 1;
if (*self.ptr).strong == 0 {
read_ptr(self.borrow()); // destroy the contained object
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
}
impl<T> Clone for Strong<T> {
#[inline]
fn clone(&self) -> Strong<T> {
unsafe {
(*self.ptr).strong += 1;
Strong { ptr: self.ptr }
}
} | #[inline]
fn deep_clone(&self) -> Strong<T> {
Strong::new(self.borrow().deep_clone())
}
}
impl<T: Eq> Eq for Strong<T> {
#[inline(always)]
fn eq(&self, other: &Strong<T>) -> bool { *self.borrow() == *other.borrow() }
#[inline(always)]
fn ne(&self, other: &Strong<T>) -> bool { *self.borrow()!= *other.borrow() }
}
impl<T: Ord> Ord for Strong<T> {
#[inline(always)]
fn lt(&self, other: &Strong<T>) -> bool { *self.borrow() < *other.borrow() }
#[inline(always)]
fn le(&self, other: &Strong<T>) -> bool { *self.borrow() <= *other.borrow() }
#[inline(always)]
fn gt(&self, other: &Strong<T>) -> bool { *self.borrow() > *other.borrow() }
#[inline(always)]
fn ge(&self, other: &Strong<T>) -> bool { *self.borrow() >= *other.borrow() }
}
#[unsafe_no_drop_flag]
pub struct Weak<T> {
ptr: *mut RcBox<T>
}
impl<T> Weak<T> {
pub fn upgrade(&self) -> Option<Strong<T>> {
unsafe {
if (*self.ptr).strong == 0 {
None
} else {
(*self.ptr).strong += 1;
Some(Strong { ptr: self.ptr })
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for Weak<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
} | }
impl<T: DeepClone> DeepClone for Strong<T> { | random_line_split |
weak.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Task-local reference counted smart pointers with weak pointer support
use mem::transmute;
use ops::Drop;
use cmp::{Eq, Ord};
use clone::{Clone, DeepClone};
use heap::free;
use ptr::read_ptr;
use option::{Option, Some, None};
use kinds::marker::NoSend;
struct RcBox<T> {
value: T,
strong: uint,
weak: uint,
no_send: NoSend
}
#[unsafe_no_drop_flag]
pub struct Strong<T> {
ptr: *mut RcBox<T>
}
impl<T> Strong<T> {
pub fn new(value: T) -> Strong<T> {
unsafe {
// The `Strong` pointers share a single `weak` reference count. This prevents the
// premature deallocation of the box when the last weak pointer is freed.
Strong { ptr: transmute(~RcBox { value: value, strong: 1, weak: 1, no_send: NoSend }) }
}
}
#[inline(always)]
pub fn borrow<'a>(&'a self) -> &'a T {
unsafe { &(*self.ptr).value }
}
pub fn downgrade(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
}
#[unsafe_destructor]
impl<T> Drop for Strong<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).strong -= 1;
if (*self.ptr).strong == 0 {
read_ptr(self.borrow()); // destroy the contained object
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
}
impl<T> Clone for Strong<T> {
#[inline]
fn clone(&self) -> Strong<T> {
unsafe {
(*self.ptr).strong += 1;
Strong { ptr: self.ptr }
}
}
}
impl<T: DeepClone> DeepClone for Strong<T> {
#[inline]
fn deep_clone(&self) -> Strong<T> {
Strong::new(self.borrow().deep_clone())
}
}
impl<T: Eq> Eq for Strong<T> {
#[inline(always)]
fn eq(&self, other: &Strong<T>) -> bool { *self.borrow() == *other.borrow() }
#[inline(always)]
fn ne(&self, other: &Strong<T>) -> bool { *self.borrow()!= *other.borrow() }
}
impl<T: Ord> Ord for Strong<T> {
#[inline(always)]
fn lt(&self, other: &Strong<T>) -> bool { *self.borrow() < *other.borrow() }
#[inline(always)]
fn le(&self, other: &Strong<T>) -> bool { *self.borrow() <= *other.borrow() }
#[inline(always)]
fn | (&self, other: &Strong<T>) -> bool { *self.borrow() > *other.borrow() }
#[inline(always)]
fn ge(&self, other: &Strong<T>) -> bool { *self.borrow() >= *other.borrow() }
}
#[unsafe_no_drop_flag]
pub struct Weak<T> {
ptr: *mut RcBox<T>
}
impl<T> Weak<T> {
pub fn upgrade(&self) -> Option<Strong<T>> {
unsafe {
if (*self.ptr).strong == 0 {
None
} else {
(*self.ptr).strong += 1;
Some(Strong { ptr: self.ptr })
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for Weak<T> {
fn drop(&mut self) {
unsafe {
if self.ptr!= 0 as *mut RcBox<T> {
(*self.ptr).weak -= 1;
if (*self.ptr).weak == 0 {
free(self.ptr as *mut u8)
}
}
}
}
}
impl<T> Clone for Weak<T> {
#[inline]
fn clone(&self) -> Weak<T> {
unsafe {
(*self.ptr).weak += 1;
Weak { ptr: self.ptr }
}
}
}
| gt | identifier_name |
adt-tuple-struct.rs | // Copyright 2017 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.
// Unit test for the "user substitutions" that are annotated on each
// node.
#![feature(nll)]
struct SomeStruct<T>(T);
fn no_annot() {
let c = 66;
SomeStruct(&c); | }
fn annot_underscore() {
let c = 66;
SomeStruct::<_>(&c);
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32>(&c);
}
fn annot_reference_static_lifetime() {
let c = 66;
SomeStruct::<&'static u32>(&c); //~ ERROR
}
fn annot_reference_named_lifetime<'a>(_d: &'a u32) {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
}
fn annot_reference_named_lifetime_ok<'a>(c: &'a u32) {
SomeStruct::<&'a u32>(c);
}
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) {
let _closure = || {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
};
}
fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) {
let _closure = || {
SomeStruct::<&'a u32>(c);
};
}
fn main() { } | random_line_split |
|
adt-tuple-struct.rs | // Copyright 2017 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.
// Unit test for the "user substitutions" that are annotated on each
// node.
#![feature(nll)]
struct SomeStruct<T>(T);
fn no_annot() {
let c = 66;
SomeStruct(&c);
}
fn annot_underscore() |
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32>(&c);
}
fn annot_reference_static_lifetime() {
let c = 66;
SomeStruct::<&'static u32>(&c); //~ ERROR
}
fn annot_reference_named_lifetime<'a>(_d: &'a u32) {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
}
fn annot_reference_named_lifetime_ok<'a>(c: &'a u32) {
SomeStruct::<&'a u32>(c);
}
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) {
let _closure = || {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
};
}
fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) {
let _closure = || {
SomeStruct::<&'a u32>(c);
};
}
fn main() { }
| {
let c = 66;
SomeStruct::<_>(&c);
} | identifier_body |
adt-tuple-struct.rs | // Copyright 2017 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.
// Unit test for the "user substitutions" that are annotated on each
// node.
#![feature(nll)]
struct | <T>(T);
fn no_annot() {
let c = 66;
SomeStruct(&c);
}
fn annot_underscore() {
let c = 66;
SomeStruct::<_>(&c);
}
fn annot_reference_any_lifetime() {
let c = 66;
SomeStruct::<&u32>(&c);
}
fn annot_reference_static_lifetime() {
let c = 66;
SomeStruct::<&'static u32>(&c); //~ ERROR
}
fn annot_reference_named_lifetime<'a>(_d: &'a u32) {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
}
fn annot_reference_named_lifetime_ok<'a>(c: &'a u32) {
SomeStruct::<&'a u32>(c);
}
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) {
let _closure = || {
let c = 66;
SomeStruct::<&'a u32>(&c); //~ ERROR
};
}
fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) {
let _closure = || {
SomeStruct::<&'a u32>(c);
};
}
fn main() { }
| SomeStruct | identifier_name |
main.rs | /*
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time by finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer index (starting with 0).
A hash indicates the next character in the password if its hexadecimal representation starts with five zeroes. If it does, the sixth character in the hash is the next character of the password.
For example, if the Door ID is abc:
The first index which produces a hash that starts with five zeroes is 3231929, which we find by hashing abc3231929; the sixth character of the hash, and thus the first character of the password, is 1.
5017308 produces the next interesting hash, which starts with 000008f82..., so the second character of the password is 8.
The third time a hash starts with five zeroes is for abc5278568, discovering the character f.
In this example, after continuing this search a total of eight times, the password is 18f47a30.
Given the actual Door ID, what is the password?
--- Part Two ---
As the door slides open, you are presented with a second door that uses a slightly more inspired security mechanism. Clearly unimpressed by the last version (in what movie is the password decrypted in order?!), the Easter Bunny engineers have worked out a better solution.
Instead of simply filling in the password from left to right, the hash now also indicates the position within the password to fill. You still look for hashes that begin with five zeroes; however, now, the sixth character represents the position (0-7), and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password. Use only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015...; so, 5 goes in position 1: _5______.
In the previous method, 5017308 produced an interesting hash; however, it is ignored, because it specifies an invalid position (8).
The second interesting hash is at index 5357525, which produces 000004e...; so, e goes in position 4: _5__e___.
You almost choke on your popcorn as the final character falls into place, producing the password 05ace8e3.
Given the actual Door ID and this new method, what is the password? Be extra proud of your solution if it uses a cinematic "decrypting" animation.
*/
extern crate crypto;
use crypto::md5::Md5;
use crypto::digest::Digest;
fn hash(input : &str) -> String {
let mut hash = Md5::new();
hash.input_str(&input);
hash.result_str()
}
fn solve_part_a(puzzle_input : &str){
let mut pass = Vec::new();
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
pass.push(result.chars().nth(5).unwrap());
// once the pass reaches 8 chars, break
if pass.len() == 8 {
break;
}
}
}
// we got em. 😏
println!("[PART A] cracked pass: {:?}", pass);
}
fn solve_part_b(puzzle_input : &str){
let mut pass = vec![None; 8];
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
if let Some(location) = result.chars().nth(5).unwrap().to_digit(10) {
let location = location as usize;
if location > 7 { continue };
if pass.get(location).unwrap().is_some() { continue; }
let character = result.chars().nth(6).unwrap();
pass[location] = result.chars().nth(6);
println!("found character {} for location {}", character, location);
}
}
// once all characters are filled in, break
if pass.iter().all(|c| c.is_some()) {
| }
// we got em. 😏
let pass_string : String = pass.iter().map(|c| c.unwrap()).collect();
println!("[PART B] cracked the pass: {:?}", pass_string);
}
fn main() {
const PUZZLE_INPUT : &'static str = "reyedfim";
solve_part_a(PUZZLE_INPUT);
solve_part_b(PUZZLE_INPUT);
}
| break;
}
| conditional_block |
main.rs | /*
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies.
| The eight-character password for the door is generated one character at a time by finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer index (starting with 0).
A hash indicates the next character in the password if its hexadecimal representation starts with five zeroes. If it does, the sixth character in the hash is the next character of the password.
For example, if the Door ID is abc:
The first index which produces a hash that starts with five zeroes is 3231929, which we find by hashing abc3231929; the sixth character of the hash, and thus the first character of the password, is 1.
5017308 produces the next interesting hash, which starts with 000008f82..., so the second character of the password is 8.
The third time a hash starts with five zeroes is for abc5278568, discovering the character f.
In this example, after continuing this search a total of eight times, the password is 18f47a30.
Given the actual Door ID, what is the password?
--- Part Two ---
As the door slides open, you are presented with a second door that uses a slightly more inspired security mechanism. Clearly unimpressed by the last version (in what movie is the password decrypted in order?!), the Easter Bunny engineers have worked out a better solution.
Instead of simply filling in the password from left to right, the hash now also indicates the position within the password to fill. You still look for hashes that begin with five zeroes; however, now, the sixth character represents the position (0-7), and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password. Use only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015...; so, 5 goes in position 1: _5______.
In the previous method, 5017308 produced an interesting hash; however, it is ignored, because it specifies an invalid position (8).
The second interesting hash is at index 5357525, which produces 000004e...; so, e goes in position 4: _5__e___.
You almost choke on your popcorn as the final character falls into place, producing the password 05ace8e3.
Given the actual Door ID and this new method, what is the password? Be extra proud of your solution if it uses a cinematic "decrypting" animation.
*/
extern crate crypto;
use crypto::md5::Md5;
use crypto::digest::Digest;
fn hash(input : &str) -> String {
let mut hash = Md5::new();
hash.input_str(&input);
hash.result_str()
}
fn solve_part_a(puzzle_input : &str){
let mut pass = Vec::new();
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
pass.push(result.chars().nth(5).unwrap());
// once the pass reaches 8 chars, break
if pass.len() == 8 {
break;
}
}
}
// we got em. 😏
println!("[PART A] cracked pass: {:?}", pass);
}
fn solve_part_b(puzzle_input : &str){
let mut pass = vec![None; 8];
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
if let Some(location) = result.chars().nth(5).unwrap().to_digit(10) {
let location = location as usize;
if location > 7 { continue };
if pass.get(location).unwrap().is_some() { continue; }
let character = result.chars().nth(6).unwrap();
pass[location] = result.chars().nth(6);
println!("found character {} for location {}", character, location);
}
}
// once all characters are filled in, break
if pass.iter().all(|c| c.is_some()) {
break;
}
}
// we got em. 😏
let pass_string : String = pass.iter().map(|c| c.unwrap()).collect();
println!("[PART B] cracked the pass: {:?}", pass_string);
}
fn main() {
const PUZZLE_INPUT : &'static str = "reyedfim";
solve_part_a(PUZZLE_INPUT);
solve_part_b(PUZZLE_INPUT);
} | random_line_split |
|
main.rs | /*
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time by finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer index (starting with 0).
A hash indicates the next character in the password if its hexadecimal representation starts with five zeroes. If it does, the sixth character in the hash is the next character of the password.
For example, if the Door ID is abc:
The first index which produces a hash that starts with five zeroes is 3231929, which we find by hashing abc3231929; the sixth character of the hash, and thus the first character of the password, is 1.
5017308 produces the next interesting hash, which starts with 000008f82..., so the second character of the password is 8.
The third time a hash starts with five zeroes is for abc5278568, discovering the character f.
In this example, after continuing this search a total of eight times, the password is 18f47a30.
Given the actual Door ID, what is the password?
--- Part Two ---
As the door slides open, you are presented with a second door that uses a slightly more inspired security mechanism. Clearly unimpressed by the last version (in what movie is the password decrypted in order?!), the Easter Bunny engineers have worked out a better solution.
Instead of simply filling in the password from left to right, the hash now also indicates the position within the password to fill. You still look for hashes that begin with five zeroes; however, now, the sixth character represents the position (0-7), and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password. Use only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015...; so, 5 goes in position 1: _5______.
In the previous method, 5017308 produced an interesting hash; however, it is ignored, because it specifies an invalid position (8).
The second interesting hash is at index 5357525, which produces 000004e...; so, e goes in position 4: _5__e___.
You almost choke on your popcorn as the final character falls into place, producing the password 05ace8e3.
Given the actual Door ID and this new method, what is the password? Be extra proud of your solution if it uses a cinematic "decrypting" animation.
*/
extern crate crypto;
use crypto::md5::Md5;
use crypto::digest::Digest;
fn hash(input : &str) -> String {
let mut hash = Md5::new();
hash.input_str(&input);
hash.result_str()
}
fn solve_part_a(puzzle_input : &str){
let mut pass = Vec::new();
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
pass.push(result.chars().nth(5).unwrap());
// once the pass reaches 8 chars, break
if pass.len() == 8 {
break;
}
}
}
// we got em. 😏
println!("[PART A] cracked pass: {:?}", pass);
}
fn solve_part_b(puzzle_input : &str){
let mut pass = vec![None; 8];
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
if let Some(location) = result.chars().nth(5).unwrap().to_digit(10) {
let location = location as usize;
if location > 7 { continue };
if pass.get(location).unwrap().is_some() { continue; }
let character = result.chars().nth(6).unwrap();
pass[location] = result.chars().nth(6);
println!("found character {} for location {}", character, location);
}
}
// once all characters are filled in, break
if pass.iter().all(|c| c.is_some()) {
break;
}
}
// we got em. 😏
let pass_string : String = pass.iter().map(|c| c.unwrap()).collect();
println!("[PART B] cracked the pass: {:?}", pass_string);
}
fn main() {
| const PUZZLE_INPUT : &'static str = "reyedfim";
solve_part_a(PUZZLE_INPUT);
solve_part_b(PUZZLE_INPUT);
}
| identifier_body |
|
main.rs | /*
--- Day 5: How About a Nice Game of Chess? ---
You are faced with a security door designed by Easter Bunny engineers that seem to have acquired most of their security knowledge by watching hacking movies.
The eight-character password for the door is generated one character at a time by finding the MD5 hash of some Door ID (your puzzle input) and an increasing integer index (starting with 0).
A hash indicates the next character in the password if its hexadecimal representation starts with five zeroes. If it does, the sixth character in the hash is the next character of the password.
For example, if the Door ID is abc:
The first index which produces a hash that starts with five zeroes is 3231929, which we find by hashing abc3231929; the sixth character of the hash, and thus the first character of the password, is 1.
5017308 produces the next interesting hash, which starts with 000008f82..., so the second character of the password is 8.
The third time a hash starts with five zeroes is for abc5278568, discovering the character f.
In this example, after continuing this search a total of eight times, the password is 18f47a30.
Given the actual Door ID, what is the password?
--- Part Two ---
As the door slides open, you are presented with a second door that uses a slightly more inspired security mechanism. Clearly unimpressed by the last version (in what movie is the password decrypted in order?!), the Easter Bunny engineers have worked out a better solution.
Instead of simply filling in the password from left to right, the hash now also indicates the position within the password to fill. You still look for hashes that begin with five zeroes; however, now, the sixth character represents the position (0-7), and the seventh character is the character to put in that position.
A hash result of 000001f means that f is the second character in the password. Use only the first result for each position, and ignore invalid positions.
For example, if the Door ID is abc:
The first interesting hash is from abc3231929, which produces 0000015...; so, 5 goes in position 1: _5______.
In the previous method, 5017308 produced an interesting hash; however, it is ignored, because it specifies an invalid position (8).
The second interesting hash is at index 5357525, which produces 000004e...; so, e goes in position 4: _5__e___.
You almost choke on your popcorn as the final character falls into place, producing the password 05ace8e3.
Given the actual Door ID and this new method, what is the password? Be extra proud of your solution if it uses a cinematic "decrypting" animation.
*/
extern crate crypto;
use crypto::md5::Md5;
use crypto::digest::Digest;
fn hash(input : &str) -> String {
let mut hash = Md5::new();
hash.input_str(&input);
hash.result_str()
}
fn solve_part_a(puzzle_input : &str){
let mut pass = Vec::new();
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
pass.push(result.chars().nth(5).unwrap());
// once the pass reaches 8 chars, break
if pass.len() == 8 {
break;
}
}
}
// we got em. 😏
println!("[PART A] cracked pass: {:?}", pass);
}
fn solve_part_b(puzzle_input : &str){
let mut pass = vec![None; 8];
// iterate forever until we break
for i in 0..std::u64::MAX {
let input : &str = &format!("{}{}", puzzle_input, i);
let result = hash(&input);
if result.starts_with("00000") {
if let Some(location) = result.chars().nth(5).unwrap().to_digit(10) {
let location = location as usize;
if location > 7 { continue };
if pass.get(location).unwrap().is_some() { continue; }
let character = result.chars().nth(6).unwrap();
pass[location] = result.chars().nth(6);
println!("found character {} for location {}", character, location);
}
}
// once all characters are filled in, break
if pass.iter().all(|c| c.is_some()) {
break;
}
}
// we got em. 😏
let pass_string : String = pass.iter().map(|c| c.unwrap()).collect();
println!("[PART B] cracked the pass: {:?}", pass_string);
}
fn main() | const PUZZLE_INPUT : &'static str = "reyedfim";
solve_part_a(PUZZLE_INPUT);
solve_part_b(PUZZLE_INPUT);
}
| {
| identifier_name |
htmlheadelement.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::HTMLHeadElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHeadElementDerived;
use dom::bindings::js::JS;
use dom::document::Document;
use dom::element::HTMLHeadElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct HTMLHeadElement {
htmlelement: HTMLElement
}
impl HTMLHeadElementDerived for EventTarget {
fn is_htmlheadelement(&self) -> bool {
match self.type_id {
NodeTargetTypeId(ElementNodeTypeId(HTMLHeadElementTypeId)) => true,
_ => false
}
}
}
impl HTMLHeadElement {
pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLHeadElement {
HTMLHeadElement {
htmlelement: HTMLElement::new_inherited(HTMLHeadElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLHeadElement> {
let element = HTMLHeadElement::new_inherited(localName, document.clone());
Node::reflect_node(~element, document, HTMLHeadElementBinding::Wrap)
} | } | random_line_split |
|
htmlheadelement.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::HTMLHeadElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLHeadElementDerived;
use dom::bindings::js::JS;
use dom::document::Document;
use dom::element::HTMLHeadElementTypeId;
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, ElementNodeTypeId};
use servo_util::str::DOMString;
#[deriving(Encodable)]
pub struct | {
htmlelement: HTMLElement
}
impl HTMLHeadElementDerived for EventTarget {
fn is_htmlheadelement(&self) -> bool {
match self.type_id {
NodeTargetTypeId(ElementNodeTypeId(HTMLHeadElementTypeId)) => true,
_ => false
}
}
}
impl HTMLHeadElement {
pub fn new_inherited(localName: DOMString, document: JS<Document>) -> HTMLHeadElement {
HTMLHeadElement {
htmlelement: HTMLElement::new_inherited(HTMLHeadElementTypeId, localName, document)
}
}
pub fn new(localName: DOMString, document: &JS<Document>) -> JS<HTMLHeadElement> {
let element = HTMLHeadElement::new_inherited(localName, document.clone());
Node::reflect_node(~element, document, HTMLHeadElementBinding::Wrap)
}
}
| HTMLHeadElement | identifier_name |
sort.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/. */
//! In-place sorting.
fn quicksort_helper<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: int) {
if right <= left {
return
}
let mut i: int = left - 1;
let mut j: int = right;
let mut p: int = i;
let mut q: int = j;
unsafe {
let v: *mut T = &mut arr[right as uint];
loop {
i += 1;
while arr[i as uint] < (*v) {
i += 1
}
j -= 1;
while (*v) < arr[j as uint] {
if j == left {
break
}
j -= 1;
}
if i >= j {
break
}
arr.swap(i as uint, j as uint);
if arr[i as uint] == (*v) {
p += 1;
arr.swap(p as uint, i as uint)
}
if (*v) == arr[j as uint] {
q -= 1;
arr.swap(j as uint, q as uint)
}
}
}
arr.swap(i as uint, right as uint);
j = i - 1;
i += 1;
let mut k: int = left;
while k < p {
arr.swap(k as uint, j as uint);
k += 1;
j -= 1;
assert!(k < arr.len() as int);
}
k = right - 1;
while k > q {
arr.swap(i as uint, k as uint);
k -= 1;
i += 1;
assert!(k!= 0);
}
quicksort_helper(arr, left, j);
quicksort_helper(arr, i, right);
}
/// An in-place quicksort.
///
/// The algorithm is from Sedgewick and Bentley, "Quicksort is Optimal":
/// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
pub fn quicksort<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T]) |
#[cfg(test)]
pub mod test {
use std::rand;
use std::rand::Rng;
use sort;
#[test]
pub fn random() {
let mut rng = rand::task_rng();
for _ in range(0, 50000) {
let len: uint = rng.gen();
let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect();
sort::quicksort(v.as_mut_slice());
for i in range(0, v.len() - 1) {
assert!(v.get(i) <= v.get(i + 1))
}
}
}
}
| {
if arr.len() <= 1 {
return
}
let len = arr.len();
quicksort_helper(arr, 0, (len - 1) as int);
} | identifier_body |
sort.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/. */
//! In-place sorting.
fn | <T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: int) {
if right <= left {
return
}
let mut i: int = left - 1;
let mut j: int = right;
let mut p: int = i;
let mut q: int = j;
unsafe {
let v: *mut T = &mut arr[right as uint];
loop {
i += 1;
while arr[i as uint] < (*v) {
i += 1
}
j -= 1;
while (*v) < arr[j as uint] {
if j == left {
break
}
j -= 1;
}
if i >= j {
break
}
arr.swap(i as uint, j as uint);
if arr[i as uint] == (*v) {
p += 1;
arr.swap(p as uint, i as uint)
}
if (*v) == arr[j as uint] {
q -= 1;
arr.swap(j as uint, q as uint)
}
}
}
arr.swap(i as uint, right as uint);
j = i - 1;
i += 1;
let mut k: int = left;
while k < p {
arr.swap(k as uint, j as uint);
k += 1;
j -= 1;
assert!(k < arr.len() as int);
}
k = right - 1;
while k > q {
arr.swap(i as uint, k as uint);
k -= 1;
i += 1;
assert!(k!= 0);
}
quicksort_helper(arr, left, j);
quicksort_helper(arr, i, right);
}
/// An in-place quicksort.
///
/// The algorithm is from Sedgewick and Bentley, "Quicksort is Optimal":
/// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
pub fn quicksort<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T]) {
if arr.len() <= 1 {
return
}
let len = arr.len();
quicksort_helper(arr, 0, (len - 1) as int);
}
#[cfg(test)]
pub mod test {
use std::rand;
use std::rand::Rng;
use sort;
#[test]
pub fn random() {
let mut rng = rand::task_rng();
for _ in range(0, 50000) {
let len: uint = rng.gen();
let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect();
sort::quicksort(v.as_mut_slice());
for i in range(0, v.len() - 1) {
assert!(v.get(i) <= v.get(i + 1))
}
}
}
}
| quicksort_helper | identifier_name |
sort.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/. */
//! In-place sorting.
fn quicksort_helper<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: int) {
if right <= left {
return
}
let mut i: int = left - 1;
let mut j: int = right;
let mut p: int = i;
let mut q: int = j;
unsafe {
let v: *mut T = &mut arr[right as uint];
loop {
i += 1;
while arr[i as uint] < (*v) {
i += 1
}
j -= 1;
while (*v) < arr[j as uint] {
if j == left {
break
}
j -= 1;
}
if i >= j |
arr.swap(i as uint, j as uint);
if arr[i as uint] == (*v) {
p += 1;
arr.swap(p as uint, i as uint)
}
if (*v) == arr[j as uint] {
q -= 1;
arr.swap(j as uint, q as uint)
}
}
}
arr.swap(i as uint, right as uint);
j = i - 1;
i += 1;
let mut k: int = left;
while k < p {
arr.swap(k as uint, j as uint);
k += 1;
j -= 1;
assert!(k < arr.len() as int);
}
k = right - 1;
while k > q {
arr.swap(i as uint, k as uint);
k -= 1;
i += 1;
assert!(k!= 0);
}
quicksort_helper(arr, left, j);
quicksort_helper(arr, i, right);
}
/// An in-place quicksort.
///
/// The algorithm is from Sedgewick and Bentley, "Quicksort is Optimal":
/// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
pub fn quicksort<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T]) {
if arr.len() <= 1 {
return
}
let len = arr.len();
quicksort_helper(arr, 0, (len - 1) as int);
}
#[cfg(test)]
pub mod test {
use std::rand;
use std::rand::Rng;
use sort;
#[test]
pub fn random() {
let mut rng = rand::task_rng();
for _ in range(0, 50000) {
let len: uint = rng.gen();
let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect();
sort::quicksort(v.as_mut_slice());
for i in range(0, v.len() - 1) {
assert!(v.get(i) <= v.get(i + 1))
}
}
}
}
| {
break
} | conditional_block |
sort.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/. */ |
fn quicksort_helper<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T], left: int, right: int) {
if right <= left {
return
}
let mut i: int = left - 1;
let mut j: int = right;
let mut p: int = i;
let mut q: int = j;
unsafe {
let v: *mut T = &mut arr[right as uint];
loop {
i += 1;
while arr[i as uint] < (*v) {
i += 1
}
j -= 1;
while (*v) < arr[j as uint] {
if j == left {
break
}
j -= 1;
}
if i >= j {
break
}
arr.swap(i as uint, j as uint);
if arr[i as uint] == (*v) {
p += 1;
arr.swap(p as uint, i as uint)
}
if (*v) == arr[j as uint] {
q -= 1;
arr.swap(j as uint, q as uint)
}
}
}
arr.swap(i as uint, right as uint);
j = i - 1;
i += 1;
let mut k: int = left;
while k < p {
arr.swap(k as uint, j as uint);
k += 1;
j -= 1;
assert!(k < arr.len() as int);
}
k = right - 1;
while k > q {
arr.swap(i as uint, k as uint);
k -= 1;
i += 1;
assert!(k!= 0);
}
quicksort_helper(arr, left, j);
quicksort_helper(arr, i, right);
}
/// An in-place quicksort.
///
/// The algorithm is from Sedgewick and Bentley, "Quicksort is Optimal":
/// http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf
pub fn quicksort<T:Ord + Eq + PartialOrd + PartialEq>(arr: &mut [T]) {
if arr.len() <= 1 {
return
}
let len = arr.len();
quicksort_helper(arr, 0, (len - 1) as int);
}
#[cfg(test)]
pub mod test {
use std::rand;
use std::rand::Rng;
use sort;
#[test]
pub fn random() {
let mut rng = rand::task_rng();
for _ in range(0, 50000) {
let len: uint = rng.gen();
let mut v: Vec<int> = rng.gen_iter::<int>().take((len % 32) + 1).collect();
sort::quicksort(v.as_mut_slice());
for i in range(0, v.len() - 1) {
assert!(v.get(i) <= v.get(i + 1))
}
}
}
} |
//! In-place sorting. | random_line_split |
task-killjoin.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.
// xfail-win32
// Create a task that is supervised by another task, join the supervised task
// from the supervising task, then fail the supervised task. The supervised
// task will kill the supervising task, waking it up. The supervising task no
// longer needs to be wakened when the supervised task exits.
fn supervised() {
// Yield to make sure the supervisor joins before we fail. This is
// currently not needed because the supervisor runs first, but I can
// imagine that changing.
task::yield();
fail!();
}
fn supervisor() {
// Unsupervise this task so the process doesn't return a failure status as
// a result of the main task being killed.
let f = supervised;
task::try(supervised);
}
pub fn main() |
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
| {
task::spawn_unlinked(supervisor)
} | identifier_body |
task-killjoin.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.
// xfail-win32
// Create a task that is supervised by another task, join the supervised task
// from the supervising task, then fail the supervised task. The supervised
// task will kill the supervising task, waking it up. The supervising task no
// longer needs to be wakened when the supervised task exits.
| // currently not needed because the supervisor runs first, but I can
// imagine that changing.
task::yield();
fail!();
}
fn supervisor() {
// Unsupervise this task so the process doesn't return a failure status as
// a result of the main task being killed.
let f = supervised;
task::try(supervised);
}
pub fn main() {
task::spawn_unlinked(supervisor)
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End: | fn supervised() {
// Yield to make sure the supervisor joins before we fail. This is | random_line_split |
task-killjoin.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.
// xfail-win32
// Create a task that is supervised by another task, join the supervised task
// from the supervising task, then fail the supervised task. The supervised
// task will kill the supervising task, waking it up. The supervising task no
// longer needs to be wakened when the supervised task exits.
fn | () {
// Yield to make sure the supervisor joins before we fail. This is
// currently not needed because the supervisor runs first, but I can
// imagine that changing.
task::yield();
fail!();
}
fn supervisor() {
// Unsupervise this task so the process doesn't return a failure status as
// a result of the main task being killed.
let f = supervised;
task::try(supervised);
}
pub fn main() {
task::spawn_unlinked(supervisor)
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
| supervised | identifier_name |
eval_assignment.rs | use crate::helpers::{values::*, *};
use ostrov::errors::RuntimeError::*;
#[test]
fn returns_expression() {
assert_eval_val(
"(define x 0)
(set! x (+ x 1))",
unspecified(),
);
}
#[test]
fn overwrites_variables() {
assert_eval(
"(define x 0)
(set! x (+ x 1))
x",
"1",
);
}
#[test]
fn overwrites_variables_on_upper_scopes() {
assert_eval(
"(define x 0)
(define (f)
(set! x (+ x 1)))
(f)
(f)
(f)
x",
"3",
);
}
#[test]
fn | () {
assert_eval(
"(define (gen-counter)
(define counter 0)
(lambda ()
(set! counter (+ counter 1))
counter))
(define count (gen-counter))
(count)
(count)
(count)",
"3",
);
}
#[test]
fn malformed_variable_name() {
assert_eval_err("(set! 3 3)", MalformedExpression);
}
#[test]
fn unknown_variable() {
assert_eval_err("(set! x 3)", UnboundVariable("x".into()));
}
#[test]
fn wrong_arguments_number() {
assert_eval_err("(set!)", BadArity(Some("set!".into())));
assert_eval_err("(set! x)", BadArity(Some("set!".into())));
assert_eval_err("(set! x 2 3)", BadArity(Some("set!".into())));
}
| overwrites_variables_in_captured_scopes | identifier_name |
eval_assignment.rs | use crate::helpers::{values::*, *};
use ostrov::errors::RuntimeError::*;
#[test]
fn returns_expression() {
assert_eval_val(
"(define x 0)
(set! x (+ x 1))",
unspecified(),
);
}
#[test]
fn overwrites_variables() {
assert_eval(
"(define x 0)
(set! x (+ x 1))
x",
"1",
);
}
#[test]
fn overwrites_variables_on_upper_scopes() {
assert_eval(
"(define x 0)
(define (f)
(set! x (+ x 1)))
(f)
(f)
(f)
x",
"3",
);
}
#[test]
fn overwrites_variables_in_captured_scopes() {
assert_eval(
"(define (gen-counter)
(define counter 0)
(lambda ()
(set! counter (+ counter 1))
counter))
(define count (gen-counter))
(count)
(count)
(count)", | "3",
);
}
#[test]
fn malformed_variable_name() {
assert_eval_err("(set! 3 3)", MalformedExpression);
}
#[test]
fn unknown_variable() {
assert_eval_err("(set! x 3)", UnboundVariable("x".into()));
}
#[test]
fn wrong_arguments_number() {
assert_eval_err("(set!)", BadArity(Some("set!".into())));
assert_eval_err("(set! x)", BadArity(Some("set!".into())));
assert_eval_err("(set! x 2 3)", BadArity(Some("set!".into())));
} | random_line_split |
|
eval_assignment.rs | use crate::helpers::{values::*, *};
use ostrov::errors::RuntimeError::*;
#[test]
fn returns_expression() {
assert_eval_val(
"(define x 0)
(set! x (+ x 1))",
unspecified(),
);
}
#[test]
fn overwrites_variables() {
assert_eval(
"(define x 0)
(set! x (+ x 1))
x",
"1",
);
}
#[test]
fn overwrites_variables_on_upper_scopes() {
assert_eval(
"(define x 0)
(define (f)
(set! x (+ x 1)))
(f)
(f)
(f)
x",
"3",
);
}
#[test]
fn overwrites_variables_in_captured_scopes() {
assert_eval(
"(define (gen-counter)
(define counter 0)
(lambda ()
(set! counter (+ counter 1))
counter))
(define count (gen-counter))
(count)
(count)
(count)",
"3",
);
}
#[test]
fn malformed_variable_name() |
#[test]
fn unknown_variable() {
assert_eval_err("(set! x 3)", UnboundVariable("x".into()));
}
#[test]
fn wrong_arguments_number() {
assert_eval_err("(set!)", BadArity(Some("set!".into())));
assert_eval_err("(set! x)", BadArity(Some("set!".into())));
assert_eval_err("(set! x 2 3)", BadArity(Some("set!".into())));
}
| {
assert_eval_err("(set! 3 3)", MalformedExpression);
} | identifier_body |
mcts.rs | use crate::actions::Action;
use crate::Role;
use mcts::{statistics, SearchSettings};
use rand::Rng;
use search_graph;
use std::{cmp, mem};
#[derive(Clone, Debug)]
pub struct Game {}
impl statistics::two_player::PlayerMapping for Role {
fn player_one() -> Self {
Role::Dwarf
}
fn player_two() -> Self {
Role::Troll
}
fn resolve_player(&self) -> statistics::two_player::Player {
match *self {
Role::Dwarf => statistics::two_player::Player::One,
Role::Troll => statistics::two_player::Player::Two,
}
}
}
impl mcts::game::State for crate::state::State {
type Action = Action;
type PlayerId = Role;
fn active_player(&self) -> &Role {
&self.active_role()
}
fn actions<'s>(&'s self) -> Box<dyn Iterator<Item = Action> +'s> {
Box::new(self.actions())
}
fn do_action(&mut self, action: &Action) {
self.do_action(action);
}
}
impl mcts::game::Game for Game {
type Action = Action;
type PlayerId = Role;
type Payoff = statistics::two_player::ScoredPayoff;
type State = crate::state::State;
type Statistics = statistics::two_player::ScoredStatistics<Role>;
fn payoff_of(state: &Self::State) -> Option<Self::Payoff> {
if state.terminated() {
Some(statistics::two_player::ScoredPayoff {
visits: 1,
score_one: state.score(Role::Dwarf) as u32,
score_two: state.score(Role::Troll) as u32,
})
} else {
None
}
}
}
/// Controls how a game action is selected by the [MCTS
/// agent](struct.Agent.html) after MCTS search has terminated and all
/// statistics have been gathered.
#[derive(Debug, Clone, Copy)]
pub enum ActionSelect {
/// Select the action that was visited the most times.
VisitCount,
/// Select the action with the best UCB score.
Ucb,
}
/// Controls how graph compaction is done by the [MCTS agent](struct.Agent.html)
/// before each round of MCTS search.
#[derive(Debug, Clone, Copy)]
pub enum GraphCompact {
/// Prune the search graph so that the current game state and all its
/// descendants are retained, but game states that are not reachable from the
/// current game state are removed.
Prune,
/// Clear the entire search graph.
Clear,
/// Retain the entire contents of the search graph.
Retain,
}
type SearchGraph =
search_graph::Graph<crate::state::State, mcts::graph::VertexData, mcts::graph::EdgeData<Game>>;
pub struct Agent<R: Rng> {
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
graph: SearchGraph,
}
impl<R: Rng> Agent<R> {
pub fn new(
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
) -> Self {
Agent {
settings,
iterations,
rng,
action_select,
graph_compact,
graph: SearchGraph::new(),
}
}
}
fn find_most_visited_child<'a, 'id, R: Rng>(
view: &search_graph::view::View<
'a, | crate::state::State,
mcts::graph::VertexData,
mcts::graph::EdgeData<Game>,
>,
root: search_graph::view::NodeRef<'id>,
mut rng: R,
) -> search_graph::view::EdgeRef<'id> {
let mut children = view.children(root);
let mut best_child = children.next().unwrap();
let mut best_child_visits = view[best_child].statistics.visits();
let mut reservoir_count = 1u32;
for child in children {
let visits = view[child].statistics.visits();
match visits.cmp(&best_child_visits) {
cmp::Ordering::Less => continue,
cmp::Ordering::Equal => {
reservoir_count += 1;
if!rng.gen_bool(1.0f64 / (reservoir_count as f64)) {
continue;
}
}
cmp::Ordering::Greater => reservoir_count = 1,
}
best_child = child;
best_child_visits = visits;
}
best_child
}
impl<R: Rng + Send> crate::agent::Agent for Agent<R> {
fn propose_action(&mut self, state: &crate::state::State) -> crate::agent::Result {
match self.graph_compact {
GraphCompact::Prune => {
if let Some(node) = self.graph.find_node_mut(state) {
search_graph::view::of_node(node, |view, node| {
view.retain_reachable_from(Some(node).into_iter());
});
} else {
mem::swap(&mut self.graph, &mut SearchGraph::new());
}
}
GraphCompact::Clear => mem::swap(&mut self.graph, &mut SearchGraph::new()),
GraphCompact::Retain => (),
}
// Borrow/copy stuff out of self because the closure passed to of_graph
// can't borrow self.
let (rng, graph, settings, iterations, action_select) = (
&mut self.rng,
&mut self.graph,
self.settings.clone(),
self.iterations,
self.action_select,
);
search_graph::view::of_graph(graph, |view| -> crate::agent::Result {
let mut rollout = mcts::RolloutPhase::initialize(rng, settings, state.clone(), view);
for _ in 0..iterations {
let scoring = match rollout.rollout::<mcts::ucb::Rollout>() {
Ok(s) => s,
Err(e) => return Err(Box::new(e)),
};
let backprop = match scoring.score::<mcts::simulation::RandomSimulator>() {
Ok(b) => b,
Err(e) => return Err(Box::new(e)),
};
rollout = backprop
.backprop::<mcts::ucb::BestParentBackprop>()
.expand();
}
let (rng, view) = rollout.recover_components();
let root = view.find_node(state).unwrap();
let child_edge = match action_select {
ActionSelect::Ucb => {
match mcts::ucb::find_best_child(&view, root, settings.explore_bias, rng) {
Ok(child) => child,
Err(e) => return Err(Box::new(e)),
}
}
ActionSelect::VisitCount => find_most_visited_child(&view, root, rng),
};
// Because search graph de-duplication maps each set of equivalent game
// states to a single "canonical" game state, the state in the search graph
// that corresponds to `state` may not actually be the game state at `root`. As
// a result, actions on the root game state need to be mapped back into the
// set of actions on `state`.
let transposed_to_state = view.node_state(view.edge_target(child_edge));
for action in state.actions() {
let mut actual_to_state = state.clone();
actual_to_state.do_action(&action);
if actual_to_state == *transposed_to_state {
return Ok(action);
}
}
unreachable!()
})
}
} | 'id, | random_line_split |
mcts.rs | use crate::actions::Action;
use crate::Role;
use mcts::{statistics, SearchSettings};
use rand::Rng;
use search_graph;
use std::{cmp, mem};
#[derive(Clone, Debug)]
pub struct Game {}
impl statistics::two_player::PlayerMapping for Role {
fn player_one() -> Self {
Role::Dwarf
}
fn player_two() -> Self {
Role::Troll
}
fn resolve_player(&self) -> statistics::two_player::Player {
match *self {
Role::Dwarf => statistics::two_player::Player::One,
Role::Troll => statistics::two_player::Player::Two,
}
}
}
impl mcts::game::State for crate::state::State {
type Action = Action;
type PlayerId = Role;
fn active_player(&self) -> &Role {
&self.active_role()
}
fn actions<'s>(&'s self) -> Box<dyn Iterator<Item = Action> +'s> {
Box::new(self.actions())
}
fn do_action(&mut self, action: &Action) {
self.do_action(action);
}
}
impl mcts::game::Game for Game {
type Action = Action;
type PlayerId = Role;
type Payoff = statistics::two_player::ScoredPayoff;
type State = crate::state::State;
type Statistics = statistics::two_player::ScoredStatistics<Role>;
fn payoff_of(state: &Self::State) -> Option<Self::Payoff> {
if state.terminated() {
Some(statistics::two_player::ScoredPayoff {
visits: 1,
score_one: state.score(Role::Dwarf) as u32,
score_two: state.score(Role::Troll) as u32,
})
} else {
None
}
}
}
/// Controls how a game action is selected by the [MCTS
/// agent](struct.Agent.html) after MCTS search has terminated and all
/// statistics have been gathered.
#[derive(Debug, Clone, Copy)]
pub enum ActionSelect {
/// Select the action that was visited the most times.
VisitCount,
/// Select the action with the best UCB score.
Ucb,
}
/// Controls how graph compaction is done by the [MCTS agent](struct.Agent.html)
/// before each round of MCTS search.
#[derive(Debug, Clone, Copy)]
pub enum GraphCompact {
/// Prune the search graph so that the current game state and all its
/// descendants are retained, but game states that are not reachable from the
/// current game state are removed.
Prune,
/// Clear the entire search graph.
Clear,
/// Retain the entire contents of the search graph.
Retain,
}
type SearchGraph =
search_graph::Graph<crate::state::State, mcts::graph::VertexData, mcts::graph::EdgeData<Game>>;
pub struct Agent<R: Rng> {
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
graph: SearchGraph,
}
impl<R: Rng> Agent<R> {
pub fn new(
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
) -> Self {
Agent {
settings,
iterations,
rng,
action_select,
graph_compact,
graph: SearchGraph::new(),
}
}
}
fn find_most_visited_child<'a, 'id, R: Rng>(
view: &search_graph::view::View<
'a,
'id,
crate::state::State,
mcts::graph::VertexData,
mcts::graph::EdgeData<Game>,
>,
root: search_graph::view::NodeRef<'id>,
mut rng: R,
) -> search_graph::view::EdgeRef<'id> {
let mut children = view.children(root);
let mut best_child = children.next().unwrap();
let mut best_child_visits = view[best_child].statistics.visits();
let mut reservoir_count = 1u32;
for child in children {
let visits = view[child].statistics.visits();
match visits.cmp(&best_child_visits) {
cmp::Ordering::Less => continue,
cmp::Ordering::Equal => {
reservoir_count += 1;
if!rng.gen_bool(1.0f64 / (reservoir_count as f64)) {
continue;
}
}
cmp::Ordering::Greater => reservoir_count = 1,
}
best_child = child;
best_child_visits = visits;
}
best_child
}
impl<R: Rng + Send> crate::agent::Agent for Agent<R> {
fn propose_action(&mut self, state: &crate::state::State) -> crate::agent::Result | self.settings.clone(),
self.iterations,
self.action_select,
);
search_graph::view::of_graph(graph, |view| -> crate::agent::Result {
let mut rollout = mcts::RolloutPhase::initialize(rng, settings, state.clone(), view);
for _ in 0..iterations {
let scoring = match rollout.rollout::<mcts::ucb::Rollout>() {
Ok(s) => s,
Err(e) => return Err(Box::new(e)),
};
let backprop = match scoring.score::<mcts::simulation::RandomSimulator>() {
Ok(b) => b,
Err(e) => return Err(Box::new(e)),
};
rollout = backprop
.backprop::<mcts::ucb::BestParentBackprop>()
.expand();
}
let (rng, view) = rollout.recover_components();
let root = view.find_node(state).unwrap();
let child_edge = match action_select {
ActionSelect::Ucb => {
match mcts::ucb::find_best_child(&view, root, settings.explore_bias, rng) {
Ok(child) => child,
Err(e) => return Err(Box::new(e)),
}
}
ActionSelect::VisitCount => find_most_visited_child(&view, root, rng),
};
// Because search graph de-duplication maps each set of equivalent game
// states to a single "canonical" game state, the state in the search graph
// that corresponds to `state` may not actually be the game state at `root`. As
// a result, actions on the root game state need to be mapped back into the
// set of actions on `state`.
let transposed_to_state = view.node_state(view.edge_target(child_edge));
for action in state.actions() {
let mut actual_to_state = state.clone();
actual_to_state.do_action(&action);
if actual_to_state == *transposed_to_state {
return Ok(action);
}
}
unreachable!()
})
}
}
| {
match self.graph_compact {
GraphCompact::Prune => {
if let Some(node) = self.graph.find_node_mut(state) {
search_graph::view::of_node(node, |view, node| {
view.retain_reachable_from(Some(node).into_iter());
});
} else {
mem::swap(&mut self.graph, &mut SearchGraph::new());
}
}
GraphCompact::Clear => mem::swap(&mut self.graph, &mut SearchGraph::new()),
GraphCompact::Retain => (),
}
// Borrow/copy stuff out of self because the closure passed to of_graph
// can't borrow self.
let (rng, graph, settings, iterations, action_select) = (
&mut self.rng,
&mut self.graph, | identifier_body |
mcts.rs | use crate::actions::Action;
use crate::Role;
use mcts::{statistics, SearchSettings};
use rand::Rng;
use search_graph;
use std::{cmp, mem};
#[derive(Clone, Debug)]
pub struct Game {}
impl statistics::two_player::PlayerMapping for Role {
fn | () -> Self {
Role::Dwarf
}
fn player_two() -> Self {
Role::Troll
}
fn resolve_player(&self) -> statistics::two_player::Player {
match *self {
Role::Dwarf => statistics::two_player::Player::One,
Role::Troll => statistics::two_player::Player::Two,
}
}
}
impl mcts::game::State for crate::state::State {
type Action = Action;
type PlayerId = Role;
fn active_player(&self) -> &Role {
&self.active_role()
}
fn actions<'s>(&'s self) -> Box<dyn Iterator<Item = Action> +'s> {
Box::new(self.actions())
}
fn do_action(&mut self, action: &Action) {
self.do_action(action);
}
}
impl mcts::game::Game for Game {
type Action = Action;
type PlayerId = Role;
type Payoff = statistics::two_player::ScoredPayoff;
type State = crate::state::State;
type Statistics = statistics::two_player::ScoredStatistics<Role>;
fn payoff_of(state: &Self::State) -> Option<Self::Payoff> {
if state.terminated() {
Some(statistics::two_player::ScoredPayoff {
visits: 1,
score_one: state.score(Role::Dwarf) as u32,
score_two: state.score(Role::Troll) as u32,
})
} else {
None
}
}
}
/// Controls how a game action is selected by the [MCTS
/// agent](struct.Agent.html) after MCTS search has terminated and all
/// statistics have been gathered.
#[derive(Debug, Clone, Copy)]
pub enum ActionSelect {
/// Select the action that was visited the most times.
VisitCount,
/// Select the action with the best UCB score.
Ucb,
}
/// Controls how graph compaction is done by the [MCTS agent](struct.Agent.html)
/// before each round of MCTS search.
#[derive(Debug, Clone, Copy)]
pub enum GraphCompact {
/// Prune the search graph so that the current game state and all its
/// descendants are retained, but game states that are not reachable from the
/// current game state are removed.
Prune,
/// Clear the entire search graph.
Clear,
/// Retain the entire contents of the search graph.
Retain,
}
type SearchGraph =
search_graph::Graph<crate::state::State, mcts::graph::VertexData, mcts::graph::EdgeData<Game>>;
pub struct Agent<R: Rng> {
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
graph: SearchGraph,
}
impl<R: Rng> Agent<R> {
pub fn new(
settings: SearchSettings,
iterations: u32,
rng: R,
action_select: ActionSelect,
graph_compact: GraphCompact,
) -> Self {
Agent {
settings,
iterations,
rng,
action_select,
graph_compact,
graph: SearchGraph::new(),
}
}
}
fn find_most_visited_child<'a, 'id, R: Rng>(
view: &search_graph::view::View<
'a,
'id,
crate::state::State,
mcts::graph::VertexData,
mcts::graph::EdgeData<Game>,
>,
root: search_graph::view::NodeRef<'id>,
mut rng: R,
) -> search_graph::view::EdgeRef<'id> {
let mut children = view.children(root);
let mut best_child = children.next().unwrap();
let mut best_child_visits = view[best_child].statistics.visits();
let mut reservoir_count = 1u32;
for child in children {
let visits = view[child].statistics.visits();
match visits.cmp(&best_child_visits) {
cmp::Ordering::Less => continue,
cmp::Ordering::Equal => {
reservoir_count += 1;
if!rng.gen_bool(1.0f64 / (reservoir_count as f64)) {
continue;
}
}
cmp::Ordering::Greater => reservoir_count = 1,
}
best_child = child;
best_child_visits = visits;
}
best_child
}
impl<R: Rng + Send> crate::agent::Agent for Agent<R> {
fn propose_action(&mut self, state: &crate::state::State) -> crate::agent::Result {
match self.graph_compact {
GraphCompact::Prune => {
if let Some(node) = self.graph.find_node_mut(state) {
search_graph::view::of_node(node, |view, node| {
view.retain_reachable_from(Some(node).into_iter());
});
} else {
mem::swap(&mut self.graph, &mut SearchGraph::new());
}
}
GraphCompact::Clear => mem::swap(&mut self.graph, &mut SearchGraph::new()),
GraphCompact::Retain => (),
}
// Borrow/copy stuff out of self because the closure passed to of_graph
// can't borrow self.
let (rng, graph, settings, iterations, action_select) = (
&mut self.rng,
&mut self.graph,
self.settings.clone(),
self.iterations,
self.action_select,
);
search_graph::view::of_graph(graph, |view| -> crate::agent::Result {
let mut rollout = mcts::RolloutPhase::initialize(rng, settings, state.clone(), view);
for _ in 0..iterations {
let scoring = match rollout.rollout::<mcts::ucb::Rollout>() {
Ok(s) => s,
Err(e) => return Err(Box::new(e)),
};
let backprop = match scoring.score::<mcts::simulation::RandomSimulator>() {
Ok(b) => b,
Err(e) => return Err(Box::new(e)),
};
rollout = backprop
.backprop::<mcts::ucb::BestParentBackprop>()
.expand();
}
let (rng, view) = rollout.recover_components();
let root = view.find_node(state).unwrap();
let child_edge = match action_select {
ActionSelect::Ucb => {
match mcts::ucb::find_best_child(&view, root, settings.explore_bias, rng) {
Ok(child) => child,
Err(e) => return Err(Box::new(e)),
}
}
ActionSelect::VisitCount => find_most_visited_child(&view, root, rng),
};
// Because search graph de-duplication maps each set of equivalent game
// states to a single "canonical" game state, the state in the search graph
// that corresponds to `state` may not actually be the game state at `root`. As
// a result, actions on the root game state need to be mapped back into the
// set of actions on `state`.
let transposed_to_state = view.node_state(view.edge_target(child_edge));
for action in state.actions() {
let mut actual_to_state = state.clone();
actual_to_state.do_action(&action);
if actual_to_state == *transposed_to_state {
return Ok(action);
}
}
unreachable!()
})
}
}
| player_one | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | #![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#![plugin(serde_macros)]
extern crate backtrace;
extern crate canvas;
extern crate canvas_traits;
extern crate compositing;
extern crate devtools_traits;
extern crate euclid;
#[cfg(not(target_os = "windows"))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate ipc_channel;
extern crate layers;
extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender_traits;
mod constellation;
mod pipeline;
#[cfg(not(target_os = "windows"))]
mod sandboxing;
mod timer_scheduler;
pub use constellation::{Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState};
pub use pipeline::UnprivilegedPipelineContent;
#[cfg(not(target_os = "windows"))]
pub use sandboxing::content_process_sandbox_profile; | * 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/. */
#![feature(box_syntax)] | random_line_split |
const-vec-of-fns.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-test
// FIXME: #7385: hits a codegen bug on OS X x86_64
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn f() |
static bare_fns: &'static [extern fn()] = &[f, f];
struct S<'self>(&'self fn());
static closures: &'static [S<'static>] = &[S(f), S(f)];
pub fn main() {
for &bare_fn in bare_fns.iter() { bare_fn() }
for &closure in closures.iter() { (*closure)() }
}
| { } | identifier_body |
const-vec-of-fns.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-test
// FIXME: #7385: hits a codegen bug on OS X x86_64
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn f() { }
static bare_fns: &'static [extern fn()] = &[f, f];
struct S<'self>(&'self fn());
static closures: &'static [S<'static>] = &[S(f), S(f)];
pub fn | () {
for &bare_fn in bare_fns.iter() { bare_fn() }
for &closure in closures.iter() { (*closure)() }
}
| main | identifier_name |
const-vec-of-fns.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | // FIXME: #7385: hits a codegen bug on OS X x86_64
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn f() { }
static bare_fns: &'static [extern fn()] = &[f, f];
struct S<'self>(&'self fn());
static closures: &'static [S<'static>] = &[S(f), S(f)];
pub fn main() {
for &bare_fn in bare_fns.iter() { bare_fn() }
for &closure in closures.iter() { (*closure)() }
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-test | random_line_split |
cfg.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/**
The compiler code necessary to support the cfg! extension, which
expands to a literal `true` or `false` based on whether the given cfgs
match the current compilation environment.
*/
use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use attr;
use attr::*;
use parse::attr::ParserAttr;
use parse::token::InternedString;
use parse::token;
pub fn expand_cfg(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> {
let mut p = cx.new_parser_from_tts(tts);
let mut cfgs = Vec::new();
// parse `cfg!(meta_item, meta_item(x,y), meta_item="foo",...)`
while p.token!= token::EOF {
cfgs.push(p.parse_meta_item());
if p.eat(&token::EOF) | // trailing comma is optional,.
p.expect(&token::COMMA);
}
// test_cfg searches for meta items looking like `cfg(foo,...)`
let in_cfg = &[cx.meta_list(sp, InternedString::new("cfg"), cfgs)];
let matches_cfg = attr::test_cfg(cx.cfg().as_slice(),
in_cfg.iter().map(|&x| x));
let e = cx.expr_bool(sp, matches_cfg);
MacExpr::new(e)
}
| { break } | conditional_block |
cfg.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/**
The compiler code necessary to support the cfg! extension, which
expands to a literal `true` or `false` based on whether the given cfgs
match the current compilation environment.
*/
use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use attr;
use attr::*;
use parse::attr::ParserAttr;
use parse::token::InternedString;
use parse::token;
pub fn | (cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> {
let mut p = cx.new_parser_from_tts(tts);
let mut cfgs = Vec::new();
// parse `cfg!(meta_item, meta_item(x,y), meta_item="foo",...)`
while p.token!= token::EOF {
cfgs.push(p.parse_meta_item());
if p.eat(&token::EOF) { break } // trailing comma is optional,.
p.expect(&token::COMMA);
}
// test_cfg searches for meta items looking like `cfg(foo,...)`
let in_cfg = &[cx.meta_list(sp, InternedString::new("cfg"), cfgs)];
let matches_cfg = attr::test_cfg(cx.cfg().as_slice(),
in_cfg.iter().map(|&x| x));
let e = cx.expr_bool(sp, matches_cfg);
MacExpr::new(e)
}
| expand_cfg | identifier_name |
cfg.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/**
The compiler code necessary to support the cfg! extension, which
expands to a literal `true` or `false` based on whether the given cfgs | use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use attr;
use attr::*;
use parse::attr::ParserAttr;
use parse::token::InternedString;
use parse::token;
pub fn expand_cfg(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> {
let mut p = cx.new_parser_from_tts(tts);
let mut cfgs = Vec::new();
// parse `cfg!(meta_item, meta_item(x,y), meta_item="foo",...)`
while p.token!= token::EOF {
cfgs.push(p.parse_meta_item());
if p.eat(&token::EOF) { break } // trailing comma is optional,.
p.expect(&token::COMMA);
}
// test_cfg searches for meta items looking like `cfg(foo,...)`
let in_cfg = &[cx.meta_list(sp, InternedString::new("cfg"), cfgs)];
let matches_cfg = attr::test_cfg(cx.cfg().as_slice(),
in_cfg.iter().map(|&x| x));
let e = cx.expr_bool(sp, matches_cfg);
MacExpr::new(e)
} | match the current compilation environment.
*/
| random_line_split |
cfg.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/**
The compiler code necessary to support the cfg! extension, which
expands to a literal `true` or `false` based on whether the given cfgs
match the current compilation environment.
*/
use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use attr;
use attr::*;
use parse::attr::ParserAttr;
use parse::token::InternedString;
use parse::token;
pub fn expand_cfg(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult> | {
let mut p = cx.new_parser_from_tts(tts);
let mut cfgs = Vec::new();
// parse `cfg!(meta_item, meta_item(x,y), meta_item="foo", ...)`
while p.token != token::EOF {
cfgs.push(p.parse_meta_item());
if p.eat(&token::EOF) { break } // trailing comma is optional,.
p.expect(&token::COMMA);
}
// test_cfg searches for meta items looking like `cfg(foo, ...)`
let in_cfg = &[cx.meta_list(sp, InternedString::new("cfg"), cfgs)];
let matches_cfg = attr::test_cfg(cx.cfg().as_slice(),
in_cfg.iter().map(|&x| x));
let e = cx.expr_bool(sp, matches_cfg);
MacExpr::new(e)
} | identifier_body |
|
main.rs | fn main() {
// var()
// control_flow()
let n = 45;
let big = fib(n);
println!("{}th fib: {}", n, big);
}
fn var() |
fn control_flow() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
let a = [1, 2, 3, 4, 5];
for e in a.iter() {
println!("I'm looping {}", e)
}
for number in (1..4).rev() {
println!("{}!", number)
}
println!("LIFTOFF!!!")
}
fn fib(n: u32) -> u32 {
if n == 0 {
1
} else if n == 1 {
1
} else if n == 2 {
2
} else {
fib(n - 1) + fib(n - 2)
}
}
| {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (_, y, _) = tup;
println!("The value of y is: {}", y);
println!("The value if x is: {}", tup.0);
} | identifier_body |
main.rs | fn main() {
// var()
// control_flow()
let n = 45;
let big = fib(n);
println!("{}th fib: {}", n, big);
}
fn var() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (_, y, _) = tup;
println!("The value of y is: {}", y);
println!("The value if x is: {}", tup.0);
}
fn control_flow() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
let a = [1, 2, 3, 4, 5];
for e in a.iter() {
println!("I'm looping {}", e)
}
for number in (1..4).rev() {
println!("{}!", number)
}
println!("LIFTOFF!!!")
}
fn | (n: u32) -> u32 {
if n == 0 {
1
} else if n == 1 {
1
} else if n == 2 {
2
} else {
fib(n - 1) + fib(n - 2)
}
}
| fib | identifier_name |
main.rs | fn main() {
// var()
// control_flow()
let n = 45;
let big = fib(n);
println!("{}th fib: {}", n, big);
}
fn var() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (_, y, _) = tup; |
fn control_flow() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
let a = [1, 2, 3, 4, 5];
for e in a.iter() {
println!("I'm looping {}", e)
}
for number in (1..4).rev() {
println!("{}!", number)
}
println!("LIFTOFF!!!")
}
fn fib(n: u32) -> u32 {
if n == 0 {
1
} else if n == 1 {
1
} else if n == 2 {
2
} else {
fib(n - 1) + fib(n - 2)
}
} | println!("The value of y is: {}", y);
println!("The value if x is: {}", tup.0);
} | random_line_split |
main.rs | fn main() {
// var()
// control_flow()
let n = 45;
let big = fib(n);
println!("{}th fib: {}", n, big);
}
fn var() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (_, y, _) = tup;
println!("The value of y is: {}", y);
println!("The value if x is: {}", tup.0);
}
fn control_flow() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
let a = [1, 2, 3, 4, 5];
for e in a.iter() {
println!("I'm looping {}", e)
}
for number in (1..4).rev() {
println!("{}!", number)
}
println!("LIFTOFF!!!")
}
fn fib(n: u32) -> u32 {
if n == 0 {
1
} else if n == 1 {
1
} else if n == 2 | else {
fib(n - 1) + fib(n - 2)
}
}
| {
2
} | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use fbinit::FacebookInit;
use futures_stats::{FutureStats, StreamStats};
use metadata::Metadata;
use nonzero_ext::nonzero;
pub use observability::ScubaVerbosityLevel;
use observability::{ObservabilityContext, ScubaLoggingDecisionFields};
use permission_checker::MononokeIdentitySetExt;
use scuba::{builder::ServerData, ScubaSample, ScubaSampleBuilder};
pub use scuba::{Sampling, ScubaValue};
use std::collections::hash_map::Entry;
use std::io::Error as IoError;
use std::num::NonZeroU64;
use std::path::Path;
use std::time::Duration;
use time_ext::DurationExt;
use tunables::tunables;
pub use scribe_ext::ScribeClientImplementation;
/// An extensible wrapper struct around `ScubaSampleBuilder`
#[derive(Clone)]
pub struct MononokeScubaSampleBuilder {
inner: ScubaSampleBuilder,
maybe_observability_context: Option<ObservabilityContext>,
// This field decides if sampled out requests should
// still be logged when verbose logging is enabled
fallback_sampled_out_to_verbose: bool,
}
impl std::fmt::Debug for MononokeScubaSampleBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MononokeScubaSampleBuilder({:?})", self.inner)
}
}
impl MononokeScubaSampleBuilder {
pub fn new(fb: FacebookInit, scuba_table: &str) -> Self {
Self {
inner: ScubaSampleBuilder::new(fb, scuba_table),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_discard() -> Self {
Self {
inner: ScubaSampleBuilder::with_discard(),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_opt_table(fb: FacebookInit, scuba_table: Option<String>) -> Self {
match scuba_table {
None => Self::with_discard(),
Some(scuba_table) => Self::new(fb, &scuba_table),
}
}
pub fn with_observability_context(self, octx: ObservabilityContext) -> Self {
Self {
maybe_observability_context: Some(octx),
..self
}
}
fn get_logging_decision_fields(&self) -> ScubaLoggingDecisionFields {
ScubaLoggingDecisionFields {
maybe_session_id: self.get("session_uuid"),
maybe_unix_username: self.get("unix_username"),
maybe_source_hostname: self.get("source_hostname"),
}
}
pub fn should_log_with_level(&self, level: ScubaVerbosityLevel) -> bool {
match level {
ScubaVerbosityLevel::Normal => true,
ScubaVerbosityLevel::Verbose => self
.maybe_observability_context
.as_ref()
.map_or(false, |octx| {
octx.should_log_scuba_sample(level, self.get_logging_decision_fields())
}),
}
}
pub fn add<K: Into<String>, V: Into<ScubaValue>>(&mut self, key: K, value: V) -> &mut Self {
self.inner.add(key, value);
self
}
pub fn add_metadata(&mut self, metadata: &Metadata) -> &mut Self {
self.inner
.add("session_uuid", metadata.session_id().to_string());
self.inner.add(
"client_identities",
metadata
.identities()
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>(),
);
if let Some(client_hostname) = metadata.client_hostname() {
// "source_hostname" to remain compatible with historical logging
self.inner
.add("source_hostname", client_hostname.to_owned());
} else {
if let Some(client_ip) = metadata.client_ip() {
self.inner.add("client_ip", client_ip.to_string());
}
}
if let Some(unix_name) = metadata.unix_name() {
// "unix_username" to remain compatible with historical logging
self.inner.add("unix_username", unix_name);
}
self.inner
.add_opt("sandcastle_alias", metadata.sandcastle_alias());
self.inner
.add_opt("sandcastle_nonce", metadata.sandcastle_nonce());
self.inner
.add_opt("clientinfo_tag", metadata.clientinfo_u64tag());
self
}
pub fn sample_for_identities(&mut self, identities: &impl MononokeIdentitySetExt) {
// Details of quicksand traffic aren't particularly interesting because all Quicksand tasks are
// doing effectively the same thing at the same time. If we need real-time debugging, we can
// always rely on updating the verbosity in real time.
if identities.is_quicksand() {
self.sampled_unless_verbose(nonzero!(100u64));
}
}
pub fn log_with_msg<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if self.fallback_sampled_out_to_verbose
&& self.should_log_with_level(ScubaVerbosityLevel::Verbose)
{
// We need to unsample before we log, so that
// `sample_rate` field is not added, as we are about
// to log everything.
self.inner.unsampled();
}
self.inner.add("log_tag", log_tag);
if let Some(mut msg) = msg.into() {
match tunables().get_max_scuba_msg_length().try_into() {
Ok(size) if size > 0 && msg.len() > size => {
msg.truncate(size);
msg.push_str(" (...)");
}
_ => {}
};
self.inner.add("msg", msg);
}
self.inner.log();
}
/// Same as `log_with_msg`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_with_msg_verbose<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
return;
}
self.log_with_msg(log_tag, msg)
}
pub fn add_stream_stats(&mut self, stats: &StreamStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add("count", stats.count)
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn add_future_stats(&mut self, stats: &FutureStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn is_discard(&self) -> bool {
self.inner.is_discard()
}
pub fn sampled(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = false;
self.inner.sampled(sample_rate);
self
}
pub fn sampled_unless_verbose(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = true;
self.inner.sampled(sample_rate);
self
}
pub fn unsampled(&mut self) -> &mut Self {
self.inner.unsampled();
self
}
pub fn log(&mut self) -> bool {
self.inner.log()
}
/// Same as `log`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_verbose(&mut self) -> bool {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
// Return value of the `log` function indicates whether
// the sample passed sampling. If it's too verbose, let's
// return false
return false;
}
self.log()
}
pub fn add_common_server_data(&mut self) -> &mut Self {
self.inner.add_common_server_data();
self
}
pub fn sampling(&self) -> &Sampling {
self.inner.sampling()
}
pub fn add_mapped_common_server_data<F>(&mut self, mapper: F) -> &mut Self
where
F: Fn(ServerData) -> &'static str,
{
self.inner.add_mapped_common_server_data(mapper);
self
}
pub fn with_log_file<L: AsRef<Path>>(mut self, log_file: L) -> Result<Self, IoError> {
self.inner = self.inner.with_log_file(log_file)?;
Ok(self)
}
pub fn with_seq(mut self, key: impl Into<String>) -> Self {
self.inner = self.inner.with_seq(key);
self
}
pub fn log_with_time(&mut self, time: u64) -> bool {
self.inner.log_with_time(time)
}
pub fn | <K: Into<String>>(&mut self, key: K) -> Entry<String, ScubaValue> {
self.inner.entry(key)
}
pub fn flush(&self, timeout: Duration) {
self.inner.flush(timeout)
}
pub fn get_sample(&self) -> &ScubaSample {
self.inner.get_sample()
}
pub fn add_opt<K: Into<String>, V: Into<ScubaValue>>(
&mut self,
key: K,
value: Option<V>,
) -> &mut Self {
self.inner.add_opt(key, value);
self
}
pub fn get<K: Into<String>>(&self, key: K) -> Option<&ScubaValue> {
self.inner.get(key)
}
}
| entry | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use fbinit::FacebookInit;
use futures_stats::{FutureStats, StreamStats};
use metadata::Metadata;
use nonzero_ext::nonzero;
pub use observability::ScubaVerbosityLevel;
use observability::{ObservabilityContext, ScubaLoggingDecisionFields};
use permission_checker::MononokeIdentitySetExt;
use scuba::{builder::ServerData, ScubaSample, ScubaSampleBuilder};
pub use scuba::{Sampling, ScubaValue};
use std::collections::hash_map::Entry;
use std::io::Error as IoError;
use std::num::NonZeroU64;
use std::path::Path;
use std::time::Duration;
use time_ext::DurationExt;
use tunables::tunables;
pub use scribe_ext::ScribeClientImplementation;
/// An extensible wrapper struct around `ScubaSampleBuilder`
#[derive(Clone)]
pub struct MononokeScubaSampleBuilder {
inner: ScubaSampleBuilder,
maybe_observability_context: Option<ObservabilityContext>,
// This field decides if sampled out requests should
// still be logged when verbose logging is enabled
fallback_sampled_out_to_verbose: bool,
}
impl std::fmt::Debug for MononokeScubaSampleBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MononokeScubaSampleBuilder({:?})", self.inner)
}
}
impl MononokeScubaSampleBuilder {
pub fn new(fb: FacebookInit, scuba_table: &str) -> Self {
Self {
inner: ScubaSampleBuilder::new(fb, scuba_table),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_discard() -> Self {
Self {
inner: ScubaSampleBuilder::with_discard(),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_opt_table(fb: FacebookInit, scuba_table: Option<String>) -> Self {
match scuba_table {
None => Self::with_discard(),
Some(scuba_table) => Self::new(fb, &scuba_table),
}
}
pub fn with_observability_context(self, octx: ObservabilityContext) -> Self {
Self {
maybe_observability_context: Some(octx),
..self
}
}
fn get_logging_decision_fields(&self) -> ScubaLoggingDecisionFields {
ScubaLoggingDecisionFields {
maybe_session_id: self.get("session_uuid"),
maybe_unix_username: self.get("unix_username"),
maybe_source_hostname: self.get("source_hostname"),
}
}
pub fn should_log_with_level(&self, level: ScubaVerbosityLevel) -> bool {
match level {
ScubaVerbosityLevel::Normal => true,
ScubaVerbosityLevel::Verbose => self
.maybe_observability_context
.as_ref()
.map_or(false, |octx| {
octx.should_log_scuba_sample(level, self.get_logging_decision_fields())
}),
}
}
pub fn add<K: Into<String>, V: Into<ScubaValue>>(&mut self, key: K, value: V) -> &mut Self {
self.inner.add(key, value);
self
}
pub fn add_metadata(&mut self, metadata: &Metadata) -> &mut Self {
self.inner
.add("session_uuid", metadata.session_id().to_string());
self.inner.add(
"client_identities",
metadata
.identities()
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>(),
);
if let Some(client_hostname) = metadata.client_hostname() {
// "source_hostname" to remain compatible with historical logging
self.inner
.add("source_hostname", client_hostname.to_owned());
} else {
if let Some(client_ip) = metadata.client_ip() {
self.inner.add("client_ip", client_ip.to_string());
}
}
if let Some(unix_name) = metadata.unix_name() {
// "unix_username" to remain compatible with historical logging
self.inner.add("unix_username", unix_name);
}
self.inner
.add_opt("sandcastle_alias", metadata.sandcastle_alias());
self.inner
.add_opt("sandcastle_nonce", metadata.sandcastle_nonce());
self.inner
.add_opt("clientinfo_tag", metadata.clientinfo_u64tag());
self
}
pub fn sample_for_identities(&mut self, identities: &impl MononokeIdentitySetExt) {
// Details of quicksand traffic aren't particularly interesting because all Quicksand tasks are
// doing effectively the same thing at the same time. If we need real-time debugging, we can
// always rely on updating the verbosity in real time.
if identities.is_quicksand() {
self.sampled_unless_verbose(nonzero!(100u64));
}
}
pub fn log_with_msg<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if self.fallback_sampled_out_to_verbose
&& self.should_log_with_level(ScubaVerbosityLevel::Verbose)
{
// We need to unsample before we log, so that
// `sample_rate` field is not added, as we are about
// to log everything.
self.inner.unsampled();
}
self.inner.add("log_tag", log_tag);
if let Some(mut msg) = msg.into() {
match tunables().get_max_scuba_msg_length().try_into() {
Ok(size) if size > 0 && msg.len() > size => {
msg.truncate(size);
msg.push_str(" (...)");
}
_ => {}
};
self.inner.add("msg", msg);
}
self.inner.log();
}
/// Same as `log_with_msg`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_with_msg_verbose<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
return;
}
self.log_with_msg(log_tag, msg)
}
pub fn add_stream_stats(&mut self, stats: &StreamStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add("count", stats.count)
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn add_future_stats(&mut self, stats: &FutureStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn is_discard(&self) -> bool {
self.inner.is_discard()
}
pub fn sampled(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = false;
self.inner.sampled(sample_rate);
self
}
pub fn sampled_unless_verbose(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = true;
self.inner.sampled(sample_rate);
self
}
pub fn unsampled(&mut self) -> &mut Self {
self.inner.unsampled();
self
}
pub fn log(&mut self) -> bool {
self.inner.log()
}
/// Same as `log`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_verbose(&mut self) -> bool {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) |
self.log()
}
pub fn add_common_server_data(&mut self) -> &mut Self {
self.inner.add_common_server_data();
self
}
pub fn sampling(&self) -> &Sampling {
self.inner.sampling()
}
pub fn add_mapped_common_server_data<F>(&mut self, mapper: F) -> &mut Self
where
F: Fn(ServerData) -> &'static str,
{
self.inner.add_mapped_common_server_data(mapper);
self
}
pub fn with_log_file<L: AsRef<Path>>(mut self, log_file: L) -> Result<Self, IoError> {
self.inner = self.inner.with_log_file(log_file)?;
Ok(self)
}
pub fn with_seq(mut self, key: impl Into<String>) -> Self {
self.inner = self.inner.with_seq(key);
self
}
pub fn log_with_time(&mut self, time: u64) -> bool {
self.inner.log_with_time(time)
}
pub fn entry<K: Into<String>>(&mut self, key: K) -> Entry<String, ScubaValue> {
self.inner.entry(key)
}
pub fn flush(&self, timeout: Duration) {
self.inner.flush(timeout)
}
pub fn get_sample(&self) -> &ScubaSample {
self.inner.get_sample()
}
pub fn add_opt<K: Into<String>, V: Into<ScubaValue>>(
&mut self,
key: K,
value: Option<V>,
) -> &mut Self {
self.inner.add_opt(key, value);
self
}
pub fn get<K: Into<String>>(&self, key: K) -> Option<&ScubaValue> {
self.inner.get(key)
}
}
| {
// Return value of the `log` function indicates whether
// the sample passed sampling. If it's too verbose, let's
// return false
return false;
} | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use fbinit::FacebookInit;
use futures_stats::{FutureStats, StreamStats};
use metadata::Metadata;
use nonzero_ext::nonzero;
pub use observability::ScubaVerbosityLevel;
use observability::{ObservabilityContext, ScubaLoggingDecisionFields};
use permission_checker::MononokeIdentitySetExt;
use scuba::{builder::ServerData, ScubaSample, ScubaSampleBuilder};
pub use scuba::{Sampling, ScubaValue};
use std::collections::hash_map::Entry;
use std::io::Error as IoError;
use std::num::NonZeroU64;
use std::path::Path;
use std::time::Duration;
use time_ext::DurationExt;
use tunables::tunables;
pub use scribe_ext::ScribeClientImplementation;
/// An extensible wrapper struct around `ScubaSampleBuilder`
#[derive(Clone)]
pub struct MononokeScubaSampleBuilder {
inner: ScubaSampleBuilder,
maybe_observability_context: Option<ObservabilityContext>,
// This field decides if sampled out requests should
// still be logged when verbose logging is enabled
fallback_sampled_out_to_verbose: bool,
}
impl std::fmt::Debug for MononokeScubaSampleBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MononokeScubaSampleBuilder({:?})", self.inner)
}
}
impl MononokeScubaSampleBuilder {
pub fn new(fb: FacebookInit, scuba_table: &str) -> Self {
Self {
inner: ScubaSampleBuilder::new(fb, scuba_table),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_discard() -> Self {
Self {
inner: ScubaSampleBuilder::with_discard(),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_opt_table(fb: FacebookInit, scuba_table: Option<String>) -> Self {
match scuba_table {
None => Self::with_discard(),
Some(scuba_table) => Self::new(fb, &scuba_table),
}
}
pub fn with_observability_context(self, octx: ObservabilityContext) -> Self {
Self {
maybe_observability_context: Some(octx),
..self
}
}
fn get_logging_decision_fields(&self) -> ScubaLoggingDecisionFields {
ScubaLoggingDecisionFields {
maybe_session_id: self.get("session_uuid"),
maybe_unix_username: self.get("unix_username"),
maybe_source_hostname: self.get("source_hostname"),
}
}
pub fn should_log_with_level(&self, level: ScubaVerbosityLevel) -> bool {
match level {
ScubaVerbosityLevel::Normal => true,
ScubaVerbosityLevel::Verbose => self
.maybe_observability_context
.as_ref()
.map_or(false, |octx| {
octx.should_log_scuba_sample(level, self.get_logging_decision_fields())
}),
}
}
pub fn add<K: Into<String>, V: Into<ScubaValue>>(&mut self, key: K, value: V) -> &mut Self {
self.inner.add(key, value);
self
}
pub fn add_metadata(&mut self, metadata: &Metadata) -> &mut Self {
self.inner
.add("session_uuid", metadata.session_id().to_string());
self.inner.add(
"client_identities",
metadata
.identities()
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>(),
);
if let Some(client_hostname) = metadata.client_hostname() {
// "source_hostname" to remain compatible with historical logging
self.inner
.add("source_hostname", client_hostname.to_owned());
} else {
if let Some(client_ip) = metadata.client_ip() {
self.inner.add("client_ip", client_ip.to_string());
}
}
if let Some(unix_name) = metadata.unix_name() {
// "unix_username" to remain compatible with historical logging
self.inner.add("unix_username", unix_name);
}
self.inner
.add_opt("sandcastle_alias", metadata.sandcastle_alias());
self.inner
.add_opt("sandcastle_nonce", metadata.sandcastle_nonce());
self.inner
.add_opt("clientinfo_tag", metadata.clientinfo_u64tag());
self
}
pub fn sample_for_identities(&mut self, identities: &impl MononokeIdentitySetExt) {
// Details of quicksand traffic aren't particularly interesting because all Quicksand tasks are
// doing effectively the same thing at the same time. If we need real-time debugging, we can
// always rely on updating the verbosity in real time.
if identities.is_quicksand() {
self.sampled_unless_verbose(nonzero!(100u64));
}
}
pub fn log_with_msg<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if self.fallback_sampled_out_to_verbose
&& self.should_log_with_level(ScubaVerbosityLevel::Verbose)
{
// We need to unsample before we log, so that
// `sample_rate` field is not added, as we are about
// to log everything.
self.inner.unsampled();
}
self.inner.add("log_tag", log_tag);
if let Some(mut msg) = msg.into() {
match tunables().get_max_scuba_msg_length().try_into() {
Ok(size) if size > 0 && msg.len() > size => {
msg.truncate(size);
msg.push_str(" (...)");
}
_ => {}
};
self.inner.add("msg", msg);
}
self.inner.log();
}
/// Same as `log_with_msg`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_with_msg_verbose<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) |
pub fn add_stream_stats(&mut self, stats: &StreamStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add("count", stats.count)
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn add_future_stats(&mut self, stats: &FutureStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn is_discard(&self) -> bool {
self.inner.is_discard()
}
pub fn sampled(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = false;
self.inner.sampled(sample_rate);
self
}
pub fn sampled_unless_verbose(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = true;
self.inner.sampled(sample_rate);
self
}
pub fn unsampled(&mut self) -> &mut Self {
self.inner.unsampled();
self
}
pub fn log(&mut self) -> bool {
self.inner.log()
}
/// Same as `log`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_verbose(&mut self) -> bool {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
// Return value of the `log` function indicates whether
// the sample passed sampling. If it's too verbose, let's
// return false
return false;
}
self.log()
}
pub fn add_common_server_data(&mut self) -> &mut Self {
self.inner.add_common_server_data();
self
}
pub fn sampling(&self) -> &Sampling {
self.inner.sampling()
}
pub fn add_mapped_common_server_data<F>(&mut self, mapper: F) -> &mut Self
where
F: Fn(ServerData) -> &'static str,
{
self.inner.add_mapped_common_server_data(mapper);
self
}
pub fn with_log_file<L: AsRef<Path>>(mut self, log_file: L) -> Result<Self, IoError> {
self.inner = self.inner.with_log_file(log_file)?;
Ok(self)
}
pub fn with_seq(mut self, key: impl Into<String>) -> Self {
self.inner = self.inner.with_seq(key);
self
}
pub fn log_with_time(&mut self, time: u64) -> bool {
self.inner.log_with_time(time)
}
pub fn entry<K: Into<String>>(&mut self, key: K) -> Entry<String, ScubaValue> {
self.inner.entry(key)
}
pub fn flush(&self, timeout: Duration) {
self.inner.flush(timeout)
}
pub fn get_sample(&self) -> &ScubaSample {
self.inner.get_sample()
}
pub fn add_opt<K: Into<String>, V: Into<ScubaValue>>(
&mut self,
key: K,
value: Option<V>,
) -> &mut Self {
self.inner.add_opt(key, value);
self
}
pub fn get<K: Into<String>>(&self, key: K) -> Option<&ScubaValue> {
self.inner.get(key)
}
}
| {
if !self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
return;
}
self.log_with_msg(log_tag, msg)
} | identifier_body |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
use fbinit::FacebookInit;
use futures_stats::{FutureStats, StreamStats};
use metadata::Metadata;
use nonzero_ext::nonzero;
pub use observability::ScubaVerbosityLevel;
use observability::{ObservabilityContext, ScubaLoggingDecisionFields};
use permission_checker::MononokeIdentitySetExt;
use scuba::{builder::ServerData, ScubaSample, ScubaSampleBuilder};
pub use scuba::{Sampling, ScubaValue};
use std::collections::hash_map::Entry;
use std::io::Error as IoError;
use std::num::NonZeroU64;
use std::path::Path;
use std::time::Duration;
use time_ext::DurationExt;
use tunables::tunables;
pub use scribe_ext::ScribeClientImplementation;
/// An extensible wrapper struct around `ScubaSampleBuilder`
#[derive(Clone)]
pub struct MononokeScubaSampleBuilder {
inner: ScubaSampleBuilder,
maybe_observability_context: Option<ObservabilityContext>,
// This field decides if sampled out requests should
// still be logged when verbose logging is enabled
fallback_sampled_out_to_verbose: bool,
}
impl std::fmt::Debug for MononokeScubaSampleBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "MononokeScubaSampleBuilder({:?})", self.inner)
}
}
impl MononokeScubaSampleBuilder {
pub fn new(fb: FacebookInit, scuba_table: &str) -> Self {
Self {
inner: ScubaSampleBuilder::new(fb, scuba_table),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_discard() -> Self {
Self {
inner: ScubaSampleBuilder::with_discard(),
maybe_observability_context: None,
fallback_sampled_out_to_verbose: false,
}
}
pub fn with_opt_table(fb: FacebookInit, scuba_table: Option<String>) -> Self {
match scuba_table {
None => Self::with_discard(),
Some(scuba_table) => Self::new(fb, &scuba_table),
}
}
pub fn with_observability_context(self, octx: ObservabilityContext) -> Self {
Self {
maybe_observability_context: Some(octx),
..self
}
}
fn get_logging_decision_fields(&self) -> ScubaLoggingDecisionFields {
ScubaLoggingDecisionFields {
maybe_session_id: self.get("session_uuid"),
maybe_unix_username: self.get("unix_username"),
maybe_source_hostname: self.get("source_hostname"),
}
}
pub fn should_log_with_level(&self, level: ScubaVerbosityLevel) -> bool {
match level {
ScubaVerbosityLevel::Normal => true,
ScubaVerbosityLevel::Verbose => self
.maybe_observability_context
.as_ref()
.map_or(false, |octx| {
octx.should_log_scuba_sample(level, self.get_logging_decision_fields())
}),
}
}
pub fn add<K: Into<String>, V: Into<ScubaValue>>(&mut self, key: K, value: V) -> &mut Self {
self.inner.add(key, value);
self
}
pub fn add_metadata(&mut self, metadata: &Metadata) -> &mut Self {
self.inner
.add("session_uuid", metadata.session_id().to_string());
self.inner.add(
"client_identities",
metadata
.identities()
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>(),
);
if let Some(client_hostname) = metadata.client_hostname() {
// "source_hostname" to remain compatible with historical logging
self.inner
.add("source_hostname", client_hostname.to_owned());
} else {
if let Some(client_ip) = metadata.client_ip() {
self.inner.add("client_ip", client_ip.to_string());
}
}
if let Some(unix_name) = metadata.unix_name() {
// "unix_username" to remain compatible with historical logging
self.inner.add("unix_username", unix_name);
}
self.inner
.add_opt("sandcastle_alias", metadata.sandcastle_alias());
self.inner
.add_opt("sandcastle_nonce", metadata.sandcastle_nonce());
self.inner
.add_opt("clientinfo_tag", metadata.clientinfo_u64tag());
self
}
pub fn sample_for_identities(&mut self, identities: &impl MononokeIdentitySetExt) {
// Details of quicksand traffic aren't particularly interesting because all Quicksand tasks are
// doing effectively the same thing at the same time. If we need real-time debugging, we can
// always rely on updating the verbosity in real time.
if identities.is_quicksand() {
self.sampled_unless_verbose(nonzero!(100u64));
}
}
pub fn log_with_msg<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if self.fallback_sampled_out_to_verbose
&& self.should_log_with_level(ScubaVerbosityLevel::Verbose)
{
// We need to unsample before we log, so that
// `sample_rate` field is not added, as we are about
// to log everything.
self.inner.unsampled();
}
self.inner.add("log_tag", log_tag);
if let Some(mut msg) = msg.into() {
match tunables().get_max_scuba_msg_length().try_into() {
Ok(size) if size > 0 && msg.len() > size => {
msg.truncate(size);
msg.push_str(" (...)");
}
_ => {}
};
self.inner.add("msg", msg);
}
self.inner.log(); | pub fn log_with_msg_verbose<S: Into<Option<String>>>(&mut self, log_tag: &str, msg: S) {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
return;
}
self.log_with_msg(log_tag, msg)
}
pub fn add_stream_stats(&mut self, stats: &StreamStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add("count", stats.count)
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn add_future_stats(&mut self, stats: &FutureStats) -> &mut Self {
self.inner
.add("poll_count", stats.poll_count)
.add("poll_time_us", stats.poll_time.as_micros_unchecked())
.add(
"completion_time_us",
stats.completion_time.as_micros_unchecked(),
);
self
}
pub fn is_discard(&self) -> bool {
self.inner.is_discard()
}
pub fn sampled(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = false;
self.inner.sampled(sample_rate);
self
}
pub fn sampled_unless_verbose(&mut self, sample_rate: NonZeroU64) -> &mut Self {
self.fallback_sampled_out_to_verbose = true;
self.inner.sampled(sample_rate);
self
}
pub fn unsampled(&mut self) -> &mut Self {
self.inner.unsampled();
self
}
pub fn log(&mut self) -> bool {
self.inner.log()
}
/// Same as `log`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met
pub fn log_verbose(&mut self) -> bool {
if!self.should_log_with_level(ScubaVerbosityLevel::Verbose) {
// Return value of the `log` function indicates whether
// the sample passed sampling. If it's too verbose, let's
// return false
return false;
}
self.log()
}
pub fn add_common_server_data(&mut self) -> &mut Self {
self.inner.add_common_server_data();
self
}
pub fn sampling(&self) -> &Sampling {
self.inner.sampling()
}
pub fn add_mapped_common_server_data<F>(&mut self, mapper: F) -> &mut Self
where
F: Fn(ServerData) -> &'static str,
{
self.inner.add_mapped_common_server_data(mapper);
self
}
pub fn with_log_file<L: AsRef<Path>>(mut self, log_file: L) -> Result<Self, IoError> {
self.inner = self.inner.with_log_file(log_file)?;
Ok(self)
}
pub fn with_seq(mut self, key: impl Into<String>) -> Self {
self.inner = self.inner.with_seq(key);
self
}
pub fn log_with_time(&mut self, time: u64) -> bool {
self.inner.log_with_time(time)
}
pub fn entry<K: Into<String>>(&mut self, key: K) -> Entry<String, ScubaValue> {
self.inner.entry(key)
}
pub fn flush(&self, timeout: Duration) {
self.inner.flush(timeout)
}
pub fn get_sample(&self) -> &ScubaSample {
self.inner.get_sample()
}
pub fn add_opt<K: Into<String>, V: Into<ScubaValue>>(
&mut self,
key: K,
value: Option<V>,
) -> &mut Self {
self.inner.add_opt(key, value);
self
}
pub fn get<K: Into<String>>(&self, key: K) -> Option<&ScubaValue> {
self.inner.get(key)
}
} | }
/// Same as `log_with_msg`, but sample is assumed to be verbose and is only logged
/// if verbose logging conditions are met | random_line_split |
function.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 std::rc::Rc;
use std::cell::RefCell;
use value::*;
use ast;
use environment::Environment;
use runtime::RuntimeError;
#[derive(Clone, Debug)]
pub struct CallSign {
pub num_params: usize,
pub variadic: bool,
}
#[derive(Clone, Debug)]
pub enum Function {
NativeVoid(CallSign, fn(Vec<Value>) -> Result<(), RuntimeError>),
NativeReturning(CallSign, fn(Vec<Value>) -> Result<Value, RuntimeError>),
User {
call_sign: CallSign,
param_names: Vec<String>,
body: Box<ast::StmtNode>,
env: Rc<RefCell<Environment>>,
},
}
impl Function {
pub fn get_call_sign(&self) -> CallSign {
match *self {
Function::NativeVoid(ref call_sign, _) |
Function::NativeReturning(ref call_sign, _) |
Function::User { ref call_sign,.. } => call_sign.clone(),
}
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_println(args: Vec<Value>) -> Result<(), RuntimeError> {
if args.is_empty() {
return Ok(());
}
if args.len() == 1 {
println!("{}", args[0]);
} else {
print!("{}", args[0]);
for arg in args.iter().skip(1) {
print!(" {}", arg);
}
println!("");
}
Ok(())
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_assert(args: Vec<Value>) -> Result<(), RuntimeError> {
let val = &args[0];
if!val.is_truthy() {
Err(RuntimeError::GeneralRuntimeError(
format!("assert: assertion failed for value {}", val),
))
} else {
Ok(())
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_assert_eq(args: Vec<Value>) -> Result<(), RuntimeError> {
let (val1, val2) = (&args[0], &args[1]);
if val1!= val2 {
Err(RuntimeError::GeneralRuntimeError(
format!("assert_eq: {}!= {}", val1, val2),
))
} else {
Ok(())
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_len(args: Vec<Value>) -> Result<Value, RuntimeError> {
let val = &args[0];
match *val {
Value::Tuple(ref v) => Ok(Value::Number(Number::Integer(v.len() as i64))),
ref non_tuple_val => Err(RuntimeError::GeneralRuntimeError(
format!("cannot get len of {:?}", non_tuple_val.get_type()),
)),
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_run_http_server(args: Vec<Value>) -> Result<(), RuntimeError> {
use hyper::server::{Request, Response, Server};
use hyper::header::ContentType;
use hyper::uri::RequestUri;
use std::sync::mpsc::channel;
use std::sync::Mutex;
use std::thread;
use std::sync::PoisonError;
use ast_walk_interpreter::call_func;
let handler_val = &args[0];
let handler_func = match *handler_val {
Value::Function(ref f) => f,
_ => {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: handler is not a Function".to_owned(),
))
}
};
let maybe_hyper_server = Server::http("0.0.0.0:8000");
if let Err(e) = maybe_hyper_server {
return Err(RuntimeError::GeneralRuntimeError(
format!("http_server: {}", e),
));
}
let server = maybe_hyper_server.unwrap();
// channel from server to interpreter
let (sender, receiver) = channel();
let sender_mutex = Mutex::new(sender);
thread::spawn(|| {
println!("http_server: listening on 0.0.0.0:8000 on a new thread");
let handle_result = server.handle(move |req: Request, mut res: Response| {
let sender = match sender_mutex.lock() {
Ok(sender) => sender,
Err(PoisonError {.. }) => panic!("http_server: threading error (lock poisoned)"),
};
if let RequestUri::AbsolutePath(path) = req.uri {
// channel from interpreter to server
let (rev_sender, rev_receiver) = channel();
if sender.send((path, rev_sender)).is_err() {
panic!("http_server: threading error (could not send on reverse channel)");
}
let response_string: String = match rev_receiver.recv() {
Ok(response_string) => response_string,
Err(_) => {
// assume some clean disconnect
return;
}
};
res.headers_mut().set(ContentType::html());
if res.send(response_string.as_bytes()).is_err() {
panic!("http_server: could not send response");
}
} else {
panic!("http_server: unknown kind of request");
}
});
if handle_result.is_err() {
panic!("http_server: could not handle requests");
}
});
loop {
match receiver.recv() {
Err(_) => {
// assume some clean disconnect
break;
}
Ok(msg) => {
let (path, sender) = msg;
let possible_response_value = call_func(handler_func, &[Value::String(path)])?;
let response_value = match possible_response_value {
None => {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: handler \
function did not return a \
value"
.to_owned(),
));
}
Some(val) => val,
};
if sender.send(response_value.to_string()).is_err() |
}
}
}
Ok(())
}
| {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: threading error \
(could not send on reverse \
channel)"
.to_owned(),
));
} | conditional_block |
function.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 std::rc::Rc;
use std::cell::RefCell;
use value::*;
use ast;
use environment::Environment;
use runtime::RuntimeError;
#[derive(Clone, Debug)]
pub struct CallSign {
pub num_params: usize,
pub variadic: bool,
}
#[derive(Clone, Debug)]
pub enum | {
NativeVoid(CallSign, fn(Vec<Value>) -> Result<(), RuntimeError>),
NativeReturning(CallSign, fn(Vec<Value>) -> Result<Value, RuntimeError>),
User {
call_sign: CallSign,
param_names: Vec<String>,
body: Box<ast::StmtNode>,
env: Rc<RefCell<Environment>>,
},
}
impl Function {
pub fn get_call_sign(&self) -> CallSign {
match *self {
Function::NativeVoid(ref call_sign, _) |
Function::NativeReturning(ref call_sign, _) |
Function::User { ref call_sign,.. } => call_sign.clone(),
}
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_println(args: Vec<Value>) -> Result<(), RuntimeError> {
if args.is_empty() {
return Ok(());
}
if args.len() == 1 {
println!("{}", args[0]);
} else {
print!("{}", args[0]);
for arg in args.iter().skip(1) {
print!(" {}", arg);
}
println!("");
}
Ok(())
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_assert(args: Vec<Value>) -> Result<(), RuntimeError> {
let val = &args[0];
if!val.is_truthy() {
Err(RuntimeError::GeneralRuntimeError(
format!("assert: assertion failed for value {}", val),
))
} else {
Ok(())
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_assert_eq(args: Vec<Value>) -> Result<(), RuntimeError> {
let (val1, val2) = (&args[0], &args[1]);
if val1!= val2 {
Err(RuntimeError::GeneralRuntimeError(
format!("assert_eq: {}!= {}", val1, val2),
))
} else {
Ok(())
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_len(args: Vec<Value>) -> Result<Value, RuntimeError> {
let val = &args[0];
match *val {
Value::Tuple(ref v) => Ok(Value::Number(Number::Integer(v.len() as i64))),
ref non_tuple_val => Err(RuntimeError::GeneralRuntimeError(
format!("cannot get len of {:?}", non_tuple_val.get_type()),
)),
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_run_http_server(args: Vec<Value>) -> Result<(), RuntimeError> {
use hyper::server::{Request, Response, Server};
use hyper::header::ContentType;
use hyper::uri::RequestUri;
use std::sync::mpsc::channel;
use std::sync::Mutex;
use std::thread;
use std::sync::PoisonError;
use ast_walk_interpreter::call_func;
let handler_val = &args[0];
let handler_func = match *handler_val {
Value::Function(ref f) => f,
_ => {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: handler is not a Function".to_owned(),
))
}
};
let maybe_hyper_server = Server::http("0.0.0.0:8000");
if let Err(e) = maybe_hyper_server {
return Err(RuntimeError::GeneralRuntimeError(
format!("http_server: {}", e),
));
}
let server = maybe_hyper_server.unwrap();
// channel from server to interpreter
let (sender, receiver) = channel();
let sender_mutex = Mutex::new(sender);
thread::spawn(|| {
println!("http_server: listening on 0.0.0.0:8000 on a new thread");
let handle_result = server.handle(move |req: Request, mut res: Response| {
let sender = match sender_mutex.lock() {
Ok(sender) => sender,
Err(PoisonError {.. }) => panic!("http_server: threading error (lock poisoned)"),
};
if let RequestUri::AbsolutePath(path) = req.uri {
// channel from interpreter to server
let (rev_sender, rev_receiver) = channel();
if sender.send((path, rev_sender)).is_err() {
panic!("http_server: threading error (could not send on reverse channel)");
}
let response_string: String = match rev_receiver.recv() {
Ok(response_string) => response_string,
Err(_) => {
// assume some clean disconnect
return;
}
};
res.headers_mut().set(ContentType::html());
if res.send(response_string.as_bytes()).is_err() {
panic!("http_server: could not send response");
}
} else {
panic!("http_server: unknown kind of request");
}
});
if handle_result.is_err() {
panic!("http_server: could not handle requests");
}
});
loop {
match receiver.recv() {
Err(_) => {
// assume some clean disconnect
break;
}
Ok(msg) => {
let (path, sender) = msg;
let possible_response_value = call_func(handler_func, &[Value::String(path)])?;
let response_value = match possible_response_value {
None => {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: handler \
function did not return a \
value"
.to_owned(),
));
}
Some(val) => val,
};
if sender.send(response_value.to_string()).is_err() {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: threading error \
(could not send on reverse \
channel)"
.to_owned(),
));
}
}
}
}
Ok(())
}
| Function | identifier_name |
function.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 std::rc::Rc;
use std::cell::RefCell;
use value::*;
use ast;
use environment::Environment;
use runtime::RuntimeError;
#[derive(Clone, Debug)]
pub struct CallSign {
pub num_params: usize, | NativeVoid(CallSign, fn(Vec<Value>) -> Result<(), RuntimeError>),
NativeReturning(CallSign, fn(Vec<Value>) -> Result<Value, RuntimeError>),
User {
call_sign: CallSign,
param_names: Vec<String>,
body: Box<ast::StmtNode>,
env: Rc<RefCell<Environment>>,
},
}
impl Function {
pub fn get_call_sign(&self) -> CallSign {
match *self {
Function::NativeVoid(ref call_sign, _) |
Function::NativeReturning(ref call_sign, _) |
Function::User { ref call_sign,.. } => call_sign.clone(),
}
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_println(args: Vec<Value>) -> Result<(), RuntimeError> {
if args.is_empty() {
return Ok(());
}
if args.len() == 1 {
println!("{}", args[0]);
} else {
print!("{}", args[0]);
for arg in args.iter().skip(1) {
print!(" {}", arg);
}
println!("");
}
Ok(())
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_assert(args: Vec<Value>) -> Result<(), RuntimeError> {
let val = &args[0];
if!val.is_truthy() {
Err(RuntimeError::GeneralRuntimeError(
format!("assert: assertion failed for value {}", val),
))
} else {
Ok(())
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_assert_eq(args: Vec<Value>) -> Result<(), RuntimeError> {
let (val1, val2) = (&args[0], &args[1]);
if val1!= val2 {
Err(RuntimeError::GeneralRuntimeError(
format!("assert_eq: {}!= {}", val1, val2),
))
} else {
Ok(())
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_len(args: Vec<Value>) -> Result<Value, RuntimeError> {
let val = &args[0];
match *val {
Value::Tuple(ref v) => Ok(Value::Number(Number::Integer(v.len() as i64))),
ref non_tuple_val => Err(RuntimeError::GeneralRuntimeError(
format!("cannot get len of {:?}", non_tuple_val.get_type()),
)),
}
}
#[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))]
pub fn native_run_http_server(args: Vec<Value>) -> Result<(), RuntimeError> {
use hyper::server::{Request, Response, Server};
use hyper::header::ContentType;
use hyper::uri::RequestUri;
use std::sync::mpsc::channel;
use std::sync::Mutex;
use std::thread;
use std::sync::PoisonError;
use ast_walk_interpreter::call_func;
let handler_val = &args[0];
let handler_func = match *handler_val {
Value::Function(ref f) => f,
_ => {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: handler is not a Function".to_owned(),
))
}
};
let maybe_hyper_server = Server::http("0.0.0.0:8000");
if let Err(e) = maybe_hyper_server {
return Err(RuntimeError::GeneralRuntimeError(
format!("http_server: {}", e),
));
}
let server = maybe_hyper_server.unwrap();
// channel from server to interpreter
let (sender, receiver) = channel();
let sender_mutex = Mutex::new(sender);
thread::spawn(|| {
println!("http_server: listening on 0.0.0.0:8000 on a new thread");
let handle_result = server.handle(move |req: Request, mut res: Response| {
let sender = match sender_mutex.lock() {
Ok(sender) => sender,
Err(PoisonError {.. }) => panic!("http_server: threading error (lock poisoned)"),
};
if let RequestUri::AbsolutePath(path) = req.uri {
// channel from interpreter to server
let (rev_sender, rev_receiver) = channel();
if sender.send((path, rev_sender)).is_err() {
panic!("http_server: threading error (could not send on reverse channel)");
}
let response_string: String = match rev_receiver.recv() {
Ok(response_string) => response_string,
Err(_) => {
// assume some clean disconnect
return;
}
};
res.headers_mut().set(ContentType::html());
if res.send(response_string.as_bytes()).is_err() {
panic!("http_server: could not send response");
}
} else {
panic!("http_server: unknown kind of request");
}
});
if handle_result.is_err() {
panic!("http_server: could not handle requests");
}
});
loop {
match receiver.recv() {
Err(_) => {
// assume some clean disconnect
break;
}
Ok(msg) => {
let (path, sender) = msg;
let possible_response_value = call_func(handler_func, &[Value::String(path)])?;
let response_value = match possible_response_value {
None => {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: handler \
function did not return a \
value"
.to_owned(),
));
}
Some(val) => val,
};
if sender.send(response_value.to_string()).is_err() {
return Err(RuntimeError::GeneralRuntimeError(
"http_server: threading error \
(could not send on reverse \
channel)"
.to_owned(),
));
}
}
}
}
Ok(())
} | pub variadic: bool,
}
#[derive(Clone, Debug)]
pub enum Function { | random_line_split |
linkedlist.rs | #![feature(associated_type_defaults)]
#![warn(clippy::linkedlist)]
#![allow(dead_code, clippy::needless_pass_by_value)]
extern crate alloc;
use alloc::collections::linked_list::LinkedList;
const C: LinkedList<i32> = LinkedList::new();
static S: LinkedList<i32> = LinkedList::new();
trait Foo {
type Baz = LinkedList<u8>;
fn foo(_: LinkedList<u8>);
const BAR: Option<LinkedList<u8>>;
}
// Ok, we don’t want to warn for implementations; see issue #605.
impl Foo for LinkedList<u8> {
fn foo(_: LinkedList<u8>) {}
const BAR: Option<LinkedList<u8>> = None;
}
struct Bar;
impl Bar {
fn foo(_: LinkedList<u8>) {} |
pub fn test(my_favourite_linked_list: LinkedList<u8>) {
println!("{:?}", my_favourite_linked_list)
}
pub fn test_ret() -> Option<LinkedList<u8>> {
unimplemented!();
}
pub fn test_local_not_linted() {
let _: LinkedList<u8>;
}
fn main() {
test(LinkedList::new());
test_local_not_linted();
}
|
} | identifier_body |
linkedlist.rs | #![feature(associated_type_defaults)]
#![warn(clippy::linkedlist)]
#![allow(dead_code, clippy::needless_pass_by_value)]
extern crate alloc;
use alloc::collections::linked_list::LinkedList;
const C: LinkedList<i32> = LinkedList::new();
static S: LinkedList<i32> = LinkedList::new();
trait Foo {
type Baz = LinkedList<u8>;
fn foo(_: LinkedList<u8>);
const BAR: Option<LinkedList<u8>>;
}
// Ok, we don’t want to warn for implementations; see issue #605.
impl Foo for LinkedList<u8> {
fn foo(_: LinkedList<u8>) {}
const BAR: Option<LinkedList<u8>> = None;
}
struct Bar;
impl Bar {
fn foo(_: LinkedList<u8>) {}
}
pub fn test(my_favourite_linked_list: LinkedList<u8>) {
println!("{:?}", my_favourite_linked_list)
}
pub fn test_ret() -> Option<LinkedList<u8>> {
unimplemented!();
}
pub fn test_local_not_linted() { | test_local_not_linted();
} | let _: LinkedList<u8>;
}
fn main() {
test(LinkedList::new()); | random_line_split |
linkedlist.rs | #![feature(associated_type_defaults)]
#![warn(clippy::linkedlist)]
#![allow(dead_code, clippy::needless_pass_by_value)]
extern crate alloc;
use alloc::collections::linked_list::LinkedList;
const C: LinkedList<i32> = LinkedList::new();
static S: LinkedList<i32> = LinkedList::new();
trait Foo {
type Baz = LinkedList<u8>;
fn foo(_: LinkedList<u8>);
const BAR: Option<LinkedList<u8>>;
}
// Ok, we don’t want to warn for implementations; see issue #605.
impl Foo for LinkedList<u8> {
fn foo(_: LinkedList<u8>) {}
const BAR: Option<LinkedList<u8>> = None;
}
struct Bar;
impl Bar {
fn foo(_: LinkedList<u8>) {}
}
pub fn test(my_favourite_linked_list: LinkedList<u8>) {
println!("{:?}", my_favourite_linked_list)
}
pub fn test_ret() -> Option<LinkedList<u8>> {
unimplemented!();
}
pub fn te | {
let _: LinkedList<u8>;
}
fn main() {
test(LinkedList::new());
test_local_not_linted();
}
| st_local_not_linted() | identifier_name |
check_static_recursion.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This compiler pass detects static items that refer to themselves
// recursively.
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefMap};
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a DefMap,
ast_map: &'a ast_map::Map<'ast>
}
impl<'v, 'a, 'ast> Visitor<'v> for CheckCrateVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &ast::Item) {
match it.node {
ast::ItemStatic(_, _, ref expr) |
ast::ItemConst(_, ref expr) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
visit::walk_expr(self, &*expr)
},
_ => visit::walk_item(self, it)
}
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
match ti.node {
ast::ConstTraitItem(_, ref default) => {
if let Some(ref expr) = *default {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ti.span);
recursion_visitor.visit_trait_item(ti);
visit::walk_expr(self, &*expr)
}
}
_ => visit::walk_trait_item(self, ti)
}
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
match ii.node {
ast::ConstImplItem(_, ref expr) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ii.span);
recursion_visitor.visit_impl_item(ii);
visit::walk_expr(self, &*expr)
}
_ => visit::walk_impl_item(self, ii)
}
}
}
pub fn check_crate<'ast>(sess: &Session,
krate: &ast::Crate,
def_map: &DefMap,
ast_map: &ast_map::Map<'ast>) {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
}
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
idstack: Vec<ast::NodeId>
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
idstack: Vec::new()
}
}
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) |
}
impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &ast::Item) {
self.with_item_id_pushed(it.id, |v| visit::walk_item(v, it));
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.with_item_id_pushed(ti.id, |v| visit::walk_trait_item(v, ti));
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.with_item_id_pushed(ii.id, |v| visit::walk_impl_item(v, ii));
}
fn visit_expr(&mut self, e: &ast::Expr) {
match e.node {
ast::ExprPath(..) => {
match self.def_map.borrow().get(&e.id).map(|d| d.base_def) {
Some(DefStatic(def_id, _)) |
Some(DefAssociatedConst(def_id, _)) |
Some(DefConst(def_id)) if
ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.visit_trait_item(item),
ast_map::NodeImplItem(item) =>
self.visit_impl_item(item),
ast_map::NodeForeignItem(_) => {},
_ => {
span_err!(self.sess, e.span, E0266,
"expected item, found {}",
self.ast_map.node_to_string(def_id.node));
return;
},
}
}
_ => ()
}
},
_ => ()
}
visit::walk_expr(self, e);
}
}
| {
if self.idstack.iter().any(|x| x == &(id)) {
span_err!(self.sess, *self.root_span, E0265, "recursive constant");
return;
}
self.idstack.push(id);
f(self);
self.idstack.pop();
} | identifier_body |
check_static_recursion.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This compiler pass detects static items that refer to themselves
// recursively.
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefMap};
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a DefMap,
ast_map: &'a ast_map::Map<'ast>
}
impl<'v, 'a, 'ast> Visitor<'v> for CheckCrateVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &ast::Item) {
match it.node {
ast::ItemStatic(_, _, ref expr) |
ast::ItemConst(_, ref expr) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
visit::walk_expr(self, &*expr)
},
_ => visit::walk_item(self, it)
}
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
match ti.node {
ast::ConstTraitItem(_, ref default) => {
if let Some(ref expr) = *default {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ti.span);
recursion_visitor.visit_trait_item(ti);
visit::walk_expr(self, &*expr)
}
}
_ => visit::walk_trait_item(self, ti)
}
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
match ii.node {
ast::ConstImplItem(_, ref expr) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ii.span);
recursion_visitor.visit_impl_item(ii);
visit::walk_expr(self, &*expr)
}
_ => visit::walk_impl_item(self, ii)
}
}
}
pub fn check_crate<'ast>(sess: &Session,
krate: &ast::Crate,
def_map: &DefMap,
ast_map: &ast_map::Map<'ast>) {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
}
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
idstack: Vec<ast::NodeId>
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
idstack: Vec::new()
}
}
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) {
if self.idstack.iter().any(|x| x == &(id)) {
span_err!(self.sess, *self.root_span, E0265, "recursive constant");
return;
}
self.idstack.push(id);
f(self);
self.idstack.pop();
}
}
impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> { | fn visit_item(&mut self, it: &ast::Item) {
self.with_item_id_pushed(it.id, |v| visit::walk_item(v, it));
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.with_item_id_pushed(ti.id, |v| visit::walk_trait_item(v, ti));
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.with_item_id_pushed(ii.id, |v| visit::walk_impl_item(v, ii));
}
fn visit_expr(&mut self, e: &ast::Expr) {
match e.node {
ast::ExprPath(..) => {
match self.def_map.borrow().get(&e.id).map(|d| d.base_def) {
Some(DefStatic(def_id, _)) |
Some(DefAssociatedConst(def_id, _)) |
Some(DefConst(def_id)) if
ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.visit_trait_item(item),
ast_map::NodeImplItem(item) =>
self.visit_impl_item(item),
ast_map::NodeForeignItem(_) => {},
_ => {
span_err!(self.sess, e.span, E0266,
"expected item, found {}",
self.ast_map.node_to_string(def_id.node));
return;
},
}
}
_ => ()
}
},
_ => ()
}
visit::walk_expr(self, e);
}
} | random_line_split |
|
check_static_recursion.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This compiler pass detects static items that refer to themselves
// recursively.
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefMap};
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::visit::Visitor;
use syntax::visit;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a DefMap,
ast_map: &'a ast_map::Map<'ast>
}
impl<'v, 'a, 'ast> Visitor<'v> for CheckCrateVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &ast::Item) {
match it.node {
ast::ItemStatic(_, _, ref expr) |
ast::ItemConst(_, ref expr) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
visit::walk_expr(self, &*expr)
},
_ => visit::walk_item(self, it)
}
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
match ti.node {
ast::ConstTraitItem(_, ref default) => {
if let Some(ref expr) = *default {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ti.span);
recursion_visitor.visit_trait_item(ti);
visit::walk_expr(self, &*expr)
}
}
_ => visit::walk_trait_item(self, ti)
}
}
fn | (&mut self, ii: &ast::ImplItem) {
match ii.node {
ast::ConstImplItem(_, ref expr) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ii.span);
recursion_visitor.visit_impl_item(ii);
visit::walk_expr(self, &*expr)
}
_ => visit::walk_impl_item(self, ii)
}
}
}
pub fn check_crate<'ast>(sess: &Session,
krate: &ast::Crate,
def_map: &DefMap,
ast_map: &ast_map::Map<'ast>) {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
}
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
idstack: Vec<ast::NodeId>
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
idstack: Vec::new()
}
}
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) {
if self.idstack.iter().any(|x| x == &(id)) {
span_err!(self.sess, *self.root_span, E0265, "recursive constant");
return;
}
self.idstack.push(id);
f(self);
self.idstack.pop();
}
}
impl<'a, 'ast, 'v> Visitor<'v> for CheckItemRecursionVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &ast::Item) {
self.with_item_id_pushed(it.id, |v| visit::walk_item(v, it));
}
fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
self.with_item_id_pushed(ti.id, |v| visit::walk_trait_item(v, ti));
}
fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
self.with_item_id_pushed(ii.id, |v| visit::walk_impl_item(v, ii));
}
fn visit_expr(&mut self, e: &ast::Expr) {
match e.node {
ast::ExprPath(..) => {
match self.def_map.borrow().get(&e.id).map(|d| d.base_def) {
Some(DefStatic(def_id, _)) |
Some(DefAssociatedConst(def_id, _)) |
Some(DefConst(def_id)) if
ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.visit_trait_item(item),
ast_map::NodeImplItem(item) =>
self.visit_impl_item(item),
ast_map::NodeForeignItem(_) => {},
_ => {
span_err!(self.sess, e.span, E0266,
"expected item, found {}",
self.ast_map.node_to_string(def_id.node));
return;
},
}
}
_ => ()
}
},
_ => ()
}
visit::walk_expr(self, e);
}
}
| visit_impl_item | identifier_name |
associated-types-ref-in-struct-literal.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test associated type references in a struct literal. Issue #20535.
pub trait Foo {
type Bar;
fn dummy(&self) { }
}
impl Foo for isize {
type Bar = isize;
}
struct Thing<F: Foo> {
a: F,
b: F::Bar,
}
fn | () {
let thing = Thing{a: 1, b: 2};
assert_eq!(thing.a + 1, thing.b);
}
| main | identifier_name |
associated-types-ref-in-struct-literal.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // except according to those terms.
// Test associated type references in a struct literal. Issue #20535.
pub trait Foo {
type Bar;
fn dummy(&self) { }
}
impl Foo for isize {
type Bar = isize;
}
struct Thing<F: Foo> {
a: F,
b: F::Bar,
}
fn main() {
let thing = Thing{a: 1, b: 2};
assert_eq!(thing.a + 1, thing.b);
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
associated-types-ref-in-struct-literal.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test associated type references in a struct literal. Issue #20535.
pub trait Foo {
type Bar;
fn dummy(&self) { }
}
impl Foo for isize {
type Bar = isize;
}
struct Thing<F: Foo> {
a: F,
b: F::Bar,
}
fn main() | {
let thing = Thing{a: 1, b: 2};
assert_eq!(thing.a + 1, thing.b);
} | identifier_body |
|
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
#![feature(box_syntax, int_uint)]
#![allow(unstable)]
#[macro_use] extern crate bitflags;
#[cfg(target_os="macos")]
extern crate cgl;
extern crate compositing;
extern crate geom;
extern crate gleam;
extern crate glutin;
extern crate layers;
extern crate libc;
extern crate msg;
extern crate time;
extern crate util;
extern crate egl;
use compositing::windowing::WindowEvent;
use geom::scale_factor::ScaleFactor;
use std::rc::Rc;
use window::Window;
use util::opts;
pub mod window;
pub trait NestedEventLoopListener {
fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool;
}
pub fn create_window() -> Rc<Window> {
// Read command-line options.
let opts = opts::get();
let foreground = opts.output_file.is_none();
let scale_factor = opts.device_pixels_per_px.unwrap_or(ScaleFactor(1.0));
let size = opts.initial_window_size.as_f32() * scale_factor;
// Open a window.
Window::new(foreground, size.as_uint().cast().unwrap())
} |
//! A simple application that uses glutin to open a window for Servo to display in. | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A simple application that uses glutin to open a window for Servo to display in.
#![feature(box_syntax, int_uint)]
#![allow(unstable)]
#[macro_use] extern crate bitflags;
#[cfg(target_os="macos")]
extern crate cgl;
extern crate compositing;
extern crate geom;
extern crate gleam;
extern crate glutin;
extern crate layers;
extern crate libc;
extern crate msg;
extern crate time;
extern crate util;
extern crate egl;
use compositing::windowing::WindowEvent;
use geom::scale_factor::ScaleFactor;
use std::rc::Rc;
use window::Window;
use util::opts;
pub mod window;
pub trait NestedEventLoopListener {
fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool;
}
pub fn | () -> Rc<Window> {
// Read command-line options.
let opts = opts::get();
let foreground = opts.output_file.is_none();
let scale_factor = opts.device_pixels_per_px.unwrap_or(ScaleFactor(1.0));
let size = opts.initial_window_size.as_f32() * scale_factor;
// Open a window.
Window::new(foreground, size.as_uint().cast().unwrap())
}
| create_window | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! A simple application that uses glutin to open a window for Servo to display in.
#![feature(box_syntax, int_uint)]
#![allow(unstable)]
#[macro_use] extern crate bitflags;
#[cfg(target_os="macos")]
extern crate cgl;
extern crate compositing;
extern crate geom;
extern crate gleam;
extern crate glutin;
extern crate layers;
extern crate libc;
extern crate msg;
extern crate time;
extern crate util;
extern crate egl;
use compositing::windowing::WindowEvent;
use geom::scale_factor::ScaleFactor;
use std::rc::Rc;
use window::Window;
use util::opts;
pub mod window;
pub trait NestedEventLoopListener {
fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool;
}
pub fn create_window() -> Rc<Window> | {
// Read command-line options.
let opts = opts::get();
let foreground = opts.output_file.is_none();
let scale_factor = opts.device_pixels_per_px.unwrap_or(ScaleFactor(1.0));
let size = opts.initial_window_size.as_f32() * scale_factor;
// Open a window.
Window::new(foreground, size.as_uint().cast().unwrap())
} | identifier_body |
|
lib.rs | use std::io::ErrorKind;
use std::net::Ipv4Addr;
use std::net::TcpStream;
use spaceapi_server::api;
use spaceapi_server::{SpaceapiServer, SpaceapiServerBuilder};
/// Create a new status object containing test data.
fn | () -> api::Status {
api::StatusBuilder::new("ourspace")
.logo("https://example.com/logo.png")
.url("https://example.com/")
.location(api::Location {
address: Some("Street 1, Zürich, Switzerland".into()),
lat: 47.123,
lon: 8.88,
})
.contact(api::Contact {
irc: None,
twitter: None,
foursquare: None,
email: Some("[email protected]".into()),
ml: None,
phone: None,
jabber: None,
issue_mail: None,
identica: None,
facebook: None,
google: None,
keymasters: None,
sip: None,
})
.add_issue_report_channel(api::IssueReportChannel::Email)
.add_issue_report_channel(api::IssueReportChannel::Twitter)
.build()
.unwrap()
}
/// Create a new SpaceapiServer instance listening on the specified port.
fn get_server(status: api::Status) -> SpaceapiServer {
SpaceapiServerBuilder::new(status)
.redis_connection_info("redis://127.0.0.1/")
.build()
.unwrap()
}
#[test]
fn server_starts() {
//! Test that the spaceapi server starts at all.
// Ip / port for test server
let ip = Ipv4Addr::new(127, 0, 0, 1);
let port = 3344;
// Test data
let status = get_status();
// Connection to port should fail right now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_err());
assert_eq!(connect_result.unwrap_err().kind(), ErrorKind::ConnectionRefused);
// Instantiate and start server
let server = get_server(status);
let mut listening = server.serve((ip, port)).unwrap();
// Connecting to server should work now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_ok());
// Close server
listening.close().unwrap();
}
| get_status | identifier_name |
lib.rs | use std::io::ErrorKind;
use std::net::Ipv4Addr;
use std::net::TcpStream;
use spaceapi_server::api;
use spaceapi_server::{SpaceapiServer, SpaceapiServerBuilder};
/// Create a new status object containing test data.
fn get_status() -> api::Status {
api::StatusBuilder::new("ourspace")
.logo("https://example.com/logo.png")
.url("https://example.com/")
.location(api::Location {
address: Some("Street 1, Zürich, Switzerland".into()),
lat: 47.123,
lon: 8.88,
})
.contact(api::Contact {
irc: None,
twitter: None,
foursquare: None,
email: Some("[email protected]".into()),
ml: None,
phone: None,
jabber: None,
issue_mail: None,
identica: None,
facebook: None,
google: None,
keymasters: None,
sip: None,
})
.add_issue_report_channel(api::IssueReportChannel::Email)
.add_issue_report_channel(api::IssueReportChannel::Twitter)
.build()
.unwrap()
}
/// Create a new SpaceapiServer instance listening on the specified port.
fn get_server(status: api::Status) -> SpaceapiServer { |
#[test]
fn server_starts() {
//! Test that the spaceapi server starts at all.
// Ip / port for test server
let ip = Ipv4Addr::new(127, 0, 0, 1);
let port = 3344;
// Test data
let status = get_status();
// Connection to port should fail right now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_err());
assert_eq!(connect_result.unwrap_err().kind(), ErrorKind::ConnectionRefused);
// Instantiate and start server
let server = get_server(status);
let mut listening = server.serve((ip, port)).unwrap();
// Connecting to server should work now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_ok());
// Close server
listening.close().unwrap();
}
|
SpaceapiServerBuilder::new(status)
.redis_connection_info("redis://127.0.0.1/")
.build()
.unwrap()
}
| identifier_body |
lib.rs | use std::io::ErrorKind;
use std::net::Ipv4Addr;
use std::net::TcpStream;
use spaceapi_server::api;
use spaceapi_server::{SpaceapiServer, SpaceapiServerBuilder};
/// Create a new status object containing test data.
fn get_status() -> api::Status {
api::StatusBuilder::new("ourspace")
.logo("https://example.com/logo.png")
.url("https://example.com/")
.location(api::Location {
address: Some("Street 1, Zürich, Switzerland".into()),
lat: 47.123,
lon: 8.88,
})
.contact(api::Contact {
irc: None,
twitter: None,
foursquare: None,
email: Some("[email protected]".into()),
ml: None,
phone: None,
jabber: None,
issue_mail: None,
identica: None,
facebook: None,
google: None,
keymasters: None,
sip: None,
})
.add_issue_report_channel(api::IssueReportChannel::Email)
.add_issue_report_channel(api::IssueReportChannel::Twitter)
.build()
.unwrap()
}
/// Create a new SpaceapiServer instance listening on the specified port.
fn get_server(status: api::Status) -> SpaceapiServer {
SpaceapiServerBuilder::new(status)
.redis_connection_info("redis://127.0.0.1/")
.build()
.unwrap()
}
#[test]
fn server_starts() {
//! Test that the spaceapi server starts at all.
| // Ip / port for test server
let ip = Ipv4Addr::new(127, 0, 0, 1);
let port = 3344;
// Test data
let status = get_status();
// Connection to port should fail right now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_err());
assert_eq!(connect_result.unwrap_err().kind(), ErrorKind::ConnectionRefused);
// Instantiate and start server
let server = get_server(status);
let mut listening = server.serve((ip, port)).unwrap();
// Connecting to server should work now
let connect_result = TcpStream::connect((ip, port));
assert!(connect_result.is_ok());
// Close server
listening.close().unwrap();
} | random_line_split |
|
elf64.rs | use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
pub e_ident: [u8; SIZEOF_IDENT],
/// Object file type
pub e_type: u16,
/// Architecture
pub e_machine: u16,
/// Object file version
pub e_version: u32,
/// Entry point virtual address
pub e_entry: u64,
/// Program header table file offset
pub e_phoff: u64,
/// Section header table file offset
pub e_shoff: u64,
/// Processor-specific flags
pub e_flags: u32,
/// ELF header size in bytes
pub e_ehsize: u16,
/// Program header table entry size
pub e_phentsize: u16,
/// Program header table entry count
pub e_phnum: u16,
/// Section header table entry size
pub e_shentsize: u16,
/// Section header table entry count
pub e_shnum: u16,
/// Section header string table index
pub e_shstrndx: u16,
}
impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "e_ident: {:?} e_type: {} e_machine: 0x{:x} e_version: 0x{:x} e_entry: 0x{:x} \
e_phoff: 0x{:x} e_shoff: 0x{:x} e_flags: {:x} e_ehsize: {} e_phentsize: {} \
e_phnum: {} e_shentsize: {} e_shnum: {} e_shstrndx: {}",
self.e_ident,
et_to_str(self.e_type),
self.e_machine,
self.e_version,
self.e_entry,
self.e_phoff,
self.e_shoff,
self.e_flags,
self.e_ehsize,
self.e_phentsize,
self.e_phnum,
self.e_shentsize,
self.e_shnum,
self.e_shstrndx)
}
}
/// No file type.
pub const ET_NONE: u16 = 0;
/// Relocatable file.
pub const ET_REL: u16 = 1;
/// Executable file.
pub const ET_EXEC: u16 = 2;
/// Shared object file.
pub const ET_DYN: u16 = 3;
/// Core file.
pub const ET_CORE: u16 = 4;
/// Number of defined types.
pub const ET_NUM: u16 = 5;
/// The ELF magic number.
pub const ELFMAG: &'static [u8; 4] = b"\x7FELF";
/// Sizeof ELF magic number.
pub const SELFMAG: usize = 4;
/// File class byte index.
pub const EI_CLASS: usize = 4;
/// Invalid class.
pub const ELFCLASSNONE: u8 = 0;
/// 32-bit objects.
pub const ELFCLASS32: u8 = 1;
/// 64-bit objects.
pub const ELFCLASS64: u8 = 2;
/// ELF class number.
pub const ELFCLASSNUM: u8 = 3;
/// Convert an ET value to their associated string.
#[inline]
pub fn et_to_str(et: u16) -> &'static str {
match et {
ET_NONE => "NONE",
ET_REL => "REL",
ET_EXEC => "EXEC",
ET_DYN => "DYN",
ET_CORE => "CORE",
ET_NUM => "NUM",
_ => "UNKNOWN_ET",
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct ProgramHeader {
/// Segment type
pub p_type: u32,
/// Segment flags
pub p_flags: u32,
/// Segment file offset
pub p_offset: u64,
/// Segment virtual address
pub p_vaddr: u64,
/// Segment physical address
pub p_paddr: u64,
/// Segment size in file
pub p_filesz: u64,
/// Segment size in memory
pub p_memsz: u64,
/// Segment alignment
pub p_align: u64,
}
pub const SIZEOF_PHDR: usize = 56;
/// Program header table entry unused
pub const PT_NULL: u32 = 0;
/// Loadable program segment
pub const PT_LOAD: u32 = 1;
/// Dynamic linking information
pub const PT_DYNAMIC: u32 = 2;
/// Program interpreter
pub const PT_INTERP: u32 = 3;
/// Auxiliary information
pub const PT_NOTE: u32 = 4;
/// Reserved
pub const PT_SHLIB: u32 = 5;
/// Entry for header table itself
pub const PT_PHDR: u32 = 6;
/// Thread-local storage segment
pub const PT_TLS: u32 = 7;
/// Number of defined types
pub const PT_NUM: u32 = 8;
/// Start of OS-specific
pub const PT_LOOS: u32 = 0x60000000;
/// GCC.eh_frame_hdr segment
pub const PT_GNU_EH_FRAME: u32 = 0x6474e550;
/// Indicates stack executability
pub const PT_GNU_STACK: u32 = 0x6474e551;
/// Read-only after relocation
pub const PT_GNU_RELRO: u32 = 0x6474e552;
/// Sun Specific segment
pub const PT_LOSUNW: u32 = 0x6ffffffa;
/// Sun Specific segment
pub const PT_SUNWBSS: u32 = 0x6ffffffa;
/// Stack segment
pub const PT_SUNWSTACK: u32 = 0x6ffffffb;
/// End of OS-specific
pub const PT_HISUNW: u32 = 0x6fffffff;
/// End of OS-specific
pub const PT_HIOS: u32 = 0x6fffffff;
/// Start of processor-specific
pub const PT_LOPROC: u32 = 0x70000000;
/// ARM unwind segment
pub const PT_ARM_EXIDX: u32 = 0x70000001;
/// End of processor-specific
pub const PT_HIPROC: u32 = 0x7fffffff;
/// Segment is executable
pub const PF_X: u32 = 1 << 0;
/// Segment is writable
pub const PF_W: u32 = 1 << 1;
/// Segment is readable
pub const PF_R: u32 = 1 << 2;
pub struct ProgramHeaderIter<'a> {
data: &'a [u8],
header: &'a Header,
next: usize
}
pub struct Elf64<'a> {
pub header: &'a Header,
pub data: &'a [u8]
}
impl<'a> Elf64<'a> {
pub unsafe fn | (bytes: &'a [u8]) -> Elf64<'a> {
let h = &*(bytes.as_ptr() as *const Header);
Elf64 {
data: bytes,
header: h,
}
}
pub fn program_headers(&self) -> ProgramHeaderIter<'a> {
ProgramHeaderIter {
data: self.data,
header: self.header,
next: 0
}
}
}
impl<'a> Iterator for ProgramHeaderIter<'a> {
type Item = &'a ProgramHeader;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.header.e_phnum as usize {
let program = unsafe {
&*(self.data.as_ptr().offset(
self.header.e_phoff as isize +
self.header.e_phentsize as isize * self.next as isize)
as *const ProgramHeader)
};
self.next += 1;
Some(program)
} else {
None
}
}
}
| from | identifier_name |
elf64.rs | use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
pub e_ident: [u8; SIZEOF_IDENT],
/// Object file type
pub e_type: u16,
/// Architecture
pub e_machine: u16,
/// Object file version
pub e_version: u32,
/// Entry point virtual address
pub e_entry: u64,
/// Program header table file offset
pub e_phoff: u64,
/// Section header table file offset
pub e_shoff: u64,
/// Processor-specific flags
pub e_flags: u32,
/// ELF header size in bytes
pub e_ehsize: u16,
/// Program header table entry size
pub e_phentsize: u16,
/// Program header table entry count
pub e_phnum: u16,
/// Section header table entry size
pub e_shentsize: u16,
/// Section header table entry count
pub e_shnum: u16,
/// Section header string table index
pub e_shstrndx: u16,
}
impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "e_ident: {:?} e_type: {} e_machine: 0x{:x} e_version: 0x{:x} e_entry: 0x{:x} \
e_phoff: 0x{:x} e_shoff: 0x{:x} e_flags: {:x} e_ehsize: {} e_phentsize: {} \
e_phnum: {} e_shentsize: {} e_shnum: {} e_shstrndx: {}",
self.e_ident,
et_to_str(self.e_type),
self.e_machine,
self.e_version,
self.e_entry,
self.e_phoff,
self.e_shoff,
self.e_flags,
self.e_ehsize,
self.e_phentsize,
self.e_phnum,
self.e_shentsize,
self.e_shnum,
self.e_shstrndx)
}
}
/// No file type.
pub const ET_NONE: u16 = 0;
/// Relocatable file.
pub const ET_REL: u16 = 1;
/// Executable file.
pub const ET_EXEC: u16 = 2;
/// Shared object file.
pub const ET_DYN: u16 = 3;
/// Core file.
pub const ET_CORE: u16 = 4;
/// Number of defined types.
pub const ET_NUM: u16 = 5;
/// The ELF magic number.
pub const ELFMAG: &'static [u8; 4] = b"\x7FELF";
/// Sizeof ELF magic number.
pub const SELFMAG: usize = 4;
/// File class byte index.
pub const EI_CLASS: usize = 4;
/// Invalid class.
pub const ELFCLASSNONE: u8 = 0;
/// 32-bit objects.
pub const ELFCLASS32: u8 = 1;
/// 64-bit objects.
pub const ELFCLASS64: u8 = 2;
/// ELF class number.
pub const ELFCLASSNUM: u8 = 3;
/// Convert an ET value to their associated string.
#[inline]
pub fn et_to_str(et: u16) -> &'static str {
match et {
ET_NONE => "NONE",
ET_REL => "REL",
ET_EXEC => "EXEC",
ET_DYN => "DYN",
ET_CORE => "CORE",
ET_NUM => "NUM",
_ => "UNKNOWN_ET",
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct ProgramHeader {
/// Segment type
pub p_type: u32,
/// Segment flags
pub p_flags: u32,
/// Segment file offset
pub p_offset: u64,
/// Segment virtual address
pub p_vaddr: u64,
/// Segment physical address
pub p_paddr: u64,
/// Segment size in file
pub p_filesz: u64,
/// Segment size in memory
pub p_memsz: u64,
/// Segment alignment
pub p_align: u64,
}
pub const SIZEOF_PHDR: usize = 56;
/// Program header table entry unused
pub const PT_NULL: u32 = 0;
/// Loadable program segment
pub const PT_LOAD: u32 = 1;
/// Dynamic linking information
pub const PT_DYNAMIC: u32 = 2;
/// Program interpreter
pub const PT_INTERP: u32 = 3;
/// Auxiliary information
pub const PT_NOTE: u32 = 4;
/// Reserved
pub const PT_SHLIB: u32 = 5;
/// Entry for header table itself
pub const PT_PHDR: u32 = 6;
/// Thread-local storage segment
pub const PT_TLS: u32 = 7;
/// Number of defined types
pub const PT_NUM: u32 = 8;
/// Start of OS-specific
pub const PT_LOOS: u32 = 0x60000000;
/// GCC.eh_frame_hdr segment
pub const PT_GNU_EH_FRAME: u32 = 0x6474e550;
/// Indicates stack executability
pub const PT_GNU_STACK: u32 = 0x6474e551;
/// Read-only after relocation
pub const PT_GNU_RELRO: u32 = 0x6474e552;
/// Sun Specific segment
pub const PT_LOSUNW: u32 = 0x6ffffffa;
/// Sun Specific segment
pub const PT_SUNWBSS: u32 = 0x6ffffffa;
/// Stack segment
pub const PT_SUNWSTACK: u32 = 0x6ffffffb;
/// End of OS-specific
pub const PT_HISUNW: u32 = 0x6fffffff;
/// End of OS-specific
pub const PT_HIOS: u32 = 0x6fffffff;
/// Start of processor-specific
pub const PT_LOPROC: u32 = 0x70000000;
/// ARM unwind segment
pub const PT_ARM_EXIDX: u32 = 0x70000001;
/// End of processor-specific
pub const PT_HIPROC: u32 = 0x7fffffff;
| pub const PF_X: u32 = 1 << 0;
/// Segment is writable
pub const PF_W: u32 = 1 << 1;
/// Segment is readable
pub const PF_R: u32 = 1 << 2;
pub struct ProgramHeaderIter<'a> {
data: &'a [u8],
header: &'a Header,
next: usize
}
pub struct Elf64<'a> {
pub header: &'a Header,
pub data: &'a [u8]
}
impl<'a> Elf64<'a> {
pub unsafe fn from(bytes: &'a [u8]) -> Elf64<'a> {
let h = &*(bytes.as_ptr() as *const Header);
Elf64 {
data: bytes,
header: h,
}
}
pub fn program_headers(&self) -> ProgramHeaderIter<'a> {
ProgramHeaderIter {
data: self.data,
header: self.header,
next: 0
}
}
}
impl<'a> Iterator for ProgramHeaderIter<'a> {
type Item = &'a ProgramHeader;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.header.e_phnum as usize {
let program = unsafe {
&*(self.data.as_ptr().offset(
self.header.e_phoff as isize +
self.header.e_phentsize as isize * self.next as isize)
as *const ProgramHeader)
};
self.next += 1;
Some(program)
} else {
None
}
}
} | /// Segment is executable | random_line_split |
elf64.rs | use core::fmt;
use core::iter::Iterator;
use ::kern::console::LogLevel::*;
pub const SIZEOF_IDENT: usize = 16;
pub const SIZEOF_EHDR: usize = 64;
pub const ELFCLASS: u8 = ELFCLASS64;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq)]
pub struct Header {
/// Magic number and other info
pub e_ident: [u8; SIZEOF_IDENT],
/// Object file type
pub e_type: u16,
/// Architecture
pub e_machine: u16,
/// Object file version
pub e_version: u32,
/// Entry point virtual address
pub e_entry: u64,
/// Program header table file offset
pub e_phoff: u64,
/// Section header table file offset
pub e_shoff: u64,
/// Processor-specific flags
pub e_flags: u32,
/// ELF header size in bytes
pub e_ehsize: u16,
/// Program header table entry size
pub e_phentsize: u16,
/// Program header table entry count
pub e_phnum: u16,
/// Section header table entry size
pub e_shentsize: u16,
/// Section header table entry count
pub e_shnum: u16,
/// Section header string table index
pub e_shstrndx: u16,
}
impl fmt::Debug for Header {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
/// No file type.
pub const ET_NONE: u16 = 0;
/// Relocatable file.
pub const ET_REL: u16 = 1;
/// Executable file.
pub const ET_EXEC: u16 = 2;
/// Shared object file.
pub const ET_DYN: u16 = 3;
/// Core file.
pub const ET_CORE: u16 = 4;
/// Number of defined types.
pub const ET_NUM: u16 = 5;
/// The ELF magic number.
pub const ELFMAG: &'static [u8; 4] = b"\x7FELF";
/// Sizeof ELF magic number.
pub const SELFMAG: usize = 4;
/// File class byte index.
pub const EI_CLASS: usize = 4;
/// Invalid class.
pub const ELFCLASSNONE: u8 = 0;
/// 32-bit objects.
pub const ELFCLASS32: u8 = 1;
/// 64-bit objects.
pub const ELFCLASS64: u8 = 2;
/// ELF class number.
pub const ELFCLASSNUM: u8 = 3;
/// Convert an ET value to their associated string.
#[inline]
pub fn et_to_str(et: u16) -> &'static str {
match et {
ET_NONE => "NONE",
ET_REL => "REL",
ET_EXEC => "EXEC",
ET_DYN => "DYN",
ET_CORE => "CORE",
ET_NUM => "NUM",
_ => "UNKNOWN_ET",
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct ProgramHeader {
/// Segment type
pub p_type: u32,
/// Segment flags
pub p_flags: u32,
/// Segment file offset
pub p_offset: u64,
/// Segment virtual address
pub p_vaddr: u64,
/// Segment physical address
pub p_paddr: u64,
/// Segment size in file
pub p_filesz: u64,
/// Segment size in memory
pub p_memsz: u64,
/// Segment alignment
pub p_align: u64,
}
pub const SIZEOF_PHDR: usize = 56;
/// Program header table entry unused
pub const PT_NULL: u32 = 0;
/// Loadable program segment
pub const PT_LOAD: u32 = 1;
/// Dynamic linking information
pub const PT_DYNAMIC: u32 = 2;
/// Program interpreter
pub const PT_INTERP: u32 = 3;
/// Auxiliary information
pub const PT_NOTE: u32 = 4;
/// Reserved
pub const PT_SHLIB: u32 = 5;
/// Entry for header table itself
pub const PT_PHDR: u32 = 6;
/// Thread-local storage segment
pub const PT_TLS: u32 = 7;
/// Number of defined types
pub const PT_NUM: u32 = 8;
/// Start of OS-specific
pub const PT_LOOS: u32 = 0x60000000;
/// GCC.eh_frame_hdr segment
pub const PT_GNU_EH_FRAME: u32 = 0x6474e550;
/// Indicates stack executability
pub const PT_GNU_STACK: u32 = 0x6474e551;
/// Read-only after relocation
pub const PT_GNU_RELRO: u32 = 0x6474e552;
/// Sun Specific segment
pub const PT_LOSUNW: u32 = 0x6ffffffa;
/// Sun Specific segment
pub const PT_SUNWBSS: u32 = 0x6ffffffa;
/// Stack segment
pub const PT_SUNWSTACK: u32 = 0x6ffffffb;
/// End of OS-specific
pub const PT_HISUNW: u32 = 0x6fffffff;
/// End of OS-specific
pub const PT_HIOS: u32 = 0x6fffffff;
/// Start of processor-specific
pub const PT_LOPROC: u32 = 0x70000000;
/// ARM unwind segment
pub const PT_ARM_EXIDX: u32 = 0x70000001;
/// End of processor-specific
pub const PT_HIPROC: u32 = 0x7fffffff;
/// Segment is executable
pub const PF_X: u32 = 1 << 0;
/// Segment is writable
pub const PF_W: u32 = 1 << 1;
/// Segment is readable
pub const PF_R: u32 = 1 << 2;
pub struct ProgramHeaderIter<'a> {
data: &'a [u8],
header: &'a Header,
next: usize
}
pub struct Elf64<'a> {
pub header: &'a Header,
pub data: &'a [u8]
}
impl<'a> Elf64<'a> {
pub unsafe fn from(bytes: &'a [u8]) -> Elf64<'a> {
let h = &*(bytes.as_ptr() as *const Header);
Elf64 {
data: bytes,
header: h,
}
}
pub fn program_headers(&self) -> ProgramHeaderIter<'a> {
ProgramHeaderIter {
data: self.data,
header: self.header,
next: 0
}
}
}
impl<'a> Iterator for ProgramHeaderIter<'a> {
type Item = &'a ProgramHeader;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.header.e_phnum as usize {
let program = unsafe {
&*(self.data.as_ptr().offset(
self.header.e_phoff as isize +
self.header.e_phentsize as isize * self.next as isize)
as *const ProgramHeader)
};
self.next += 1;
Some(program)
} else {
None
}
}
}
| {
write!(f, "e_ident: {:?} e_type: {} e_machine: 0x{:x} e_version: 0x{:x} e_entry: 0x{:x} \
e_phoff: 0x{:x} e_shoff: 0x{:x} e_flags: {:x} e_ehsize: {} e_phentsize: {} \
e_phnum: {} e_shentsize: {} e_shnum: {} e_shstrndx: {}",
self.e_ident,
et_to_str(self.e_type),
self.e_machine,
self.e_version,
self.e_entry,
self.e_phoff,
self.e_shoff,
self.e_flags,
self.e_ehsize,
self.e_phentsize,
self.e_phnum,
self.e_shentsize,
self.e_shnum,
self.e_shstrndx)
} | identifier_body |
stream.rs | use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub struct Stream<P: StreamProducer> {
info: StreamInfo,
metadata: Vec<Metadata>,
producer: P,
}
/// Alias for a FLAC stream produced from `Read`.
pub type StreamReader<R> = Stream<ReadStream<R>>;
/// Alias for a FLAC stream produced from a byte stream buffer.
pub type StreamBuffer<'a> = Stream<ByteStream<'a>>;
impl<P> Stream<P> where P: StreamProducer {
/// Constructor for the default state of a FLAC stream.
#[inline]
pub fn new<R: io::Read>(reader: R) -> Result<StreamReader<R>, ErrorKind> {
let producer = ReadStream::new(reader);
Stream::from_stream_producer(producer)
}
/// Returns information for the current stream.
#[inline]
pub fn info(&self) -> StreamInfo {
self.info
}
/// Returns a slice of `Metadata`
///
/// This slice excludes `StreamInfo`, which is located in `Stream::info`.
/// Everything else is related to metadata for the FLAC stream is in the
/// slice.
#[inline]
pub fn metadata(&self) -> &[Metadata] {
&self.metadata
}
/// Constructs a decoder with the given file name.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::NotFound)` is returned when the given
/// filename isn't found.
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn | (filename: &str) -> Result<StreamReader<File>, ErrorKind> {
File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
.and_then(|file| {
let producer = ReadStream::new(file);
Stream::from_stream_producer(producer)
})
}
/// Constructs a decoder with the given buffer.
///
/// This constructor assumes that an entire FLAC file is in the buffer.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_buffer(buffer: &[u8]) -> Result<StreamBuffer, ErrorKind> {
let producer = ByteStream::new(buffer);
Stream::from_stream_producer(producer)
}
fn from_stream_producer(mut producer: P) -> Result<Self, ErrorKind> {
let mut stream_info = Default::default();
let mut metadata = Vec::new();
many_metadata(&mut producer, |block| {
if let metadata::Data::StreamInfo(info) = block.data {
stream_info = info;
} else {
metadata.push(block);
}
}).map(|_| {
Stream {
info: stream_info,
metadata: metadata,
producer: producer,
}
})
}
/// Returns an iterator over the decoded samples.
#[inline]
pub fn iter<S: SampleSize>(&mut self) -> Iter<P, S::Extended> {
let samples_left = self.info.total_samples;
let channels = self.info.channels as usize;
let block_size = self.info.max_block_size as usize;
let buffer_size = block_size * channels;
Iter {
stream: self,
channel: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
buffer: vec![S::Extended::from_i8(0); buffer_size]
}
}
fn next_frame<S>(&mut self, buffer: &mut [S]) -> Option<usize>
where S: Sample {
let stream_info = &self.info;
loop {
match self.producer.parse(|i| frame_parser(i, stream_info, buffer)) {
Ok(frame) => {
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let subframes = frame.subframes[0..channels].iter();
for (channel, subframe) in subframes.enumerate() {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut buffer[start..end];
subframe::decode(&subframe, block_size, output);
}
frame::decode(frame.header.channel_assignment, buffer);
return Some(block_size);
}
Err(ErrorKind::Continue) => continue,
Err(_) => return None,
}
}
}
}
/// An iterator over a reference of the decoded FLAC stream.
pub struct Iter<'a, P, S>
where P: 'a + StreamProducer,
S: Sample{
stream: &'a mut Stream<P>,
channel: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
buffer: Vec<S>,
}
impl<'a, P, S> Iterator for Iter<'a, P, S>
where P: StreamProducer,
S: Sample {
type Item = S::Normal;
fn next(&mut self) -> Option<Self::Item> {
if self.sample_index == self.block_size {
let buffer = &mut self.buffer;
if let Some(block_size) = self.stream.next_frame(buffer) {
self.sample_index = 0;
self.block_size = block_size;
} else {
return None;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = unsafe { *self.buffer.get_unchecked(index) };
self.channel += 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
self.samples_left -= 1;
}
S::to_normal(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a chance that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
//impl<'a, P, S> IntoIterator for &'a mut Stream<P>
// where P: StreamProducer,
// S: Sample {
// type Item = S::Normal;
// type IntoIter = Iter<'a, P, S>;
//
// #[inline]
// fn into_iter(self) -> Self::IntoIter {
// self.iter()
// }
//}
| from_file | identifier_name |
stream.rs | use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub struct Stream<P: StreamProducer> {
info: StreamInfo,
metadata: Vec<Metadata>,
producer: P,
}
/// Alias for a FLAC stream produced from `Read`.
pub type StreamReader<R> = Stream<ReadStream<R>>;
/// Alias for a FLAC stream produced from a byte stream buffer.
pub type StreamBuffer<'a> = Stream<ByteStream<'a>>;
impl<P> Stream<P> where P: StreamProducer {
/// Constructor for the default state of a FLAC stream.
#[inline]
pub fn new<R: io::Read>(reader: R) -> Result<StreamReader<R>, ErrorKind> |
/// Returns information for the current stream.
#[inline]
pub fn info(&self) -> StreamInfo {
self.info
}
/// Returns a slice of `Metadata`
///
/// This slice excludes `StreamInfo`, which is located in `Stream::info`.
/// Everything else is related to metadata for the FLAC stream is in the
/// slice.
#[inline]
pub fn metadata(&self) -> &[Metadata] {
&self.metadata
}
/// Constructs a decoder with the given file name.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::NotFound)` is returned when the given
/// filename isn't found.
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_file(filename: &str) -> Result<StreamReader<File>, ErrorKind> {
File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
.and_then(|file| {
let producer = ReadStream::new(file);
Stream::from_stream_producer(producer)
})
}
/// Constructs a decoder with the given buffer.
///
/// This constructor assumes that an entire FLAC file is in the buffer.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_buffer(buffer: &[u8]) -> Result<StreamBuffer, ErrorKind> {
let producer = ByteStream::new(buffer);
Stream::from_stream_producer(producer)
}
fn from_stream_producer(mut producer: P) -> Result<Self, ErrorKind> {
let mut stream_info = Default::default();
let mut metadata = Vec::new();
many_metadata(&mut producer, |block| {
if let metadata::Data::StreamInfo(info) = block.data {
stream_info = info;
} else {
metadata.push(block);
}
}).map(|_| {
Stream {
info: stream_info,
metadata: metadata,
producer: producer,
}
})
}
/// Returns an iterator over the decoded samples.
#[inline]
pub fn iter<S: SampleSize>(&mut self) -> Iter<P, S::Extended> {
let samples_left = self.info.total_samples;
let channels = self.info.channels as usize;
let block_size = self.info.max_block_size as usize;
let buffer_size = block_size * channels;
Iter {
stream: self,
channel: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
buffer: vec![S::Extended::from_i8(0); buffer_size]
}
}
fn next_frame<S>(&mut self, buffer: &mut [S]) -> Option<usize>
where S: Sample {
let stream_info = &self.info;
loop {
match self.producer.parse(|i| frame_parser(i, stream_info, buffer)) {
Ok(frame) => {
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let subframes = frame.subframes[0..channels].iter();
for (channel, subframe) in subframes.enumerate() {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut buffer[start..end];
subframe::decode(&subframe, block_size, output);
}
frame::decode(frame.header.channel_assignment, buffer);
return Some(block_size);
}
Err(ErrorKind::Continue) => continue,
Err(_) => return None,
}
}
}
}
/// An iterator over a reference of the decoded FLAC stream.
pub struct Iter<'a, P, S>
where P: 'a + StreamProducer,
S: Sample{
stream: &'a mut Stream<P>,
channel: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
buffer: Vec<S>,
}
impl<'a, P, S> Iterator for Iter<'a, P, S>
where P: StreamProducer,
S: Sample {
type Item = S::Normal;
fn next(&mut self) -> Option<Self::Item> {
if self.sample_index == self.block_size {
let buffer = &mut self.buffer;
if let Some(block_size) = self.stream.next_frame(buffer) {
self.sample_index = 0;
self.block_size = block_size;
} else {
return None;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = unsafe { *self.buffer.get_unchecked(index) };
self.channel += 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
self.samples_left -= 1;
}
S::to_normal(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a chance that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
//impl<'a, P, S> IntoIterator for &'a mut Stream<P>
// where P: StreamProducer,
// S: Sample {
// type Item = S::Normal;
// type IntoIter = Iter<'a, P, S>;
//
// #[inline]
// fn into_iter(self) -> Self::IntoIter {
// self.iter()
// }
//}
| {
let producer = ReadStream::new(reader);
Stream::from_stream_producer(producer)
} | identifier_body |
stream.rs | use metadata;
use frame;
use subframe;
use metadata::{Metadata, StreamInfo};
use frame::frame_parser;
use utility::{
ErrorKind, ByteStream, ReadStream, Sample, SampleSize, StreamProducer,
many_metadata,
};
use std::io;
use std::usize;
use std::fs::File;
/// FLAC stream that decodes and hold file information.
pub struct Stream<P: StreamProducer> {
info: StreamInfo,
metadata: Vec<Metadata>,
producer: P,
}
/// Alias for a FLAC stream produced from `Read`.
pub type StreamReader<R> = Stream<ReadStream<R>>;
/// Alias for a FLAC stream produced from a byte stream buffer.
pub type StreamBuffer<'a> = Stream<ByteStream<'a>>;
impl<P> Stream<P> where P: StreamProducer {
/// Constructor for the default state of a FLAC stream.
#[inline]
pub fn new<R: io::Read>(reader: R) -> Result<StreamReader<R>, ErrorKind> {
let producer = ReadStream::new(reader);
Stream::from_stream_producer(producer)
}
/// Returns information for the current stream.
#[inline]
pub fn info(&self) -> StreamInfo {
self.info
}
/// Returns a slice of `Metadata`
///
/// This slice excludes `StreamInfo`, which is located in `Stream::info`.
/// Everything else is related to metadata for the FLAC stream is in the
/// slice.
#[inline]
pub fn metadata(&self) -> &[Metadata] {
&self.metadata
}
/// Constructs a decoder with the given file name.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::NotFound)` is returned when the given
/// filename isn't found.
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_file(filename: &str) -> Result<StreamReader<File>, ErrorKind> {
File::open(filename).map_err(|e| ErrorKind::IO(e.kind()))
.and_then(|file| {
let producer = ReadStream::new(file);
Stream::from_stream_producer(producer)
})
}
/// Constructs a decoder with the given buffer.
///
/// This constructor assumes that an entire FLAC file is in the buffer.
///
/// # Failures
///
/// * `ErrorKind::IO(io::ErrorKind::InvalidData)` is returned when the data
/// within the file isn't valid FLAC data.
/// * Several different parser specific errors that are structured as
/// `ErrorKind::<parser_name>Parser`.
/// * Several different invalidation specific errors that are
/// structured as `ErrorKind::Invalid<invalidation_name>`.
#[inline]
pub fn from_buffer(buffer: &[u8]) -> Result<StreamBuffer, ErrorKind> {
let producer = ByteStream::new(buffer);
Stream::from_stream_producer(producer)
}
fn from_stream_producer(mut producer: P) -> Result<Self, ErrorKind> {
let mut stream_info = Default::default();
let mut metadata = Vec::new(); | stream_info = info;
} else {
metadata.push(block);
}
}).map(|_| {
Stream {
info: stream_info,
metadata: metadata,
producer: producer,
}
})
}
/// Returns an iterator over the decoded samples.
#[inline]
pub fn iter<S: SampleSize>(&mut self) -> Iter<P, S::Extended> {
let samples_left = self.info.total_samples;
let channels = self.info.channels as usize;
let block_size = self.info.max_block_size as usize;
let buffer_size = block_size * channels;
Iter {
stream: self,
channel: 0,
block_size: 0,
sample_index: 0,
samples_left: samples_left,
buffer: vec![S::Extended::from_i8(0); buffer_size]
}
}
fn next_frame<S>(&mut self, buffer: &mut [S]) -> Option<usize>
where S: Sample {
let stream_info = &self.info;
loop {
match self.producer.parse(|i| frame_parser(i, stream_info, buffer)) {
Ok(frame) => {
let channels = frame.header.channels as usize;
let block_size = frame.header.block_size as usize;
let subframes = frame.subframes[0..channels].iter();
for (channel, subframe) in subframes.enumerate() {
let start = channel * block_size;
let end = (channel + 1) * block_size;
let output = &mut buffer[start..end];
subframe::decode(&subframe, block_size, output);
}
frame::decode(frame.header.channel_assignment, buffer);
return Some(block_size);
}
Err(ErrorKind::Continue) => continue,
Err(_) => return None,
}
}
}
}
/// An iterator over a reference of the decoded FLAC stream.
pub struct Iter<'a, P, S>
where P: 'a + StreamProducer,
S: Sample{
stream: &'a mut Stream<P>,
channel: usize,
block_size: usize,
sample_index: usize,
samples_left: u64,
buffer: Vec<S>,
}
impl<'a, P, S> Iterator for Iter<'a, P, S>
where P: StreamProducer,
S: Sample {
type Item = S::Normal;
fn next(&mut self) -> Option<Self::Item> {
if self.sample_index == self.block_size {
let buffer = &mut self.buffer;
if let Some(block_size) = self.stream.next_frame(buffer) {
self.sample_index = 0;
self.block_size = block_size;
} else {
return None;
}
}
let channels = self.stream.info.channels as usize;
let index = self.sample_index + (self.channel * self.block_size);
let sample = unsafe { *self.buffer.get_unchecked(index) };
self.channel += 1;
// Reset current channel
if self.channel == channels {
self.channel = 0;
self.sample_index += 1;
self.samples_left -= 1;
}
S::to_normal(sample)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let samples_left = self.samples_left as usize;
let max_value = usize::max_value() as u64;
// There is a chance that samples_left will be larger than a usize since
// it is a u64. Make the upper bound None when it is.
if self.samples_left > max_value {
(samples_left, None)
} else {
(samples_left, Some(samples_left))
}
}
}
//impl<'a, P, S> IntoIterator for &'a mut Stream<P>
// where P: StreamProducer,
// S: Sample {
// type Item = S::Normal;
// type IntoIter = Iter<'a, P, S>;
//
// #[inline]
// fn into_iter(self) -> Self::IntoIter {
// self.iter()
// }
//} |
many_metadata(&mut producer, |block| {
if let metadata::Data::StreamInfo(info) = block.data { | random_line_split |
glutin.rs | use glium::{
Frame,
IndexBuffer,
Surface,
VertexBuffer,
glutin,
program,
texture,
};
use glium::index::PrimitiveType;
use glium::backend::glutin_backend::GlutinFacade;
use super::super::gamestate::*;
use super::sound::{
Player,
PortAudio,
};
#[derive(Copy, Clone)]
// Non-snake case names mandated by shaders
#[allow(non_snake_case)]
struct Vertex {
InVertex: [f32; 3],
InTexCoord0: [f32; 2]
}
implement_vertex!(Vertex, InVertex, InTexCoord0);
// clockwise order
const SQUARE_VERTICES: [Vertex; 4] = [
Vertex {
InVertex: [ 0.5f32, 0.5f32, 0.0f32],
InTexCoord0: [1.0f32, 1.0f32]
},
Vertex {
InVertex: [ 0.5f32,-0.5f32, 0.0f32],
InTexCoord0: [1.0f32, 0.0f32]
},
Vertex {
InVertex: [-0.5f32,-0.5f32, 0.0f32],
InTexCoord0: [0.0f32, 0.0f32]
},
Vertex {
InVertex: [-0.5f32, 0.5f32, 0.0f32],
InTexCoord0: [0.0f32, 1.0f32]
},
];
const SQUARE_INDICES: [u16; 6] = [
0,3,1,
2,1,3
];
/// Runs tetris in a GL context managed by the glium library
pub fn run_tetris() {
use super::RenderData;
use glium::DisplayBuild;
use std::sync::{Arc,Mutex,MutexGuard};
use std::cell::Ref;
use std::convert::From;
const WIDTH: u32 = 400;
const HEIGHT: u32 = 800;
let display = glutin::WindowBuilder::new()
.with_dimensions(WIDTH, HEIGHT)
.build_glium()
.unwrap();
let vertex_buffer = VertexBuffer::new(&display, &SQUARE_VERTICES).unwrap();
let index_buffer = IndexBuffer::new(&display, PrimitiveType::TrianglesList, &SQUARE_INDICES).unwrap();
let program = load_shaders(&display).unwrap();
let image = gen_image();
let texture = texture::Texture2d::new(&display, image).unwrap();
let data_mutex: Arc<Mutex<Option<RenderData>>> = Arc::new(Mutex::new(None));
let mut game: game::Game;
{
let data_mutex = data_mutex.clone();
let callback = move |field: Ref<field::Field>, current: &piece::Piece, ghost: Option<&piece::Piece>| {
let new_data = RenderData {
current: From::from(current),
field: field.clone(),
ghost: match ghost {
Some(piece) => Some(From::from(piece)),
None => None
},
};
let mut data: MutexGuard<Option<super::RenderData>> = data_mutex.lock().unwrap();
*data = Some(new_data);
};
game = game::Game::new(Box::new(callback));
}
game.run().unwrap();
let pa = PortAudio::new().unwrap();
let mut player = Player::new();
player.start_music(&pa).unwrap();
loop {
for ev in display.poll_events() {
match ev {
glutin::Event::Closed => return,
glutin::Event::KeyboardInput(state, byte, opt) => key_input(&mut game, &pa, &mut player, state, byte, opt),
_ => ()
}
}
let data_opt: Option<RenderData> = data_mutex.lock().unwrap().clone();
if let Some(data) = data_opt {
draw_frame(&display, data, &vertex_buffer, &index_buffer, &program, &texture);
}
if game.is_game_over() {
player.reset_music().unwrap();
}
}
}
fn load_shaders(display: &GlutinFacade) -> Result<program::Program, program::ProgramCreationError> {
use std::fs::*;
use std::io::Read;
use std::path::Path;
const VERT_PATH: &'static str = "shaders/simple.vert";
const FRAG_PATH: &'static str = "shaders/default.frag";
const PROJECT_ROOT: &'static str = "../../";
let vert_path = Path::new(PROJECT_ROOT).join(Path::new(VERT_PATH));
let frag_path = Path::new(PROJECT_ROOT).join(Path::new( FRAG_PATH));
let mut vertex_file: File = File::open(vert_path.clone()).expect(&format!("couldn't open {:?}", vert_path));
let mut frag_file: File = File::open(frag_path.clone()).expect(&format!("couldn't open {:?}", frag_path));
let mut vertex_str = String::new();
let mut frag_str = String::new();
vertex_file.read_to_string(&mut vertex_str).expect(&format!("couldn't read vertex_file {:?}", vertex_file));
frag_file.read_to_string(&mut frag_str).expect(&format!("couldn't read frag_file {:?}", frag_file));
program::Program::from_source(display, &vertex_str, &frag_str, None)
}
fn draw_block<V:Copy>(target: &mut Frame,
v_buff: &VertexBuffer<V>, i_buff: &IndexBuffer<u16>,
program: &program::Program,
offset: (f32, f32), color: (f32, f32, f32, f32), tex: &texture::Texture2d) -> ()
{
let uniforms = uniform! {
offset: offset,
tint: color,
msampler: tex,
};
target.draw(v_buff, i_buff, program, &uniforms, &Default::default()).unwrap();
}
fn draw_frame<V: Copy>(display: &GlutinFacade,
data: super::RenderData,
v_buff: &VertexBuffer<V>, i_buff: &IndexBuffer<u16>,
program: &program::Program,
tex: &texture::Texture2d) -> ()
{
use super::super::gamestate::field;
use super::super::gamestate::piece::Type;
use super::super::gamestate::Coord;
//const WHITE_COLOR: (f32, f32, f32, f32) = (1.0f32, 1.0f32, 1.0f32, 1.0f32);
const GREY_COLOR: (f32, f32, f32, f32) = (0.6f32, 0.6f32, 0.6f32, 0.6f32);
const I_COLOR: (f32, f32, f32, f32) = (1.0f32, 0.0f32, 0.0f32, 1.0f32);
const J_COLOR: (f32, f32, f32, f32) = (0.0f32, 1.0f32, 0.0f32, 1.0f32);
const L_COLOR: (f32, f32, f32, f32) = (0.0f32, 0.0f32, 1.0f32, 1.0f32);
const O_COLOR: (f32, f32, f32, f32) = (1.0f32, 1.0f32, 0.0f32, 1.0f32);
const S_COLOR: (f32, f32, f32, f32) = (1.0f32, 0.0f32, 1.0f32, 1.0f32);
const T_COLOR: (f32, f32, f32, f32) = (0.0f32, 1.0f32, 1.0f32, 1.0f32);
const Z_COLOR: (f32, f32, f32, f32) = (0.5f32, 1.0f32, 0.5f32, 1.0f32);
let mut frame: Frame = display.draw();
frame.clear_color(0.0, 0.0, 0.0, 1.0);
// Draw blocks in field
for i in 0..field::WIDTH {
for j in 0..field::HEIGHT {
if data.field.get(Coord::new(i as i32, j as i32)).unwrap() {
draw_block(&mut frame, v_buff, i_buff, program,
(i as f32, j as f32),
GREY_COLOR, tex);
}
}
}
// Draw current piece
let color = match data.current.typ {
Type::I => I_COLOR,
Type::J => J_COLOR,
Type::L => L_COLOR,
Type::O => O_COLOR,
Type::S => S_COLOR,
Type::T => T_COLOR,
Type::Z => Z_COLOR
};
for block in &data.current.blocks {
draw_block(&mut frame, v_buff, i_buff, program,
(block.x as f32, block.y as f32),
color, tex);
}
frame.finish().unwrap();
}
fn | () -> texture::RawImage2d<'static, (f32, f32, f32)> {
use std::cmp::min;
use std::mem;
use glium::texture::ClientFormat;
const TEXDIMENSION: u32 = 256;
const TEXBUFFSIZE: usize = (TEXDIMENSION*TEXDIMENSION) as usize;
let mut raw_data: Vec<(f32, f32, f32)> = Vec::new();
for i in 0..TEXDIMENSION {
for j in 0..TEXDIMENSION {
let idist = min(TEXDIMENSION-i, i);
let jdist = min(TEXDIMENSION-j, j);
let dist = min(idist, jdist);
let value: f32 = (dist as f32) / (TEXDIMENSION as f32) + 0.5f32;
raw_data.push((value, value, value));
}
}
assert_eq!(raw_data.len(), TEXBUFFSIZE);
let mut image = texture::RawImage2d::from_raw_rgb(raw_data, (TEXDIMENSION, TEXDIMENSION));
match image.format {
ClientFormat::F32F32F32 => (),
_ => {
println!("correcting wrong format: {:?}", image.format);
image.format = ClientFormat::F32F32F32;
}
}
assert!(image.data.len() == image.width as usize * image.height as usize * image.format.get_size() / mem::size_of::<(f32, f32, f32)>(),
"size mismatch: len {:?}, width {:?}, height {:?}, get_size() {:?}, size_of {:?}",
image.data.len(), image.width, image.height, image.format.get_size(), mem::size_of::<(f32, f32, f32)>());
image
}
fn key_input<'pa>(game: &mut game::Game, pa: &'pa PortAudio, player: &mut Player<'pa>, state: glutin::ElementState, _: u8, opt: Option<glutin::VirtualKeyCode>) -> () {
use glium::glutin::VirtualKeyCode;
use gamestate::piece::Input;
let input: Option<Input>;
if state == glutin::ElementState::Pressed {
if let Some(code) = opt {
input = match code {
VirtualKeyCode::Down => Some(Input::HardDrop),
VirtualKeyCode::E => Some(Input::RotateCW),
VirtualKeyCode::Left => Some(Input::ShiftLeft),
VirtualKeyCode::Q => Some(Input::RotateCCW),
VirtualKeyCode::Return => Some(Input::HardDrop),
VirtualKeyCode::Right => Some(Input::ShiftRight),
VirtualKeyCode::P => {
game.pause().or_else(|_|{game.run()}).expect("If pause fails run should always succeed");
player.toggle_play_music(pa).unwrap();
None
},
_ => None
}
} else {
input = None;
}
} else {
input = None;
}
if let Some(input) = input {
let _ = game.queue_input(input);
}
}
| gen_image | identifier_name |
glutin.rs | use glium::{
Frame,
IndexBuffer,
Surface,
VertexBuffer,
glutin,
program,
texture,
};
use glium::index::PrimitiveType;
use glium::backend::glutin_backend::GlutinFacade;
use super::super::gamestate::*;
use super::sound::{
Player,
PortAudio,
};
#[derive(Copy, Clone)]
// Non-snake case names mandated by shaders
#[allow(non_snake_case)]
struct Vertex {
InVertex: [f32; 3],
InTexCoord0: [f32; 2]
}
implement_vertex!(Vertex, InVertex, InTexCoord0);
// clockwise order
const SQUARE_VERTICES: [Vertex; 4] = [
Vertex {
InVertex: [ 0.5f32, 0.5f32, 0.0f32],
InTexCoord0: [1.0f32, 1.0f32]
},
Vertex {
InVertex: [ 0.5f32,-0.5f32, 0.0f32],
InTexCoord0: [1.0f32, 0.0f32]
},
Vertex {
InVertex: [-0.5f32,-0.5f32, 0.0f32],
InTexCoord0: [0.0f32, 0.0f32]
},
Vertex {
InVertex: [-0.5f32, 0.5f32, 0.0f32],
InTexCoord0: [0.0f32, 1.0f32]
},
];
const SQUARE_INDICES: [u16; 6] = [
0,3,1,
2,1,3
];
/// Runs tetris in a GL context managed by the glium library
pub fn run_tetris() {
use super::RenderData;
use glium::DisplayBuild;
use std::sync::{Arc,Mutex,MutexGuard};
use std::cell::Ref;
use std::convert::From;
const WIDTH: u32 = 400;
const HEIGHT: u32 = 800;
let display = glutin::WindowBuilder::new()
.with_dimensions(WIDTH, HEIGHT)
.build_glium()
.unwrap();
let vertex_buffer = VertexBuffer::new(&display, &SQUARE_VERTICES).unwrap();
let index_buffer = IndexBuffer::new(&display, PrimitiveType::TrianglesList, &SQUARE_INDICES).unwrap();
let program = load_shaders(&display).unwrap();
let image = gen_image();
let texture = texture::Texture2d::new(&display, image).unwrap();
let data_mutex: Arc<Mutex<Option<RenderData>>> = Arc::new(Mutex::new(None));
let mut game: game::Game;
{
let data_mutex = data_mutex.clone();
let callback = move |field: Ref<field::Field>, current: &piece::Piece, ghost: Option<&piece::Piece>| {
let new_data = RenderData {
current: From::from(current),
field: field.clone(),
ghost: match ghost {
Some(piece) => Some(From::from(piece)),
None => None
},
};
let mut data: MutexGuard<Option<super::RenderData>> = data_mutex.lock().unwrap();
*data = Some(new_data);
};
game = game::Game::new(Box::new(callback));
}
game.run().unwrap();
let pa = PortAudio::new().unwrap();
let mut player = Player::new();
player.start_music(&pa).unwrap();
loop {
for ev in display.poll_events() {
match ev {
glutin::Event::Closed => return,
glutin::Event::KeyboardInput(state, byte, opt) => key_input(&mut game, &pa, &mut player, state, byte, opt),
_ => ()
}
}
let data_opt: Option<RenderData> = data_mutex.lock().unwrap().clone();
if let Some(data) = data_opt {
draw_frame(&display, data, &vertex_buffer, &index_buffer, &program, &texture);
}
if game.is_game_over() {
player.reset_music().unwrap();
}
}
}
fn load_shaders(display: &GlutinFacade) -> Result<program::Program, program::ProgramCreationError> {
use std::fs::*;
use std::io::Read;
use std::path::Path;
const VERT_PATH: &'static str = "shaders/simple.vert";
const FRAG_PATH: &'static str = "shaders/default.frag";
const PROJECT_ROOT: &'static str = "../../";
let vert_path = Path::new(PROJECT_ROOT).join(Path::new(VERT_PATH));
let frag_path = Path::new(PROJECT_ROOT).join(Path::new( FRAG_PATH));
let mut vertex_file: File = File::open(vert_path.clone()).expect(&format!("couldn't open {:?}", vert_path));
let mut frag_file: File = File::open(frag_path.clone()).expect(&format!("couldn't open {:?}", frag_path));
let mut vertex_str = String::new();
let mut frag_str = String::new();
vertex_file.read_to_string(&mut vertex_str).expect(&format!("couldn't read vertex_file {:?}", vertex_file));
frag_file.read_to_string(&mut frag_str).expect(&format!("couldn't read frag_file {:?}", frag_file));
program::Program::from_source(display, &vertex_str, &frag_str, None)
}
fn draw_block<V:Copy>(target: &mut Frame,
v_buff: &VertexBuffer<V>, i_buff: &IndexBuffer<u16>,
program: &program::Program,
offset: (f32, f32), color: (f32, f32, f32, f32), tex: &texture::Texture2d) -> ()
{
let uniforms = uniform! {
offset: offset,
tint: color,
msampler: tex,
};
target.draw(v_buff, i_buff, program, &uniforms, &Default::default()).unwrap();
}
fn draw_frame<V: Copy>(display: &GlutinFacade,
data: super::RenderData,
v_buff: &VertexBuffer<V>, i_buff: &IndexBuffer<u16>,
program: &program::Program,
tex: &texture::Texture2d) -> ()
{
use super::super::gamestate::field;
use super::super::gamestate::piece::Type;
use super::super::gamestate::Coord;
//const WHITE_COLOR: (f32, f32, f32, f32) = (1.0f32, 1.0f32, 1.0f32, 1.0f32);
const GREY_COLOR: (f32, f32, f32, f32) = (0.6f32, 0.6f32, 0.6f32, 0.6f32);
const I_COLOR: (f32, f32, f32, f32) = (1.0f32, 0.0f32, 0.0f32, 1.0f32);
const J_COLOR: (f32, f32, f32, f32) = (0.0f32, 1.0f32, 0.0f32, 1.0f32);
const L_COLOR: (f32, f32, f32, f32) = (0.0f32, 0.0f32, 1.0f32, 1.0f32);
const O_COLOR: (f32, f32, f32, f32) = (1.0f32, 1.0f32, 0.0f32, 1.0f32);
const S_COLOR: (f32, f32, f32, f32) = (1.0f32, 0.0f32, 1.0f32, 1.0f32);
const T_COLOR: (f32, f32, f32, f32) = (0.0f32, 1.0f32, 1.0f32, 1.0f32);
const Z_COLOR: (f32, f32, f32, f32) = (0.5f32, 1.0f32, 0.5f32, 1.0f32);
let mut frame: Frame = display.draw();
frame.clear_color(0.0, 0.0, 0.0, 1.0);
// Draw blocks in field
for i in 0..field::WIDTH {
for j in 0..field::HEIGHT {
if data.field.get(Coord::new(i as i32, j as i32)).unwrap() {
draw_block(&mut frame, v_buff, i_buff, program,
(i as f32, j as f32),
GREY_COLOR, tex);
}
}
}
// Draw current piece
let color = match data.current.typ {
Type::I => I_COLOR,
Type::J => J_COLOR,
Type::L => L_COLOR,
Type::O => O_COLOR,
Type::S => S_COLOR,
Type::T => T_COLOR,
Type::Z => Z_COLOR
};
for block in &data.current.blocks {
draw_block(&mut frame, v_buff, i_buff, program,
(block.x as f32, block.y as f32),
color, tex);
}
frame.finish().unwrap();
}
fn gen_image() -> texture::RawImage2d<'static, (f32, f32, f32)> {
use std::cmp::min;
use std::mem;
use glium::texture::ClientFormat;
const TEXDIMENSION: u32 = 256;
const TEXBUFFSIZE: usize = (TEXDIMENSION*TEXDIMENSION) as usize;
let mut raw_data: Vec<(f32, f32, f32)> = Vec::new();
for i in 0..TEXDIMENSION {
for j in 0..TEXDIMENSION {
let idist = min(TEXDIMENSION-i, i);
let jdist = min(TEXDIMENSION-j, j);
let dist = min(idist, jdist);
let value: f32 = (dist as f32) / (TEXDIMENSION as f32) + 0.5f32;
raw_data.push((value, value, value));
}
}
assert_eq!(raw_data.len(), TEXBUFFSIZE);
let mut image = texture::RawImage2d::from_raw_rgb(raw_data, (TEXDIMENSION, TEXDIMENSION));
match image.format {
ClientFormat::F32F32F32 => (),
_ => |
}
assert!(image.data.len() == image.width as usize * image.height as usize * image.format.get_size() / mem::size_of::<(f32, f32, f32)>(),
"size mismatch: len {:?}, width {:?}, height {:?}, get_size() {:?}, size_of {:?}",
image.data.len(), image.width, image.height, image.format.get_size(), mem::size_of::<(f32, f32, f32)>());
image
}
fn key_input<'pa>(game: &mut game::Game, pa: &'pa PortAudio, player: &mut Player<'pa>, state: glutin::ElementState, _: u8, opt: Option<glutin::VirtualKeyCode>) -> () {
use glium::glutin::VirtualKeyCode;
use gamestate::piece::Input;
let input: Option<Input>;
if state == glutin::ElementState::Pressed {
if let Some(code) = opt {
input = match code {
VirtualKeyCode::Down => Some(Input::HardDrop),
VirtualKeyCode::E => Some(Input::RotateCW),
VirtualKeyCode::Left => Some(Input::ShiftLeft),
VirtualKeyCode::Q => Some(Input::RotateCCW),
VirtualKeyCode::Return => Some(Input::HardDrop),
VirtualKeyCode::Right => Some(Input::ShiftRight),
VirtualKeyCode::P => {
game.pause().or_else(|_|{game.run()}).expect("If pause fails run should always succeed");
player.toggle_play_music(pa).unwrap();
None
},
_ => None
}
} else {
input = None;
}
} else {
input = None;
}
if let Some(input) = input {
let _ = game.queue_input(input);
}
}
| {
println!("correcting wrong format: {:?}", image.format);
image.format = ClientFormat::F32F32F32;
} | conditional_block |
glutin.rs | use glium::{
Frame,
IndexBuffer,
Surface,
VertexBuffer,
glutin,
program,
texture,
};
use glium::index::PrimitiveType;
use glium::backend::glutin_backend::GlutinFacade;
use super::super::gamestate::*;
use super::sound::{
Player,
PortAudio,
};
#[derive(Copy, Clone)]
// Non-snake case names mandated by shaders
#[allow(non_snake_case)]
struct Vertex {
InVertex: [f32; 3],
InTexCoord0: [f32; 2]
}
implement_vertex!(Vertex, InVertex, InTexCoord0);
// clockwise order
const SQUARE_VERTICES: [Vertex; 4] = [
Vertex {
InVertex: [ 0.5f32, 0.5f32, 0.0f32],
InTexCoord0: [1.0f32, 1.0f32]
},
Vertex {
InVertex: [ 0.5f32,-0.5f32, 0.0f32],
InTexCoord0: [1.0f32, 0.0f32]
},
Vertex {
InVertex: [-0.5f32,-0.5f32, 0.0f32],
InTexCoord0: [0.0f32, 0.0f32]
},
Vertex {
InVertex: [-0.5f32, 0.5f32, 0.0f32],
InTexCoord0: [0.0f32, 1.0f32]
},
];
const SQUARE_INDICES: [u16; 6] = [
0,3,1,
2,1,3
];
/// Runs tetris in a GL context managed by the glium library
pub fn run_tetris() {
use super::RenderData;
use glium::DisplayBuild;
use std::sync::{Arc,Mutex,MutexGuard};
use std::cell::Ref;
use std::convert::From;
const WIDTH: u32 = 400;
const HEIGHT: u32 = 800;
let display = glutin::WindowBuilder::new()
.with_dimensions(WIDTH, HEIGHT)
.build_glium()
.unwrap();
let vertex_buffer = VertexBuffer::new(&display, &SQUARE_VERTICES).unwrap();
let index_buffer = IndexBuffer::new(&display, PrimitiveType::TrianglesList, &SQUARE_INDICES).unwrap();
let program = load_shaders(&display).unwrap(); | {
let data_mutex = data_mutex.clone();
let callback = move |field: Ref<field::Field>, current: &piece::Piece, ghost: Option<&piece::Piece>| {
let new_data = RenderData {
current: From::from(current),
field: field.clone(),
ghost: match ghost {
Some(piece) => Some(From::from(piece)),
None => None
},
};
let mut data: MutexGuard<Option<super::RenderData>> = data_mutex.lock().unwrap();
*data = Some(new_data);
};
game = game::Game::new(Box::new(callback));
}
game.run().unwrap();
let pa = PortAudio::new().unwrap();
let mut player = Player::new();
player.start_music(&pa).unwrap();
loop {
for ev in display.poll_events() {
match ev {
glutin::Event::Closed => return,
glutin::Event::KeyboardInput(state, byte, opt) => key_input(&mut game, &pa, &mut player, state, byte, opt),
_ => ()
}
}
let data_opt: Option<RenderData> = data_mutex.lock().unwrap().clone();
if let Some(data) = data_opt {
draw_frame(&display, data, &vertex_buffer, &index_buffer, &program, &texture);
}
if game.is_game_over() {
player.reset_music().unwrap();
}
}
}
fn load_shaders(display: &GlutinFacade) -> Result<program::Program, program::ProgramCreationError> {
use std::fs::*;
use std::io::Read;
use std::path::Path;
const VERT_PATH: &'static str = "shaders/simple.vert";
const FRAG_PATH: &'static str = "shaders/default.frag";
const PROJECT_ROOT: &'static str = "../../";
let vert_path = Path::new(PROJECT_ROOT).join(Path::new(VERT_PATH));
let frag_path = Path::new(PROJECT_ROOT).join(Path::new( FRAG_PATH));
let mut vertex_file: File = File::open(vert_path.clone()).expect(&format!("couldn't open {:?}", vert_path));
let mut frag_file: File = File::open(frag_path.clone()).expect(&format!("couldn't open {:?}", frag_path));
let mut vertex_str = String::new();
let mut frag_str = String::new();
vertex_file.read_to_string(&mut vertex_str).expect(&format!("couldn't read vertex_file {:?}", vertex_file));
frag_file.read_to_string(&mut frag_str).expect(&format!("couldn't read frag_file {:?}", frag_file));
program::Program::from_source(display, &vertex_str, &frag_str, None)
}
fn draw_block<V:Copy>(target: &mut Frame,
v_buff: &VertexBuffer<V>, i_buff: &IndexBuffer<u16>,
program: &program::Program,
offset: (f32, f32), color: (f32, f32, f32, f32), tex: &texture::Texture2d) -> ()
{
let uniforms = uniform! {
offset: offset,
tint: color,
msampler: tex,
};
target.draw(v_buff, i_buff, program, &uniforms, &Default::default()).unwrap();
}
fn draw_frame<V: Copy>(display: &GlutinFacade,
data: super::RenderData,
v_buff: &VertexBuffer<V>, i_buff: &IndexBuffer<u16>,
program: &program::Program,
tex: &texture::Texture2d) -> ()
{
use super::super::gamestate::field;
use super::super::gamestate::piece::Type;
use super::super::gamestate::Coord;
//const WHITE_COLOR: (f32, f32, f32, f32) = (1.0f32, 1.0f32, 1.0f32, 1.0f32);
const GREY_COLOR: (f32, f32, f32, f32) = (0.6f32, 0.6f32, 0.6f32, 0.6f32);
const I_COLOR: (f32, f32, f32, f32) = (1.0f32, 0.0f32, 0.0f32, 1.0f32);
const J_COLOR: (f32, f32, f32, f32) = (0.0f32, 1.0f32, 0.0f32, 1.0f32);
const L_COLOR: (f32, f32, f32, f32) = (0.0f32, 0.0f32, 1.0f32, 1.0f32);
const O_COLOR: (f32, f32, f32, f32) = (1.0f32, 1.0f32, 0.0f32, 1.0f32);
const S_COLOR: (f32, f32, f32, f32) = (1.0f32, 0.0f32, 1.0f32, 1.0f32);
const T_COLOR: (f32, f32, f32, f32) = (0.0f32, 1.0f32, 1.0f32, 1.0f32);
const Z_COLOR: (f32, f32, f32, f32) = (0.5f32, 1.0f32, 0.5f32, 1.0f32);
let mut frame: Frame = display.draw();
frame.clear_color(0.0, 0.0, 0.0, 1.0);
// Draw blocks in field
for i in 0..field::WIDTH {
for j in 0..field::HEIGHT {
if data.field.get(Coord::new(i as i32, j as i32)).unwrap() {
draw_block(&mut frame, v_buff, i_buff, program,
(i as f32, j as f32),
GREY_COLOR, tex);
}
}
}
// Draw current piece
let color = match data.current.typ {
Type::I => I_COLOR,
Type::J => J_COLOR,
Type::L => L_COLOR,
Type::O => O_COLOR,
Type::S => S_COLOR,
Type::T => T_COLOR,
Type::Z => Z_COLOR
};
for block in &data.current.blocks {
draw_block(&mut frame, v_buff, i_buff, program,
(block.x as f32, block.y as f32),
color, tex);
}
frame.finish().unwrap();
}
fn gen_image() -> texture::RawImage2d<'static, (f32, f32, f32)> {
use std::cmp::min;
use std::mem;
use glium::texture::ClientFormat;
const TEXDIMENSION: u32 = 256;
const TEXBUFFSIZE: usize = (TEXDIMENSION*TEXDIMENSION) as usize;
let mut raw_data: Vec<(f32, f32, f32)> = Vec::new();
for i in 0..TEXDIMENSION {
for j in 0..TEXDIMENSION {
let idist = min(TEXDIMENSION-i, i);
let jdist = min(TEXDIMENSION-j, j);
let dist = min(idist, jdist);
let value: f32 = (dist as f32) / (TEXDIMENSION as f32) + 0.5f32;
raw_data.push((value, value, value));
}
}
assert_eq!(raw_data.len(), TEXBUFFSIZE);
let mut image = texture::RawImage2d::from_raw_rgb(raw_data, (TEXDIMENSION, TEXDIMENSION));
match image.format {
ClientFormat::F32F32F32 => (),
_ => {
println!("correcting wrong format: {:?}", image.format);
image.format = ClientFormat::F32F32F32;
}
}
assert!(image.data.len() == image.width as usize * image.height as usize * image.format.get_size() / mem::size_of::<(f32, f32, f32)>(),
"size mismatch: len {:?}, width {:?}, height {:?}, get_size() {:?}, size_of {:?}",
image.data.len(), image.width, image.height, image.format.get_size(), mem::size_of::<(f32, f32, f32)>());
image
}
fn key_input<'pa>(game: &mut game::Game, pa: &'pa PortAudio, player: &mut Player<'pa>, state: glutin::ElementState, _: u8, opt: Option<glutin::VirtualKeyCode>) -> () {
use glium::glutin::VirtualKeyCode;
use gamestate::piece::Input;
let input: Option<Input>;
if state == glutin::ElementState::Pressed {
if let Some(code) = opt {
input = match code {
VirtualKeyCode::Down => Some(Input::HardDrop),
VirtualKeyCode::E => Some(Input::RotateCW),
VirtualKeyCode::Left => Some(Input::ShiftLeft),
VirtualKeyCode::Q => Some(Input::RotateCCW),
VirtualKeyCode::Return => Some(Input::HardDrop),
VirtualKeyCode::Right => Some(Input::ShiftRight),
VirtualKeyCode::P => {
game.pause().or_else(|_|{game.run()}).expect("If pause fails run should always succeed");
player.toggle_play_music(pa).unwrap();
None
},
_ => None
}
} else {
input = None;
}
} else {
input = None;
}
if let Some(input) = input {
let _ = game.queue_input(input);
}
} | let image = gen_image();
let texture = texture::Texture2d::new(&display, image).unwrap();
let data_mutex: Arc<Mutex<Option<RenderData>>> = Arc::new(Mutex::new(None));
let mut game: game::Game; | random_line_split |
task-comm-11.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
extern mod extra;
use std::comm;
use std::task;
fn start(c: &comm::Chan<comm::Chan<int>>) {
let (p, ch) = comm::stream();
c.send(ch);
}
pub fn main() {
let (p, ch) = comm::stream();
let child = task::spawn(|| start(&ch) );
let c = p.recv();
} | // 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 | random_line_split |
task-comm-11.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.
// xfail-fast
extern mod extra;
use std::comm;
use std::task;
fn start(c: &comm::Chan<comm::Chan<int>>) {
let (p, ch) = comm::stream();
c.send(ch);
}
pub fn main() | {
let (p, ch) = comm::stream();
let child = task::spawn(|| start(&ch) );
let c = p.recv();
} | identifier_body |
|
task-comm-11.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.
// xfail-fast
extern mod extra;
use std::comm;
use std::task;
fn start(c: &comm::Chan<comm::Chan<int>>) {
let (p, ch) = comm::stream();
c.send(ch);
}
pub fn | () {
let (p, ch) = comm::stream();
let child = task::spawn(|| start(&ch) );
let c = p.recv();
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.