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
points.rs
use glium::{Program, Surface}; use glium::backend::Facade; use super::Figure; /// This figure is responsible for rendering points in two and three dimensions pub struct Points <'display_lifetime>{ program: Program, display: &'display_lifetime Facade } #[derive(Copy, Clone)] struct Vertex { position: [f32; 2] } implement_vertex!(Vertex, position); impl <'display_lifetime> Points<'display_lifetime> { pub fn new(display: &Facade) -> Points { Points { program: Points::create_program(display), display: display } } fn create_program(display: &Facade) -> Program { Program::from_source(display, &VERT_SRC, &FRAG_SRC, None).unwrap() } } impl <'display_lifetime> Figure for Points<'display_lifetime> { fn render<S: Surface>(&self, surface: &mut S) { use glium::index::{NoIndices, PrimitiveType}; use glium::VertexBuffer; let points = vec![ Vertex { position: [0.0, 0.0]}, Vertex { position: [0.5, 0.0]}, Vertex { position: [0.0, 0.5]}, Vertex { position: [-0.5, 0.0]},
let index_buffer = NoIndices(PrimitiveType::Points); let vertex_buffer = VertexBuffer::new(self.display, &points).unwrap(); surface.draw(&vertex_buffer, &index_buffer, &self.program, &uniform!(), &Default::default()).unwrap(); } } const VERT_SRC: &'static str = r#" #version 330 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } "#; const FRAG_SRC: &'static str = r#" #version 330 out vec4 frag_color; void main() { frag_color = vec4(1.0); } "#;
Vertex { position: [0.0, -0.5]}, ];
random_line_split
points.rs
use glium::{Program, Surface}; use glium::backend::Facade; use super::Figure; /// This figure is responsible for rendering points in two and three dimensions pub struct
<'display_lifetime>{ program: Program, display: &'display_lifetime Facade } #[derive(Copy, Clone)] struct Vertex { position: [f32; 2] } implement_vertex!(Vertex, position); impl <'display_lifetime> Points<'display_lifetime> { pub fn new(display: &Facade) -> Points { Points { program: Points::create_program(display), display: display } } fn create_program(display: &Facade) -> Program { Program::from_source(display, &VERT_SRC, &FRAG_SRC, None).unwrap() } } impl <'display_lifetime> Figure for Points<'display_lifetime> { fn render<S: Surface>(&self, surface: &mut S) { use glium::index::{NoIndices, PrimitiveType}; use glium::VertexBuffer; let points = vec![ Vertex { position: [0.0, 0.0]}, Vertex { position: [0.5, 0.0]}, Vertex { position: [0.0, 0.5]}, Vertex { position: [-0.5, 0.0]}, Vertex { position: [0.0, -0.5]}, ]; let index_buffer = NoIndices(PrimitiveType::Points); let vertex_buffer = VertexBuffer::new(self.display, &points).unwrap(); surface.draw(&vertex_buffer, &index_buffer, &self.program, &uniform!(), &Default::default()).unwrap(); } } const VERT_SRC: &'static str = r#" #version 330 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); } "#; const FRAG_SRC: &'static str = r#" #version 330 out vec4 frag_color; void main() { frag_color = vec4(1.0); } "#;
Points
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 std::collections::HashSet; use std::fs::create_dir_all; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; use std::time::SystemTime; use anyhow::{bail, format_err, Result}; use async_trait::async_trait; use percent_encoding::{percent_encode, AsciiSet, CONTROLS}; use blobstore::{ Blobstore, BlobstoreEnumerationData, BlobstoreGetData, BlobstoreIsPresent, BlobstoreKeyParam, BlobstoreKeySource, BlobstoreMetadata, BlobstorePutOps, BlobstoreUnlinkOps, OverwriteStatus, PutBehaviour, }; use context::CoreContext; use mononoke_types::BlobstoreBytes; use tempfile::{NamedTempFile, PersistError}; use tokio::{ fs::{hard_link, remove_file, File}, io::{self, AsyncReadExt, AsyncWriteExt}, }; use walkdir::WalkDir; const PREFIX: &str = "blob"; // https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); // https://url.spec.whatwg.org/#path-percent-encode-set const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}'); #[derive(Debug, Clone)] pub struct Fileblob { base: PathBuf, put_behaviour: PutBehaviour, } impl Fileblob { pub fn open<P: AsRef<Path>>(base: P, put_behaviour: PutBehaviour) -> Result<Self> { let base = base.as_ref(); if!base.is_dir() { bail!("Base {:?} doesn't exist or is not directory", base); } Ok(Self { base: base.to_owned(), put_behaviour, }) } pub fn create<P: AsRef<Path>>(base: P, put_behaviour: PutBehaviour) -> Result<Self> { let base = base.as_ref(); create_dir_all(base)?; Self::open(base, put_behaviour) } fn path(&self, key: &str) -> PathBuf { let key = percent_encode(key.as_bytes(), PATH); self.base.join(format!("{}-{}", PREFIX, key)) } } impl std::fmt::Display for Fileblob { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Fileblob") } } async fn ctime(file: &File) -> Option<i64> { let meta = file.metadata().await.ok()?; let ctime = meta.modified().ok()?; let ctime_dur = ctime.duration_since(SystemTime::UNIX_EPOCH).ok()?; i64::try_from(ctime_dur.as_secs()).ok() } #[async_trait] impl BlobstorePutOps for Fileblob { async fn put_explicit<'a>( &'a self, _ctx: &'a CoreContext, key: String, value: BlobstoreBytes, put_behaviour: PutBehaviour, ) -> Result<OverwriteStatus> { let p = self.path(&key); // block_in_place on tempfile would be ideal here, but it interacts // badly with tokio_compat let tempfile = NamedTempFile::new_in(&self.base)?; let new_file = tempfile.as_file().try_clone()?; let mut tokio_file = File::from_std(new_file); tokio_file.write_all(value.as_bytes().as_ref()).await?; tokio_file.flush().await?; tokio_file.sync_all().await?; let status = match put_behaviour { PutBehaviour::Overwrite => { tempfile.persist(&p)?; OverwriteStatus::NotChecked } PutBehaviour::IfAbsent | PutBehaviour::OverwriteAndLog => { let temp_path = tempfile.path().to_owned(); match tempfile.persist_noclobber(&p) { Ok(_) => OverwriteStatus::New, // Key already existed Err(PersistError { file: f, error: e }) if f.path() == temp_path && e.kind() == std::io::ErrorKind::AlreadyExists => { if put_behaviour.should_overwrite() { f.persist(&p)?; OverwriteStatus::Overwrote } else { OverwriteStatus::Prevented } } Err(e) => return Err(e.into()), } } }; Ok(status) } async fn put_with_status<'a>( &'a self, ctx: &'a CoreContext, key: String, value: BlobstoreBytes, ) -> Result<OverwriteStatus> { self.put_explicit(ctx, key, value, self.put_behaviour).await } } #[async_trait] impl Blobstore for Fileblob { async fn get<'a>( &'a self, _ctx: &'a CoreContext, key: &'a str, ) -> Result<Option<BlobstoreGetData>> { let p = self.path(key); let ret = match File::open(&p).await { Err(ref r) if r.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e.into()), Ok(mut f) => { let mut v = Vec::new(); f.read_to_end(&mut v).await?; Some(BlobstoreGetData::new( BlobstoreMetadata::new(ctime(&f).await, None), BlobstoreBytes::from_bytes(v), )) } }; Ok(ret) } async fn is_present<'a>( &'a self, _ctx: &'a CoreContext, key: &'a str, ) -> Result<BlobstoreIsPresent> { let p = self.path(key); let present = match File::open(&p).await { Err(ref e) if e.kind() == io::ErrorKind::NotFound => false, Err(e) => return Err(e.into()), Ok(_) => true, }; Ok(if present { BlobstoreIsPresent::Present } else { BlobstoreIsPresent::Absent }) } async fn put<'a>( &'a self, ctx: &'a CoreContext, key: String, value: BlobstoreBytes, ) -> Result<()> { BlobstorePutOps::put_with_status(self, ctx, key, value).await?; Ok(()) } // This uses hardlink semantics as the production blobstores also have hardlink like semantics // (i.e. you can't discover a canonical link source when loading by the target) async fn copy<'a>( &'a self, _ctx: &'a CoreContext, old_key: &'a str, new_key: String, ) -> Result<()> { // from std::fs::hard_link: The dst path will be a link pointing to the src path let src_path = self.path(old_key); let dst_path = self.path(&new_key); // hard_link will fail if dst_path exists. Race it in a task of its own Ok(tokio::task::spawn(async move { let _ = remove_file(&dst_path).await; hard_link(src_path, dst_path).await }) .await??) } } #[async_trait] impl BlobstoreUnlinkOps for Fileblob { async fn unlink<'a>(&'a self, _ctx: &'a CoreContext, key: &'a str) -> Result<()> { let path = self.path(key); Ok(remove_file(path).await?) } } #[async_trait] impl BlobstoreKeySource for Fileblob { async fn enumerate<'a>( &'a self, _ctx: &'a CoreContext, range: &'a BlobstoreKeyParam, ) -> Result<BlobstoreEnumerationData>
} _ => Err(format_err!("Fileblob does not support token, only ranges")), } } } #[cfg(test)] mod test { use super::*; use fbinit::FacebookInit; #[fbinit::test] async fn test_persist_error(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let blob = Fileblob { base: PathBuf::from("/mononoke/fileblob/test/path/should/not/exist"), put_behaviour: PutBehaviour::IfAbsent, }; let ret = blob .put(&ctx, "key".into(), BlobstoreBytes::from_bytes("value")) .await; assert!(ret.is_err()); Ok(()) } }
{ match range { BlobstoreKeyParam::Start(ref range) => { let mut enum_data = BlobstoreEnumerationData { keys: HashSet::new(), next_token: None, }; WalkDir::new(&self.base) .into_iter() .filter_map(|v| v.ok()) .for_each(|entry| { let entry = entry.path().to_str(); if let Some(data) = entry { let key = data.to_string(); if range.contains(&key) { enum_data.keys.insert(key); } } }); Ok(enum_data)
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 std::collections::HashSet; use std::fs::create_dir_all; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; use std::time::SystemTime; use anyhow::{bail, format_err, Result}; use async_trait::async_trait; use percent_encoding::{percent_encode, AsciiSet, CONTROLS}; use blobstore::{ Blobstore, BlobstoreEnumerationData, BlobstoreGetData, BlobstoreIsPresent, BlobstoreKeyParam, BlobstoreKeySource, BlobstoreMetadata, BlobstorePutOps, BlobstoreUnlinkOps, OverwriteStatus, PutBehaviour, }; use context::CoreContext; use mononoke_types::BlobstoreBytes; use tempfile::{NamedTempFile, PersistError}; use tokio::{ fs::{hard_link, remove_file, File}, io::{self, AsyncReadExt, AsyncWriteExt}, }; use walkdir::WalkDir; const PREFIX: &str = "blob"; // https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); // https://url.spec.whatwg.org/#path-percent-encode-set const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}'); #[derive(Debug, Clone)] pub struct Fileblob { base: PathBuf, put_behaviour: PutBehaviour, } impl Fileblob { pub fn open<P: AsRef<Path>>(base: P, put_behaviour: PutBehaviour) -> Result<Self> { let base = base.as_ref(); if!base.is_dir() { bail!("Base {:?} doesn't exist or is not directory", base); } Ok(Self { base: base.to_owned(), put_behaviour, }) } pub fn create<P: AsRef<Path>>(base: P, put_behaviour: PutBehaviour) -> Result<Self> { let base = base.as_ref(); create_dir_all(base)?; Self::open(base, put_behaviour) } fn path(&self, key: &str) -> PathBuf { let key = percent_encode(key.as_bytes(), PATH); self.base.join(format!("{}-{}", PREFIX, key)) } } impl std::fmt::Display for Fileblob { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Fileblob") } } async fn ctime(file: &File) -> Option<i64> { let meta = file.metadata().await.ok()?; let ctime = meta.modified().ok()?; let ctime_dur = ctime.duration_since(SystemTime::UNIX_EPOCH).ok()?; i64::try_from(ctime_dur.as_secs()).ok() } #[async_trait] impl BlobstorePutOps for Fileblob { async fn put_explicit<'a>( &'a self, _ctx: &'a CoreContext, key: String, value: BlobstoreBytes, put_behaviour: PutBehaviour, ) -> Result<OverwriteStatus> { let p = self.path(&key); // block_in_place on tempfile would be ideal here, but it interacts // badly with tokio_compat let tempfile = NamedTempFile::new_in(&self.base)?; let new_file = tempfile.as_file().try_clone()?; let mut tokio_file = File::from_std(new_file); tokio_file.write_all(value.as_bytes().as_ref()).await?; tokio_file.flush().await?; tokio_file.sync_all().await?; let status = match put_behaviour { PutBehaviour::Overwrite => { tempfile.persist(&p)?; OverwriteStatus::NotChecked } PutBehaviour::IfAbsent | PutBehaviour::OverwriteAndLog => { let temp_path = tempfile.path().to_owned(); match tempfile.persist_noclobber(&p) { Ok(_) => OverwriteStatus::New, // Key already existed Err(PersistError { file: f, error: e }) if f.path() == temp_path && e.kind() == std::io::ErrorKind::AlreadyExists => { if put_behaviour.should_overwrite() { f.persist(&p)?; OverwriteStatus::Overwrote } else { OverwriteStatus::Prevented } } Err(e) => return Err(e.into()), } } }; Ok(status) } async fn put_with_status<'a>( &'a self, ctx: &'a CoreContext, key: String, value: BlobstoreBytes, ) -> Result<OverwriteStatus> { self.put_explicit(ctx, key, value, self.put_behaviour).await } } #[async_trait] impl Blobstore for Fileblob { async fn get<'a>( &'a self, _ctx: &'a CoreContext, key: &'a str, ) -> Result<Option<BlobstoreGetData>> { let p = self.path(key); let ret = match File::open(&p).await { Err(ref r) if r.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e.into()), Ok(mut f) => { let mut v = Vec::new(); f.read_to_end(&mut v).await?; Some(BlobstoreGetData::new( BlobstoreMetadata::new(ctime(&f).await, None), BlobstoreBytes::from_bytes(v), )) } }; Ok(ret) } async fn is_present<'a>( &'a self, _ctx: &'a CoreContext, key: &'a str, ) -> Result<BlobstoreIsPresent> { let p = self.path(key); let present = match File::open(&p).await { Err(ref e) if e.kind() == io::ErrorKind::NotFound => false, Err(e) => return Err(e.into()), Ok(_) => true, }; Ok(if present { BlobstoreIsPresent::Present } else { BlobstoreIsPresent::Absent }) } async fn put<'a>( &'a self, ctx: &'a CoreContext, key: String, value: BlobstoreBytes,
// This uses hardlink semantics as the production blobstores also have hardlink like semantics // (i.e. you can't discover a canonical link source when loading by the target) async fn copy<'a>( &'a self, _ctx: &'a CoreContext, old_key: &'a str, new_key: String, ) -> Result<()> { // from std::fs::hard_link: The dst path will be a link pointing to the src path let src_path = self.path(old_key); let dst_path = self.path(&new_key); // hard_link will fail if dst_path exists. Race it in a task of its own Ok(tokio::task::spawn(async move { let _ = remove_file(&dst_path).await; hard_link(src_path, dst_path).await }) .await??) } } #[async_trait] impl BlobstoreUnlinkOps for Fileblob { async fn unlink<'a>(&'a self, _ctx: &'a CoreContext, key: &'a str) -> Result<()> { let path = self.path(key); Ok(remove_file(path).await?) } } #[async_trait] impl BlobstoreKeySource for Fileblob { async fn enumerate<'a>( &'a self, _ctx: &'a CoreContext, range: &'a BlobstoreKeyParam, ) -> Result<BlobstoreEnumerationData> { match range { BlobstoreKeyParam::Start(ref range) => { let mut enum_data = BlobstoreEnumerationData { keys: HashSet::new(), next_token: None, }; WalkDir::new(&self.base) .into_iter() .filter_map(|v| v.ok()) .for_each(|entry| { let entry = entry.path().to_str(); if let Some(data) = entry { let key = data.to_string(); if range.contains(&key) { enum_data.keys.insert(key); } } }); Ok(enum_data) } _ => Err(format_err!("Fileblob does not support token, only ranges")), } } } #[cfg(test)] mod test { use super::*; use fbinit::FacebookInit; #[fbinit::test] async fn test_persist_error(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let blob = Fileblob { base: PathBuf::from("/mononoke/fileblob/test/path/should/not/exist"), put_behaviour: PutBehaviour::IfAbsent, }; let ret = blob .put(&ctx, "key".into(), BlobstoreBytes::from_bytes("value")) .await; assert!(ret.is_err()); Ok(()) } }
) -> Result<()> { BlobstorePutOps::put_with_status(self, ctx, key, value).await?; Ok(()) }
random_line_split
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 std::collections::HashSet; use std::fs::create_dir_all; use std::ops::RangeBounds; use std::path::{Path, PathBuf}; use std::time::SystemTime; use anyhow::{bail, format_err, Result}; use async_trait::async_trait; use percent_encoding::{percent_encode, AsciiSet, CONTROLS}; use blobstore::{ Blobstore, BlobstoreEnumerationData, BlobstoreGetData, BlobstoreIsPresent, BlobstoreKeyParam, BlobstoreKeySource, BlobstoreMetadata, BlobstorePutOps, BlobstoreUnlinkOps, OverwriteStatus, PutBehaviour, }; use context::CoreContext; use mononoke_types::BlobstoreBytes; use tempfile::{NamedTempFile, PersistError}; use tokio::{ fs::{hard_link, remove_file, File}, io::{self, AsyncReadExt, AsyncWriteExt}, }; use walkdir::WalkDir; const PREFIX: &str = "blob"; // https://url.spec.whatwg.org/#fragment-percent-encode-set const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); // https://url.spec.whatwg.org/#path-percent-encode-set const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}'); #[derive(Debug, Clone)] pub struct Fileblob { base: PathBuf, put_behaviour: PutBehaviour, } impl Fileblob { pub fn open<P: AsRef<Path>>(base: P, put_behaviour: PutBehaviour) -> Result<Self> { let base = base.as_ref(); if!base.is_dir() { bail!("Base {:?} doesn't exist or is not directory", base); } Ok(Self { base: base.to_owned(), put_behaviour, }) } pub fn create<P: AsRef<Path>>(base: P, put_behaviour: PutBehaviour) -> Result<Self> { let base = base.as_ref(); create_dir_all(base)?; Self::open(base, put_behaviour) } fn path(&self, key: &str) -> PathBuf { let key = percent_encode(key.as_bytes(), PATH); self.base.join(format!("{}-{}", PREFIX, key)) } } impl std::fmt::Display for Fileblob { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Fileblob") } } async fn ctime(file: &File) -> Option<i64> { let meta = file.metadata().await.ok()?; let ctime = meta.modified().ok()?; let ctime_dur = ctime.duration_since(SystemTime::UNIX_EPOCH).ok()?; i64::try_from(ctime_dur.as_secs()).ok() } #[async_trait] impl BlobstorePutOps for Fileblob { async fn put_explicit<'a>( &'a self, _ctx: &'a CoreContext, key: String, value: BlobstoreBytes, put_behaviour: PutBehaviour, ) -> Result<OverwriteStatus> { let p = self.path(&key); // block_in_place on tempfile would be ideal here, but it interacts // badly with tokio_compat let tempfile = NamedTempFile::new_in(&self.base)?; let new_file = tempfile.as_file().try_clone()?; let mut tokio_file = File::from_std(new_file); tokio_file.write_all(value.as_bytes().as_ref()).await?; tokio_file.flush().await?; tokio_file.sync_all().await?; let status = match put_behaviour { PutBehaviour::Overwrite => { tempfile.persist(&p)?; OverwriteStatus::NotChecked } PutBehaviour::IfAbsent | PutBehaviour::OverwriteAndLog => { let temp_path = tempfile.path().to_owned(); match tempfile.persist_noclobber(&p) { Ok(_) => OverwriteStatus::New, // Key already existed Err(PersistError { file: f, error: e }) if f.path() == temp_path && e.kind() == std::io::ErrorKind::AlreadyExists => { if put_behaviour.should_overwrite() { f.persist(&p)?; OverwriteStatus::Overwrote } else { OverwriteStatus::Prevented } } Err(e) => return Err(e.into()), } } }; Ok(status) } async fn put_with_status<'a>( &'a self, ctx: &'a CoreContext, key: String, value: BlobstoreBytes, ) -> Result<OverwriteStatus> { self.put_explicit(ctx, key, value, self.put_behaviour).await } } #[async_trait] impl Blobstore for Fileblob { async fn get<'a>( &'a self, _ctx: &'a CoreContext, key: &'a str, ) -> Result<Option<BlobstoreGetData>> { let p = self.path(key); let ret = match File::open(&p).await { Err(ref r) if r.kind() == io::ErrorKind::NotFound => None, Err(e) => return Err(e.into()), Ok(mut f) => { let mut v = Vec::new(); f.read_to_end(&mut v).await?; Some(BlobstoreGetData::new( BlobstoreMetadata::new(ctime(&f).await, None), BlobstoreBytes::from_bytes(v), )) } }; Ok(ret) } async fn is_present<'a>( &'a self, _ctx: &'a CoreContext, key: &'a str, ) -> Result<BlobstoreIsPresent> { let p = self.path(key); let present = match File::open(&p).await { Err(ref e) if e.kind() == io::ErrorKind::NotFound => false, Err(e) => return Err(e.into()), Ok(_) => true, }; Ok(if present { BlobstoreIsPresent::Present } else { BlobstoreIsPresent::Absent }) } async fn put<'a>( &'a self, ctx: &'a CoreContext, key: String, value: BlobstoreBytes, ) -> Result<()> { BlobstorePutOps::put_with_status(self, ctx, key, value).await?; Ok(()) } // This uses hardlink semantics as the production blobstores also have hardlink like semantics // (i.e. you can't discover a canonical link source when loading by the target) async fn
<'a>( &'a self, _ctx: &'a CoreContext, old_key: &'a str, new_key: String, ) -> Result<()> { // from std::fs::hard_link: The dst path will be a link pointing to the src path let src_path = self.path(old_key); let dst_path = self.path(&new_key); // hard_link will fail if dst_path exists. Race it in a task of its own Ok(tokio::task::spawn(async move { let _ = remove_file(&dst_path).await; hard_link(src_path, dst_path).await }) .await??) } } #[async_trait] impl BlobstoreUnlinkOps for Fileblob { async fn unlink<'a>(&'a self, _ctx: &'a CoreContext, key: &'a str) -> Result<()> { let path = self.path(key); Ok(remove_file(path).await?) } } #[async_trait] impl BlobstoreKeySource for Fileblob { async fn enumerate<'a>( &'a self, _ctx: &'a CoreContext, range: &'a BlobstoreKeyParam, ) -> Result<BlobstoreEnumerationData> { match range { BlobstoreKeyParam::Start(ref range) => { let mut enum_data = BlobstoreEnumerationData { keys: HashSet::new(), next_token: None, }; WalkDir::new(&self.base) .into_iter() .filter_map(|v| v.ok()) .for_each(|entry| { let entry = entry.path().to_str(); if let Some(data) = entry { let key = data.to_string(); if range.contains(&key) { enum_data.keys.insert(key); } } }); Ok(enum_data) } _ => Err(format_err!("Fileblob does not support token, only ranges")), } } } #[cfg(test)] mod test { use super::*; use fbinit::FacebookInit; #[fbinit::test] async fn test_persist_error(fb: FacebookInit) -> Result<()> { let ctx = CoreContext::test_mock(fb); let blob = Fileblob { base: PathBuf::from("/mononoke/fileblob/test/path/should/not/exist"), put_behaviour: PutBehaviour::IfAbsent, }; let ret = blob .put(&ctx, "key".into(), BlobstoreBytes::from_bytes("value")) .await; assert!(ret.is_err()); Ok(()) } }
copy
identifier_name
type_of.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. #![allow(non_camel_case_types)] use middle::trans::adt; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux; use util::ppaux::Repr; use middle::trans::type_::Type; use syntax::abi; use syntax::ast; use syntax::owned_slice::OwnedSlice; pub fn arg_is_indirect(ccx: &CrateContext, arg_ty: ty::t) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr(ccx: &CrateContext, ty: ty::t) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type { let llty = type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } pub fn type_of_rust_fn(cx: &CrateContext, has_env: bool, inputs: &[ty::t], output: ty::t) -> Type { let mut atys: Vec<Type> = Vec::new(); // Arg 0: Output pointer. // (if the output type is non-immediate) let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = type_of(cx, output); if use_out_pointer { atys.push(lloutputtype.ptr_to()); } // Arg 1: Environment if has_env { atys.push(Type::i8p(cx)); } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); // Use the output as the actual return value if it's immediate. if use_out_pointer || return_type_is_void(cx, output) { Type::func(atys.as_slice(), &Type::void(cx)) } else { Type::func(atys.as_slice(), &lloutputtype) } } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type { match ty::get(fty).sty { ty::ty_closure(ref f) => { type_of_rust_fn(cx, true, f.sig.inputs.as_slice(), f.sig.output) } ty::ty_bare_fn(ref f) => { if f.abi == abi::Rust || f.abi == abi::RustIntrinsic { type_of_rust_fn(cx, false, f.sig.inputs.as_slice(), f.sig.output) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type { match cx.llsizingtypes.borrow().find_copy(&t) { Some(t) => return t, None => () } let llsizingty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_box(..) | ty::ty_uniq(..) | ty::ty_ptr(..) => Type::i8p(cx), ty::ty_rptr(_, mt) => { match ty::get(mt.ty).sty { ty::ty_vec(_, None) | ty::ty_str => { Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false) } _ => Type::i8p(cx), } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_vec(mt, Some(size)) => { Type::array(&sizing_type_of(cx, mt.ty), size as u64) } ty::ty_tup(..) | ty::ty_enum(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } } ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) | ty::ty_vec(_, None) | ty::ty_str => { cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()", ty::get(t).sty).as_slice()) } }; cx.llsizingtypes.borrow_mut().insert(t, llsizingty); llsizingty } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { // Check the cache. match cx.lltypes.borrow().find(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = ty::normalize_ty(cx.tcx(), t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); return llty; } let mut llty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, an_enum, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } ty::ty_box(typ) => { Type::at_box(cx, type_of(cx, typ)).ptr_to() } ty::ty_uniq(typ) => { match ty::get(typ).sty { ty::ty_vec(mt, None) => Type::vec(cx, &type_of(cx, mt.ty)).ptr_to(), ty::ty_str => Type::vec(cx, &Type::i8(cx)).ptr_to(), _ => type_of(cx, typ).ptr_to(), } } ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_rptr(_, ref mt) => { match ty::get(mt.ty).sty { ty::ty_vec(mt, None) => { let p_ty = type_of(cx, mt.ty).ptr_to(); let u_ty = Type::uint_from_ty(cx, ast::TyU); Type::struct_(cx, [p_ty, u_ty], false) } ty::ty_str => { // This means we get a nicer name in the output cx.tn.find_type("str_slice").unwrap() } _ => type_of(cx, mt.ty).ptr_to(), }
} ty::ty_bare_fn(_) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_closure(_) => { let fn_ty = type_of_fn_from_ty(cx, t).ptr_to(); Type::struct_(cx, [fn_ty, Type::i8p(cx)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, a_struct, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } } ty::ty_vec(_, None) => cx.sess().bug("type_of with unsized ty_vec"), ty::ty_str => cx.sess().bug("type_of with unsized (bare) ty_str"), ty::ty_self(..) => cx.sess().unimpl("type_of with ty_self"), ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err") }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match ty::get(t).sty { ty::ty_enum(..) | ty::ty_struct(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } // Want refinements! (Or case classes, I guess pub enum named_ty { a_struct, an_enum } pub fn llvm_type_name(cx: &CrateContext, what: named_ty, did: ast::DefId, tps: &[ty::t]) -> String { let name = match what { a_struct => { "struct" } an_enum => { "enum" } }; let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did).as_slice(), &ty::NonerasedRegions( OwnedSlice::empty()), tps, did, false); if did.krate == 0 { format!("{}.{}", name, tstr) } else { format!("{}.{}[\\#{}]", name, tstr, did.krate) } } pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type { let self_ty = type_of(ccx, self_ty).ptr_to(); Type::func([self_ty], &Type::void(ccx)) }
} ty::ty_vec(ref mt, Some(n)) => { Type::array(&type_of(cx, mt.ty), n as u64)
random_line_split
type_of.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. #![allow(non_camel_case_types)] use middle::trans::adt; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux; use util::ppaux::Repr; use middle::trans::type_::Type; use syntax::abi; use syntax::ast; use syntax::owned_slice::OwnedSlice; pub fn arg_is_indirect(ccx: &CrateContext, arg_ty: ty::t) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr(ccx: &CrateContext, ty: ty::t) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type { let llty = type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } pub fn type_of_rust_fn(cx: &CrateContext, has_env: bool, inputs: &[ty::t], output: ty::t) -> Type { let mut atys: Vec<Type> = Vec::new(); // Arg 0: Output pointer. // (if the output type is non-immediate) let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = type_of(cx, output); if use_out_pointer { atys.push(lloutputtype.ptr_to()); } // Arg 1: Environment if has_env { atys.push(Type::i8p(cx)); } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); // Use the output as the actual return value if it's immediate. if use_out_pointer || return_type_is_void(cx, output) { Type::func(atys.as_slice(), &Type::void(cx)) } else { Type::func(atys.as_slice(), &lloutputtype) } } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type { match ty::get(fty).sty { ty::ty_closure(ref f) => { type_of_rust_fn(cx, true, f.sig.inputs.as_slice(), f.sig.output) } ty::ty_bare_fn(ref f) => { if f.abi == abi::Rust || f.abi == abi::RustIntrinsic { type_of_rust_fn(cx, false, f.sig.inputs.as_slice(), f.sig.output) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type { match cx.llsizingtypes.borrow().find_copy(&t) { Some(t) => return t, None => () } let llsizingty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_box(..) | ty::ty_uniq(..) | ty::ty_ptr(..) => Type::i8p(cx), ty::ty_rptr(_, mt) => { match ty::get(mt.ty).sty { ty::ty_vec(_, None) | ty::ty_str => { Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false) } _ => Type::i8p(cx), } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_vec(mt, Some(size)) => { Type::array(&sizing_type_of(cx, mt.ty), size as u64) } ty::ty_tup(..) | ty::ty_enum(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } } ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) | ty::ty_vec(_, None) | ty::ty_str => { cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()", ty::get(t).sty).as_slice()) } }; cx.llsizingtypes.borrow_mut().insert(t, llsizingty); llsizingty } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { // Check the cache. match cx.lltypes.borrow().find(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = ty::normalize_ty(cx.tcx(), t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); return llty; } let mut llty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, an_enum, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } ty::ty_box(typ) => { Type::at_box(cx, type_of(cx, typ)).ptr_to() } ty::ty_uniq(typ) => { match ty::get(typ).sty { ty::ty_vec(mt, None) => Type::vec(cx, &type_of(cx, mt.ty)).ptr_to(), ty::ty_str => Type::vec(cx, &Type::i8(cx)).ptr_to(), _ => type_of(cx, typ).ptr_to(), } } ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_rptr(_, ref mt) => { match ty::get(mt.ty).sty { ty::ty_vec(mt, None) => { let p_ty = type_of(cx, mt.ty).ptr_to(); let u_ty = Type::uint_from_ty(cx, ast::TyU); Type::struct_(cx, [p_ty, u_ty], false) } ty::ty_str => { // This means we get a nicer name in the output cx.tn.find_type("str_slice").unwrap() } _ => type_of(cx, mt.ty).ptr_to(), } } ty::ty_vec(ref mt, Some(n)) => { Type::array(&type_of(cx, mt.ty), n as u64) } ty::ty_bare_fn(_) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_closure(_) => { let fn_ty = type_of_fn_from_ty(cx, t).ptr_to(); Type::struct_(cx, [fn_ty, Type::i8p(cx)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, a_struct, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } } ty::ty_vec(_, None) => cx.sess().bug("type_of with unsized ty_vec"), ty::ty_str => cx.sess().bug("type_of with unsized (bare) ty_str"), ty::ty_self(..) => cx.sess().unimpl("type_of with ty_self"), ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err") }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match ty::get(t).sty { ty::ty_enum(..) | ty::ty_struct(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } // Want refinements! (Or case classes, I guess pub enum named_ty { a_struct, an_enum } pub fn llvm_type_name(cx: &CrateContext, what: named_ty, did: ast::DefId, tps: &[ty::t]) -> String { let name = match what { a_struct => { "struct" } an_enum =>
}; let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did).as_slice(), &ty::NonerasedRegions( OwnedSlice::empty()), tps, did, false); if did.krate == 0 { format!("{}.{}", name, tstr) } else { format!("{}.{}[\\#{}]", name, tstr, did.krate) } } pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type { let self_ty = type_of(ccx, self_ty).ptr_to(); Type::func([self_ty], &Type::void(ccx)) }
{ "enum" }
conditional_block
type_of.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. #![allow(non_camel_case_types)] use middle::trans::adt; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux; use util::ppaux::Repr; use middle::trans::type_::Type; use syntax::abi; use syntax::ast; use syntax::owned_slice::OwnedSlice; pub fn arg_is_indirect(ccx: &CrateContext, arg_ty: ty::t) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr(ccx: &CrateContext, ty: ty::t) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type { let llty = type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } pub fn type_of_rust_fn(cx: &CrateContext, has_env: bool, inputs: &[ty::t], output: ty::t) -> Type { let mut atys: Vec<Type> = Vec::new(); // Arg 0: Output pointer. // (if the output type is non-immediate) let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = type_of(cx, output); if use_out_pointer { atys.push(lloutputtype.ptr_to()); } // Arg 1: Environment if has_env { atys.push(Type::i8p(cx)); } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); // Use the output as the actual return value if it's immediate. if use_out_pointer || return_type_is_void(cx, output) { Type::func(atys.as_slice(), &Type::void(cx)) } else { Type::func(atys.as_slice(), &lloutputtype) } } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type { match ty::get(fty).sty { ty::ty_closure(ref f) => { type_of_rust_fn(cx, true, f.sig.inputs.as_slice(), f.sig.output) } ty::ty_bare_fn(ref f) => { if f.abi == abi::Rust || f.abi == abi::RustIntrinsic { type_of_rust_fn(cx, false, f.sig.inputs.as_slice(), f.sig.output) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type { match cx.llsizingtypes.borrow().find_copy(&t) { Some(t) => return t, None => () } let llsizingty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_box(..) | ty::ty_uniq(..) | ty::ty_ptr(..) => Type::i8p(cx), ty::ty_rptr(_, mt) => { match ty::get(mt.ty).sty { ty::ty_vec(_, None) | ty::ty_str => { Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false) } _ => Type::i8p(cx), } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_vec(mt, Some(size)) => { Type::array(&sizing_type_of(cx, mt.ty), size as u64) } ty::ty_tup(..) | ty::ty_enum(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } } ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) | ty::ty_vec(_, None) | ty::ty_str => { cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()", ty::get(t).sty).as_slice()) } }; cx.llsizingtypes.borrow_mut().insert(t, llsizingty); llsizingty } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { // Check the cache. match cx.lltypes.borrow().find(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = ty::normalize_ty(cx.tcx(), t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); return llty; } let mut llty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, an_enum, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } ty::ty_box(typ) => { Type::at_box(cx, type_of(cx, typ)).ptr_to() } ty::ty_uniq(typ) => { match ty::get(typ).sty { ty::ty_vec(mt, None) => Type::vec(cx, &type_of(cx, mt.ty)).ptr_to(), ty::ty_str => Type::vec(cx, &Type::i8(cx)).ptr_to(), _ => type_of(cx, typ).ptr_to(), } } ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_rptr(_, ref mt) => { match ty::get(mt.ty).sty { ty::ty_vec(mt, None) => { let p_ty = type_of(cx, mt.ty).ptr_to(); let u_ty = Type::uint_from_ty(cx, ast::TyU); Type::struct_(cx, [p_ty, u_ty], false) } ty::ty_str => { // This means we get a nicer name in the output cx.tn.find_type("str_slice").unwrap() } _ => type_of(cx, mt.ty).ptr_to(), } } ty::ty_vec(ref mt, Some(n)) => { Type::array(&type_of(cx, mt.ty), n as u64) } ty::ty_bare_fn(_) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_closure(_) => { let fn_ty = type_of_fn_from_ty(cx, t).ptr_to(); Type::struct_(cx, [fn_ty, Type::i8p(cx)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, a_struct, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } } ty::ty_vec(_, None) => cx.sess().bug("type_of with unsized ty_vec"), ty::ty_str => cx.sess().bug("type_of with unsized (bare) ty_str"), ty::ty_self(..) => cx.sess().unimpl("type_of with ty_self"), ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err") }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match ty::get(t).sty { ty::ty_enum(..) | ty::ty_struct(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } // Want refinements! (Or case classes, I guess pub enum named_ty { a_struct, an_enum } pub fn
(cx: &CrateContext, what: named_ty, did: ast::DefId, tps: &[ty::t]) -> String { let name = match what { a_struct => { "struct" } an_enum => { "enum" } }; let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did).as_slice(), &ty::NonerasedRegions( OwnedSlice::empty()), tps, did, false); if did.krate == 0 { format!("{}.{}", name, tstr) } else { format!("{}.{}[\\#{}]", name, tstr, did.krate) } } pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type { let self_ty = type_of(ccx, self_ty).ptr_to(); Type::func([self_ty], &Type::void(ccx)) }
llvm_type_name
identifier_name
type_of.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. #![allow(non_camel_case_types)] use middle::trans::adt; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux; use util::ppaux::Repr; use middle::trans::type_::Type; use syntax::abi; use syntax::ast; use syntax::owned_slice::OwnedSlice; pub fn arg_is_indirect(ccx: &CrateContext, arg_ty: ty::t) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr(ccx: &CrateContext, ty: ty::t) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type { let llty = type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } pub fn type_of_rust_fn(cx: &CrateContext, has_env: bool, inputs: &[ty::t], output: ty::t) -> Type { let mut atys: Vec<Type> = Vec::new(); // Arg 0: Output pointer. // (if the output type is non-immediate) let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = type_of(cx, output); if use_out_pointer { atys.push(lloutputtype.ptr_to()); } // Arg 1: Environment if has_env { atys.push(Type::i8p(cx)); } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); // Use the output as the actual return value if it's immediate. if use_out_pointer || return_type_is_void(cx, output) { Type::func(atys.as_slice(), &Type::void(cx)) } else { Type::func(atys.as_slice(), &lloutputtype) } } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type { match ty::get(fty).sty { ty::ty_closure(ref f) => { type_of_rust_fn(cx, true, f.sig.inputs.as_slice(), f.sig.output) } ty::ty_bare_fn(ref f) => { if f.abi == abi::Rust || f.abi == abi::RustIntrinsic { type_of_rust_fn(cx, false, f.sig.inputs.as_slice(), f.sig.output) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type
Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false) } _ => Type::i8p(cx), } } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_vec(mt, Some(size)) => { Type::array(&sizing_type_of(cx, mt.ty), size as u64) } ty::ty_tup(..) | ty::ty_enum(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } } ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) | ty::ty_vec(_, None) | ty::ty_str => { cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()", ty::get(t).sty).as_slice()) } }; cx.llsizingtypes.borrow_mut().insert(t, llsizingty); llsizingty } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { // Check the cache. match cx.lltypes.borrow().find(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = ty::normalize_ty(cx.tcx(), t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); return llty; } let mut llty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, an_enum, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } ty::ty_box(typ) => { Type::at_box(cx, type_of(cx, typ)).ptr_to() } ty::ty_uniq(typ) => { match ty::get(typ).sty { ty::ty_vec(mt, None) => Type::vec(cx, &type_of(cx, mt.ty)).ptr_to(), ty::ty_str => Type::vec(cx, &Type::i8(cx)).ptr_to(), _ => type_of(cx, typ).ptr_to(), } } ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_rptr(_, ref mt) => { match ty::get(mt.ty).sty { ty::ty_vec(mt, None) => { let p_ty = type_of(cx, mt.ty).ptr_to(); let u_ty = Type::uint_from_ty(cx, ast::TyU); Type::struct_(cx, [p_ty, u_ty], false) } ty::ty_str => { // This means we get a nicer name in the output cx.tn.find_type("str_slice").unwrap() } _ => type_of(cx, mt.ty).ptr_to(), } } ty::ty_vec(ref mt, Some(n)) => { Type::array(&type_of(cx, mt.ty), n as u64) } ty::ty_bare_fn(_) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_closure(_) => { let fn_ty = type_of_fn_from_ty(cx, t).ptr_to(); Type::struct_(cx, [fn_ty, Type::i8p(cx)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, a_struct, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name.as_slice()) } } ty::ty_vec(_, None) => cx.sess().bug("type_of with unsized ty_vec"), ty::ty_str => cx.sess().bug("type_of with unsized (bare) ty_str"), ty::ty_self(..) => cx.sess().unimpl("type_of with ty_self"), ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err") }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match ty::get(t).sty { ty::ty_enum(..) | ty::ty_struct(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } // Want refinements! (Or case classes, I guess pub enum named_ty { a_struct, an_enum } pub fn llvm_type_name(cx: &CrateContext, what: named_ty, did: ast::DefId, tps: &[ty::t]) -> String { let name = match what { a_struct => { "struct" } an_enum => { "enum" } }; let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did).as_slice(), &ty::NonerasedRegions( OwnedSlice::empty()), tps, did, false); if did.krate == 0 { format!("{}.{}", name, tstr) } else { format!("{}.{}[\\#{}]", name, tstr, did.krate) } } pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type { let self_ty = type_of(ccx, self_ty).ptr_to(); Type::func([self_ty], &Type::void(ccx)) }
{ match cx.llsizingtypes.borrow().find_copy(&t) { Some(t) => return t, None => () } let llsizingty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_box(..) | ty::ty_uniq(..) | ty::ty_ptr(..) => Type::i8p(cx), ty::ty_rptr(_, mt) => { match ty::get(mt.ty).sty { ty::ty_vec(_, None) | ty::ty_str => {
identifier_body
env.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. /* * The compiler code necessary to support the env! extension. Eventually this * should all get sucked into either the compiler syntax extension plugin * interface. */ use ast; use codemap::Span; use ext::base::*; use ext::base; use ext::build::AstBuilder; use parse::token; use std::env; pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") { None => return DummyResult::expr(sp), Some(v) => v }; let e = match env::var(&var[..]) { Err(..) => { cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), Vec::new(), vec!(cx.ty_rptr(sp, cx.ty_ident(sp, cx.ident_of("str")), Some(cx.lifetime(sp, cx.ident_of( "'static").name)), ast::MutImmutable)), Vec::new())) } Ok(s) => { cx.expr_call_global(sp, cx.std_path(&["option", "Option", "Some"]), vec!(cx.expr_str(sp, token::intern_and_get_ident( &s[..])))) } }; MacEager::expr(e) } pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let mut exprs = match get_exprs_from_tts(cx, sp, tts) { Some(ref exprs) if exprs.is_empty() => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } None => return DummyResult::expr(sp), Some(exprs) => exprs.into_iter() }; let var = match expr_to_string(cx, exprs.next().unwrap(), "expected string literal") { None => return DummyResult::expr(sp), Some((v, _style)) => v
}; let msg = match exprs.next() { None => { token::intern_and_get_ident(&format!("environment variable `{}` \ not defined", var)) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { None => return DummyResult::expr(sp), Some((s, _style)) => s } } }; match exprs.next() { None => {} Some(_) => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } } let e = match env::var(&var[..]) { Err(_) => { cx.span_err(sp, &msg); cx.expr_usize(sp, 0) } Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s)) }; MacEager::expr(e) }
random_line_split
env.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. /* * The compiler code necessary to support the env! extension. Eventually this * should all get sucked into either the compiler syntax extension plugin * interface. */ use ast; use codemap::Span; use ext::base::*; use ext::base; use ext::build::AstBuilder; use parse::token; use std::env; pub fn
<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") { None => return DummyResult::expr(sp), Some(v) => v }; let e = match env::var(&var[..]) { Err(..) => { cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), Vec::new(), vec!(cx.ty_rptr(sp, cx.ty_ident(sp, cx.ident_of("str")), Some(cx.lifetime(sp, cx.ident_of( "'static").name)), ast::MutImmutable)), Vec::new())) } Ok(s) => { cx.expr_call_global(sp, cx.std_path(&["option", "Option", "Some"]), vec!(cx.expr_str(sp, token::intern_and_get_ident( &s[..])))) } }; MacEager::expr(e) } pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let mut exprs = match get_exprs_from_tts(cx, sp, tts) { Some(ref exprs) if exprs.is_empty() => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } None => return DummyResult::expr(sp), Some(exprs) => exprs.into_iter() }; let var = match expr_to_string(cx, exprs.next().unwrap(), "expected string literal") { None => return DummyResult::expr(sp), Some((v, _style)) => v }; let msg = match exprs.next() { None => { token::intern_and_get_ident(&format!("environment variable `{}` \ not defined", var)) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { None => return DummyResult::expr(sp), Some((s, _style)) => s } } }; match exprs.next() { None => {} Some(_) => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } } let e = match env::var(&var[..]) { Err(_) => { cx.span_err(sp, &msg); cx.expr_usize(sp, 0) } Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s)) }; MacEager::expr(e) }
expand_option_env
identifier_name
env.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. /* * The compiler code necessary to support the env! extension. Eventually this * should all get sucked into either the compiler syntax extension plugin * interface. */ use ast; use codemap::Span; use ext::base::*; use ext::base; use ext::build::AstBuilder; use parse::token; use std::env; pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx> { let var = match get_single_str_from_tts(cx, sp, tts, "option_env!") { None => return DummyResult::expr(sp), Some(v) => v }; let e = match env::var(&var[..]) { Err(..) => { cx.expr_path(cx.path_all(sp, true, cx.std_path(&["option", "Option", "None"]), Vec::new(), vec!(cx.ty_rptr(sp, cx.ty_ident(sp, cx.ident_of("str")), Some(cx.lifetime(sp, cx.ident_of( "'static").name)), ast::MutImmutable)), Vec::new())) } Ok(s) => { cx.expr_call_global(sp, cx.std_path(&["option", "Option", "Some"]), vec!(cx.expr_str(sp, token::intern_and_get_ident( &s[..])))) } }; MacEager::expr(e) } pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult+'cx>
var)) } Some(second) => { match expr_to_string(cx, second, "expected string literal") { None => return DummyResult::expr(sp), Some((s, _style)) => s } } }; match exprs.next() { None => {} Some(_) => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } } let e = match env::var(&var[..]) { Err(_) => { cx.span_err(sp, &msg); cx.expr_usize(sp, 0) } Ok(s) => cx.expr_str(sp, token::intern_and_get_ident(&s)) }; MacEager::expr(e) }
{ let mut exprs = match get_exprs_from_tts(cx, sp, tts) { Some(ref exprs) if exprs.is_empty() => { cx.span_err(sp, "env! takes 1 or 2 arguments"); return DummyResult::expr(sp); } None => return DummyResult::expr(sp), Some(exprs) => exprs.into_iter() }; let var = match expr_to_string(cx, exprs.next().unwrap(), "expected string literal") { None => return DummyResult::expr(sp), Some((v, _style)) => v }; let msg = match exprs.next() { None => { token::intern_and_get_ident(&format!("environment variable `{}` \ not defined",
identifier_body
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLEMENTATION, EXPOSED ONLY FOR INTEGRATION TESTS. pub use super::async_rt::*; } pub use crate::dealer::*; pub use crate::endpoint::{Endpoint, Host, Transport, TryIntoEndpoint}; pub use crate::error::{ZmqError, ZmqResult}; pub use crate::pull::*; pub use crate::push::*; pub use crate::r#pub::*; pub use crate::rep::*; pub use crate::req::*; pub use crate::router::*; pub use crate::sub::*; pub use message::*; use crate::codec::*; use crate::transport::AcceptStopHandle; use util::PeerIdentity; #[macro_use] extern crate enum_primitive_derive; use async_trait::async_trait; use asynchronous_codec::FramedWrite; use futures::channel::mpsc; use futures::FutureExt; use num_traits::ToPrimitive; use parking_lot::Mutex; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt::{Debug, Display}; use std::sync::Arc; #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Copy, Debug, PartialEq, Primitive)] pub enum SocketType { PAIR = 0, PUB = 1, SUB = 2, REQ = 3, REP = 4, DEALER = 5, ROUTER = 6, PULL = 7, PUSH = 8, XPUB = 9, XSUB = 10, STREAM = 11, } impl TryFrom<&str> for SocketType { type Error = ZmqError; fn try_from(s: &str) -> Result<Self, ZmqError> { Ok(match s { "PAIR" => SocketType::PAIR, "PUB" => SocketType::PUB, "SUB" => SocketType::SUB, "REQ" => SocketType::REQ, "REP" => SocketType::REP, "DEALER" => SocketType::DEALER, "ROUTER" => SocketType::ROUTER, "PULL" => SocketType::PULL, "PUSH" => SocketType::PUSH, "XPUB" => SocketType::XPUB, "XSUB" => SocketType::XSUB, "STREAM" => SocketType::STREAM, _ => return Err(ZmqError::Other("Unknown socket type")), }) } } impl Display for SocketType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SocketType::PAIR => write!(f, "PAIR"), SocketType::PUB => write!(f, "PUB"), SocketType::SUB => write!(f, "SUB"), SocketType::REQ => write!(f, "REQ"), SocketType::REP => write!(f, "REP"), SocketType::DEALER => write!(f, "DEALER"), SocketType::ROUTER => write!(f, "ROUTER"), SocketType::PULL => write!(f, "PULL"), SocketType::PUSH => write!(f, "PUSH"), SocketType::XPUB => write!(f, "XPUB"), SocketType::XSUB => write!(f, "XSUB"), SocketType::STREAM => write!(f, "STREAM"), } } } #[derive(Debug)] pub enum SocketEvent { Connected(Endpoint, PeerIdentity), ConnectDelayed, ConnectRetried, Listening(Endpoint), Accepted(Endpoint, PeerIdentity), AcceptFailed(ZmqError), Closed, CloseFailed, Disconnected(PeerIdentity), } #[derive(Default)] pub struct SocketOptions { pub(crate) peer_id: Option<PeerIdentity>, } impl SocketOptions { pub fn peer_identity(&mut self, peer_id: PeerIdentity) -> &mut Self { self.peer_id = Some(peer_id); self } } #[async_trait] pub trait MultiPeerBackend: SocketBackend { /// This should not be public.. /// Find a better way of doing this async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo); fn peer_disconnected(&self, peer_id: &PeerIdentity); } pub trait SocketBackend: Send + Sync { fn socket_type(&self) -> SocketType; fn socket_options(&self) -> &SocketOptions; fn shutdown(&self); fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>>; } #[async_trait] pub trait SocketRecv { async fn recv(&mut self) -> ZmqResult<ZmqMessage>; } #[async_trait] pub trait SocketSend { async fn send(&mut self, message: ZmqMessage) -> ZmqResult<()>; } /// Marker trait that express the fact that only certain types of sockets might be used /// in [proxy] function as a capture parameter pub trait CaptureSocket: SocketSend {} #[async_trait] pub trait Socket: Sized + Send { fn new() -> Self { Self::with_options(SocketOptions::default()) } fn with_options(options: SocketOptions) -> Self; fn backend(&self) -> Arc<dyn MultiPeerBackend>; /// Binds to the endpoint and starts a coroutine to accept new connections /// on it. /// /// Returns the endpoint resolved to the exact bound location if applicable /// (port # resolved, for example). async fn bind(&mut self, endpoint: &str) -> ZmqResult<Endpoint> { let endpoint = endpoint.try_into()?; let cloned_backend = self.backend(); let cback = move |result| { let cloned_backend = cloned_backend.clone(); async move { let result = match result { Ok((socket, endpoint)) => { match util::peer_connected(socket, cloned_backend.clone()).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), } } Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) =>
Err(e) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::AcceptFailed(e)); } } } } }; let (endpoint, stop_handle) = transport::begin_accept(endpoint, cback).await?; if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Listening(endpoint.clone())); } self.binds().insert(endpoint.clone(), stop_handle); Ok(endpoint) } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle>; /// Unbinds the endpoint, blocking until the associated endpoint is no /// longer in use /// /// # Errors /// May give a `ZmqError::NoSuchBind` if `endpoint` isn't bound. May also /// give any other zmq errors encountered when attempting to disconnect async fn unbind(&mut self, endpoint: Endpoint) -> ZmqResult<()> { let stop_handle = self.binds().remove(&endpoint); let stop_handle = stop_handle.ok_or(ZmqError::NoSuchBind(endpoint))?; stop_handle.0.shutdown().await } /// Unbinds all bound endpoints, blocking until finished. async fn unbind_all(&mut self) -> Vec<ZmqError> { let mut errs = Vec::new(); let endpoints: Vec<_> = self .binds() .iter() .map(|(endpoint, _)| endpoint.clone()) .collect(); for endpoint in endpoints { if let Err(err) = self.unbind(endpoint).await { errs.push(err); } } errs } /// Connects to the given endpoint. async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> { let backend = self.backend(); let endpoint = endpoint.try_into()?; let result = match util::connect_forever(endpoint).await { Ok((socket, endpoint)) => match util::peer_connected(socket, backend).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), }, Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Connected(endpoint, peer_id)); } Ok(()) } Err(e) => Err(e), } } /// Creates and setups new socket monitor /// /// Subsequent calls to this method each create a new monitor channel. /// Sender side of previous one is dropped. fn monitor(&mut self) -> mpsc::Receiver<SocketEvent>; // TODO: async fn connections(&self) ->? /// Disconnects from the given endpoint, blocking until finished. /// /// # Errors /// May give a `ZmqError::NoSuchConnection` if `endpoint` isn't connected. /// May also give any other zmq errors encountered when attempting to /// disconnect. // TODO: async fn disconnect(&mut self, endpoint: impl TryIntoEndpoint + 'async_trait) -> // ZmqResult<()>; /// Disconnects all connecttions, blocking until finished. // TODO: async fn disconnect_all(&mut self) -> ZmqResult<()>; /// Closes the socket, blocking until all associated binds are closed. /// This is equivalent to `drop()`, but with the benefit of blocking until /// resources are released, and getting any underlying errors. /// /// Returns any encountered errors. // TODO: Call disconnect_all() when added async fn close(mut self) -> Vec<ZmqError> { // self.disconnect_all().await?; self.unbind_all().await } } pub async fn proxy<Frontend: SocketSend + SocketRecv, Backend: SocketSend + SocketRecv>( mut frontend: Frontend, mut backend: Backend, mut capture: Option<Box<dyn CaptureSocket>>, ) -> ZmqResult<()> { loop { futures::select! { frontend_mess = frontend.recv().fuse() => { match frontend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } backend.send(message).await?; } Err(_) => { todo!() } } }, backend_mess = backend.recv().fuse() => { match backend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } frontend.send(message).await?; } Err(_) => { todo!() } } } }; } } pub mod prelude { //! Re-exports important traits. Consider glob-importing. pub use crate::{Socket, SocketRecv, SocketSend, TryIntoEndpoint}; }
{ if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Accepted(endpoint, peer_id)); } }
conditional_block
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLEMENTATION, EXPOSED ONLY FOR INTEGRATION TESTS. pub use super::async_rt::*; } pub use crate::dealer::*; pub use crate::endpoint::{Endpoint, Host, Transport, TryIntoEndpoint}; pub use crate::error::{ZmqError, ZmqResult}; pub use crate::pull::*; pub use crate::push::*; pub use crate::r#pub::*; pub use crate::rep::*; pub use crate::req::*; pub use crate::router::*; pub use crate::sub::*; pub use message::*; use crate::codec::*; use crate::transport::AcceptStopHandle; use util::PeerIdentity; #[macro_use] extern crate enum_primitive_derive; use async_trait::async_trait; use asynchronous_codec::FramedWrite; use futures::channel::mpsc; use futures::FutureExt; use num_traits::ToPrimitive; use parking_lot::Mutex; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt::{Debug, Display}; use std::sync::Arc; #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Copy, Debug, PartialEq, Primitive)] pub enum SocketType { PAIR = 0, PUB = 1, SUB = 2, REQ = 3, REP = 4, DEALER = 5, ROUTER = 6, PULL = 7, PUSH = 8, XPUB = 9, XSUB = 10, STREAM = 11, } impl TryFrom<&str> for SocketType { type Error = ZmqError; fn try_from(s: &str) -> Result<Self, ZmqError> { Ok(match s { "PAIR" => SocketType::PAIR, "PUB" => SocketType::PUB, "SUB" => SocketType::SUB, "REQ" => SocketType::REQ, "REP" => SocketType::REP, "DEALER" => SocketType::DEALER, "ROUTER" => SocketType::ROUTER, "PULL" => SocketType::PULL, "PUSH" => SocketType::PUSH, "XPUB" => SocketType::XPUB, "XSUB" => SocketType::XSUB, "STREAM" => SocketType::STREAM, _ => return Err(ZmqError::Other("Unknown socket type")), }) } } impl Display for SocketType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SocketType::PAIR => write!(f, "PAIR"), SocketType::PUB => write!(f, "PUB"), SocketType::SUB => write!(f, "SUB"), SocketType::REQ => write!(f, "REQ"), SocketType::REP => write!(f, "REP"), SocketType::DEALER => write!(f, "DEALER"), SocketType::ROUTER => write!(f, "ROUTER"), SocketType::PULL => write!(f, "PULL"), SocketType::PUSH => write!(f, "PUSH"), SocketType::XPUB => write!(f, "XPUB"), SocketType::XSUB => write!(f, "XSUB"), SocketType::STREAM => write!(f, "STREAM"), } } } #[derive(Debug)] pub enum SocketEvent { Connected(Endpoint, PeerIdentity), ConnectDelayed, ConnectRetried, Listening(Endpoint), Accepted(Endpoint, PeerIdentity), AcceptFailed(ZmqError), Closed, CloseFailed, Disconnected(PeerIdentity), } #[derive(Default)] pub struct SocketOptions { pub(crate) peer_id: Option<PeerIdentity>, } impl SocketOptions { pub fn peer_identity(&mut self, peer_id: PeerIdentity) -> &mut Self { self.peer_id = Some(peer_id); self } } #[async_trait] pub trait MultiPeerBackend: SocketBackend { /// This should not be public.. /// Find a better way of doing this async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo); fn peer_disconnected(&self, peer_id: &PeerIdentity); } pub trait SocketBackend: Send + Sync { fn socket_type(&self) -> SocketType; fn socket_options(&self) -> &SocketOptions; fn shutdown(&self); fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>>; } #[async_trait] pub trait SocketRecv { async fn recv(&mut self) -> ZmqResult<ZmqMessage>; } #[async_trait] pub trait SocketSend { async fn send(&mut self, message: ZmqMessage) -> ZmqResult<()>; } /// Marker trait that express the fact that only certain types of sockets might be used /// in [proxy] function as a capture parameter pub trait CaptureSocket: SocketSend {} #[async_trait] pub trait Socket: Sized + Send { fn new() -> Self { Self::with_options(SocketOptions::default()) } fn with_options(options: SocketOptions) -> Self; fn backend(&self) -> Arc<dyn MultiPeerBackend>; /// Binds to the endpoint and starts a coroutine to accept new connections /// on it. /// /// Returns the endpoint resolved to the exact bound location if applicable /// (port # resolved, for example). async fn bind(&mut self, endpoint: &str) -> ZmqResult<Endpoint> { let endpoint = endpoint.try_into()?; let cloned_backend = self.backend(); let cback = move |result| { let cloned_backend = cloned_backend.clone(); async move { let result = match result { Ok((socket, endpoint)) => { match util::peer_connected(socket, cloned_backend.clone()).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), } } Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Accepted(endpoint, peer_id)); } } Err(e) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::AcceptFailed(e)); } } } } }; let (endpoint, stop_handle) = transport::begin_accept(endpoint, cback).await?; if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Listening(endpoint.clone())); } self.binds().insert(endpoint.clone(), stop_handle); Ok(endpoint) } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle>; /// Unbinds the endpoint, blocking until the associated endpoint is no /// longer in use /// /// # Errors /// May give a `ZmqError::NoSuchBind` if `endpoint` isn't bound. May also /// give any other zmq errors encountered when attempting to disconnect async fn unbind(&mut self, endpoint: Endpoint) -> ZmqResult<()> { let stop_handle = self.binds().remove(&endpoint); let stop_handle = stop_handle.ok_or(ZmqError::NoSuchBind(endpoint))?; stop_handle.0.shutdown().await } /// Unbinds all bound endpoints, blocking until finished. async fn unbind_all(&mut self) -> Vec<ZmqError> { let mut errs = Vec::new(); let endpoints: Vec<_> = self .binds() .iter() .map(|(endpoint, _)| endpoint.clone()) .collect(); for endpoint in endpoints { if let Err(err) = self.unbind(endpoint).await { errs.push(err);
errs } /// Connects to the given endpoint. async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> { let backend = self.backend(); let endpoint = endpoint.try_into()?; let result = match util::connect_forever(endpoint).await { Ok((socket, endpoint)) => match util::peer_connected(socket, backend).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), }, Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Connected(endpoint, peer_id)); } Ok(()) } Err(e) => Err(e), } } /// Creates and setups new socket monitor /// /// Subsequent calls to this method each create a new monitor channel. /// Sender side of previous one is dropped. fn monitor(&mut self) -> mpsc::Receiver<SocketEvent>; // TODO: async fn connections(&self) ->? /// Disconnects from the given endpoint, blocking until finished. /// /// # Errors /// May give a `ZmqError::NoSuchConnection` if `endpoint` isn't connected. /// May also give any other zmq errors encountered when attempting to /// disconnect. // TODO: async fn disconnect(&mut self, endpoint: impl TryIntoEndpoint + 'async_trait) -> // ZmqResult<()>; /// Disconnects all connecttions, blocking until finished. // TODO: async fn disconnect_all(&mut self) -> ZmqResult<()>; /// Closes the socket, blocking until all associated binds are closed. /// This is equivalent to `drop()`, but with the benefit of blocking until /// resources are released, and getting any underlying errors. /// /// Returns any encountered errors. // TODO: Call disconnect_all() when added async fn close(mut self) -> Vec<ZmqError> { // self.disconnect_all().await?; self.unbind_all().await } } pub async fn proxy<Frontend: SocketSend + SocketRecv, Backend: SocketSend + SocketRecv>( mut frontend: Frontend, mut backend: Backend, mut capture: Option<Box<dyn CaptureSocket>>, ) -> ZmqResult<()> { loop { futures::select! { frontend_mess = frontend.recv().fuse() => { match frontend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } backend.send(message).await?; } Err(_) => { todo!() } } }, backend_mess = backend.recv().fuse() => { match backend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } frontend.send(message).await?; } Err(_) => { todo!() } } } }; } } pub mod prelude { //! Re-exports important traits. Consider glob-importing. pub use crate::{Socket, SocketRecv, SocketSend, TryIntoEndpoint}; }
} }
random_line_split
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLEMENTATION, EXPOSED ONLY FOR INTEGRATION TESTS. pub use super::async_rt::*; } pub use crate::dealer::*; pub use crate::endpoint::{Endpoint, Host, Transport, TryIntoEndpoint}; pub use crate::error::{ZmqError, ZmqResult}; pub use crate::pull::*; pub use crate::push::*; pub use crate::r#pub::*; pub use crate::rep::*; pub use crate::req::*; pub use crate::router::*; pub use crate::sub::*; pub use message::*; use crate::codec::*; use crate::transport::AcceptStopHandle; use util::PeerIdentity; #[macro_use] extern crate enum_primitive_derive; use async_trait::async_trait; use asynchronous_codec::FramedWrite; use futures::channel::mpsc; use futures::FutureExt; use num_traits::ToPrimitive; use parking_lot::Mutex; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt::{Debug, Display}; use std::sync::Arc; #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Copy, Debug, PartialEq, Primitive)] pub enum SocketType { PAIR = 0, PUB = 1, SUB = 2, REQ = 3, REP = 4, DEALER = 5, ROUTER = 6, PULL = 7, PUSH = 8, XPUB = 9, XSUB = 10, STREAM = 11, } impl TryFrom<&str> for SocketType { type Error = ZmqError; fn try_from(s: &str) -> Result<Self, ZmqError> { Ok(match s { "PAIR" => SocketType::PAIR, "PUB" => SocketType::PUB, "SUB" => SocketType::SUB, "REQ" => SocketType::REQ, "REP" => SocketType::REP, "DEALER" => SocketType::DEALER, "ROUTER" => SocketType::ROUTER, "PULL" => SocketType::PULL, "PUSH" => SocketType::PUSH, "XPUB" => SocketType::XPUB, "XSUB" => SocketType::XSUB, "STREAM" => SocketType::STREAM, _ => return Err(ZmqError::Other("Unknown socket type")), }) } } impl Display for SocketType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SocketType::PAIR => write!(f, "PAIR"), SocketType::PUB => write!(f, "PUB"), SocketType::SUB => write!(f, "SUB"), SocketType::REQ => write!(f, "REQ"), SocketType::REP => write!(f, "REP"), SocketType::DEALER => write!(f, "DEALER"), SocketType::ROUTER => write!(f, "ROUTER"), SocketType::PULL => write!(f, "PULL"), SocketType::PUSH => write!(f, "PUSH"), SocketType::XPUB => write!(f, "XPUB"), SocketType::XSUB => write!(f, "XSUB"), SocketType::STREAM => write!(f, "STREAM"), } } } #[derive(Debug)] pub enum SocketEvent { Connected(Endpoint, PeerIdentity), ConnectDelayed, ConnectRetried, Listening(Endpoint), Accepted(Endpoint, PeerIdentity), AcceptFailed(ZmqError), Closed, CloseFailed, Disconnected(PeerIdentity), } #[derive(Default)] pub struct
{ pub(crate) peer_id: Option<PeerIdentity>, } impl SocketOptions { pub fn peer_identity(&mut self, peer_id: PeerIdentity) -> &mut Self { self.peer_id = Some(peer_id); self } } #[async_trait] pub trait MultiPeerBackend: SocketBackend { /// This should not be public.. /// Find a better way of doing this async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo); fn peer_disconnected(&self, peer_id: &PeerIdentity); } pub trait SocketBackend: Send + Sync { fn socket_type(&self) -> SocketType; fn socket_options(&self) -> &SocketOptions; fn shutdown(&self); fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>>; } #[async_trait] pub trait SocketRecv { async fn recv(&mut self) -> ZmqResult<ZmqMessage>; } #[async_trait] pub trait SocketSend { async fn send(&mut self, message: ZmqMessage) -> ZmqResult<()>; } /// Marker trait that express the fact that only certain types of sockets might be used /// in [proxy] function as a capture parameter pub trait CaptureSocket: SocketSend {} #[async_trait] pub trait Socket: Sized + Send { fn new() -> Self { Self::with_options(SocketOptions::default()) } fn with_options(options: SocketOptions) -> Self; fn backend(&self) -> Arc<dyn MultiPeerBackend>; /// Binds to the endpoint and starts a coroutine to accept new connections /// on it. /// /// Returns the endpoint resolved to the exact bound location if applicable /// (port # resolved, for example). async fn bind(&mut self, endpoint: &str) -> ZmqResult<Endpoint> { let endpoint = endpoint.try_into()?; let cloned_backend = self.backend(); let cback = move |result| { let cloned_backend = cloned_backend.clone(); async move { let result = match result { Ok((socket, endpoint)) => { match util::peer_connected(socket, cloned_backend.clone()).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), } } Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Accepted(endpoint, peer_id)); } } Err(e) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::AcceptFailed(e)); } } } } }; let (endpoint, stop_handle) = transport::begin_accept(endpoint, cback).await?; if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Listening(endpoint.clone())); } self.binds().insert(endpoint.clone(), stop_handle); Ok(endpoint) } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle>; /// Unbinds the endpoint, blocking until the associated endpoint is no /// longer in use /// /// # Errors /// May give a `ZmqError::NoSuchBind` if `endpoint` isn't bound. May also /// give any other zmq errors encountered when attempting to disconnect async fn unbind(&mut self, endpoint: Endpoint) -> ZmqResult<()> { let stop_handle = self.binds().remove(&endpoint); let stop_handle = stop_handle.ok_or(ZmqError::NoSuchBind(endpoint))?; stop_handle.0.shutdown().await } /// Unbinds all bound endpoints, blocking until finished. async fn unbind_all(&mut self) -> Vec<ZmqError> { let mut errs = Vec::new(); let endpoints: Vec<_> = self .binds() .iter() .map(|(endpoint, _)| endpoint.clone()) .collect(); for endpoint in endpoints { if let Err(err) = self.unbind(endpoint).await { errs.push(err); } } errs } /// Connects to the given endpoint. async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> { let backend = self.backend(); let endpoint = endpoint.try_into()?; let result = match util::connect_forever(endpoint).await { Ok((socket, endpoint)) => match util::peer_connected(socket, backend).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), }, Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Connected(endpoint, peer_id)); } Ok(()) } Err(e) => Err(e), } } /// Creates and setups new socket monitor /// /// Subsequent calls to this method each create a new monitor channel. /// Sender side of previous one is dropped. fn monitor(&mut self) -> mpsc::Receiver<SocketEvent>; // TODO: async fn connections(&self) ->? /// Disconnects from the given endpoint, blocking until finished. /// /// # Errors /// May give a `ZmqError::NoSuchConnection` if `endpoint` isn't connected. /// May also give any other zmq errors encountered when attempting to /// disconnect. // TODO: async fn disconnect(&mut self, endpoint: impl TryIntoEndpoint + 'async_trait) -> // ZmqResult<()>; /// Disconnects all connecttions, blocking until finished. // TODO: async fn disconnect_all(&mut self) -> ZmqResult<()>; /// Closes the socket, blocking until all associated binds are closed. /// This is equivalent to `drop()`, but with the benefit of blocking until /// resources are released, and getting any underlying errors. /// /// Returns any encountered errors. // TODO: Call disconnect_all() when added async fn close(mut self) -> Vec<ZmqError> { // self.disconnect_all().await?; self.unbind_all().await } } pub async fn proxy<Frontend: SocketSend + SocketRecv, Backend: SocketSend + SocketRecv>( mut frontend: Frontend, mut backend: Backend, mut capture: Option<Box<dyn CaptureSocket>>, ) -> ZmqResult<()> { loop { futures::select! { frontend_mess = frontend.recv().fuse() => { match frontend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } backend.send(message).await?; } Err(_) => { todo!() } } }, backend_mess = backend.recv().fuse() => { match backend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } frontend.send(message).await?; } Err(_) => { todo!() } } } }; } } pub mod prelude { //! Re-exports important traits. Consider glob-importing. pub use crate::{Socket, SocketRecv, SocketSend, TryIntoEndpoint}; }
SocketOptions
identifier_name
lib.rs
#![recursion_limit = "1024"] mod async_rt; mod backend; mod codec; mod dealer; mod endpoint; mod error; mod fair_queue; mod message; mod r#pub; mod pull; mod push; mod rep; mod req; mod router; mod sub; mod task_handle; mod transport; pub mod util; #[doc(hidden)] pub mod __async_rt { //! DO NOT USE! PRIVATE IMPLEMENTATION, EXPOSED ONLY FOR INTEGRATION TESTS. pub use super::async_rt::*; } pub use crate::dealer::*; pub use crate::endpoint::{Endpoint, Host, Transport, TryIntoEndpoint}; pub use crate::error::{ZmqError, ZmqResult}; pub use crate::pull::*; pub use crate::push::*; pub use crate::r#pub::*; pub use crate::rep::*; pub use crate::req::*; pub use crate::router::*; pub use crate::sub::*; pub use message::*; use crate::codec::*; use crate::transport::AcceptStopHandle; use util::PeerIdentity; #[macro_use] extern crate enum_primitive_derive; use async_trait::async_trait; use asynchronous_codec::FramedWrite; use futures::channel::mpsc; use futures::FutureExt; use num_traits::ToPrimitive; use parking_lot::Mutex; use std::collections::HashMap; use std::convert::TryFrom; use std::fmt::{Debug, Display}; use std::sync::Arc; #[allow(clippy::upper_case_acronyms)] #[derive(Clone, Copy, Debug, PartialEq, Primitive)] pub enum SocketType { PAIR = 0, PUB = 1, SUB = 2, REQ = 3, REP = 4, DEALER = 5, ROUTER = 6, PULL = 7, PUSH = 8, XPUB = 9, XSUB = 10, STREAM = 11, } impl TryFrom<&str> for SocketType { type Error = ZmqError; fn try_from(s: &str) -> Result<Self, ZmqError> { Ok(match s { "PAIR" => SocketType::PAIR, "PUB" => SocketType::PUB, "SUB" => SocketType::SUB, "REQ" => SocketType::REQ, "REP" => SocketType::REP, "DEALER" => SocketType::DEALER, "ROUTER" => SocketType::ROUTER, "PULL" => SocketType::PULL, "PUSH" => SocketType::PUSH, "XPUB" => SocketType::XPUB, "XSUB" => SocketType::XSUB, "STREAM" => SocketType::STREAM, _ => return Err(ZmqError::Other("Unknown socket type")), }) } } impl Display for SocketType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { SocketType::PAIR => write!(f, "PAIR"), SocketType::PUB => write!(f, "PUB"), SocketType::SUB => write!(f, "SUB"), SocketType::REQ => write!(f, "REQ"), SocketType::REP => write!(f, "REP"), SocketType::DEALER => write!(f, "DEALER"), SocketType::ROUTER => write!(f, "ROUTER"), SocketType::PULL => write!(f, "PULL"), SocketType::PUSH => write!(f, "PUSH"), SocketType::XPUB => write!(f, "XPUB"), SocketType::XSUB => write!(f, "XSUB"), SocketType::STREAM => write!(f, "STREAM"), } } } #[derive(Debug)] pub enum SocketEvent { Connected(Endpoint, PeerIdentity), ConnectDelayed, ConnectRetried, Listening(Endpoint), Accepted(Endpoint, PeerIdentity), AcceptFailed(ZmqError), Closed, CloseFailed, Disconnected(PeerIdentity), } #[derive(Default)] pub struct SocketOptions { pub(crate) peer_id: Option<PeerIdentity>, } impl SocketOptions { pub fn peer_identity(&mut self, peer_id: PeerIdentity) -> &mut Self { self.peer_id = Some(peer_id); self } } #[async_trait] pub trait MultiPeerBackend: SocketBackend { /// This should not be public.. /// Find a better way of doing this async fn peer_connected(self: Arc<Self>, peer_id: &PeerIdentity, io: FramedIo); fn peer_disconnected(&self, peer_id: &PeerIdentity); } pub trait SocketBackend: Send + Sync { fn socket_type(&self) -> SocketType; fn socket_options(&self) -> &SocketOptions; fn shutdown(&self); fn monitor(&self) -> &Mutex<Option<mpsc::Sender<SocketEvent>>>; } #[async_trait] pub trait SocketRecv { async fn recv(&mut self) -> ZmqResult<ZmqMessage>; } #[async_trait] pub trait SocketSend { async fn send(&mut self, message: ZmqMessage) -> ZmqResult<()>; } /// Marker trait that express the fact that only certain types of sockets might be used /// in [proxy] function as a capture parameter pub trait CaptureSocket: SocketSend {} #[async_trait] pub trait Socket: Sized + Send { fn new() -> Self { Self::with_options(SocketOptions::default()) } fn with_options(options: SocketOptions) -> Self; fn backend(&self) -> Arc<dyn MultiPeerBackend>; /// Binds to the endpoint and starts a coroutine to accept new connections /// on it. /// /// Returns the endpoint resolved to the exact bound location if applicable /// (port # resolved, for example). async fn bind(&mut self, endpoint: &str) -> ZmqResult<Endpoint>
} } Err(e) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::AcceptFailed(e)); } } } } }; let (endpoint, stop_handle) = transport::begin_accept(endpoint, cback).await?; if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Listening(endpoint.clone())); } self.binds().insert(endpoint.clone(), stop_handle); Ok(endpoint) } fn binds(&mut self) -> &mut HashMap<Endpoint, AcceptStopHandle>; /// Unbinds the endpoint, blocking until the associated endpoint is no /// longer in use /// /// # Errors /// May give a `ZmqError::NoSuchBind` if `endpoint` isn't bound. May also /// give any other zmq errors encountered when attempting to disconnect async fn unbind(&mut self, endpoint: Endpoint) -> ZmqResult<()> { let stop_handle = self.binds().remove(&endpoint); let stop_handle = stop_handle.ok_or(ZmqError::NoSuchBind(endpoint))?; stop_handle.0.shutdown().await } /// Unbinds all bound endpoints, blocking until finished. async fn unbind_all(&mut self) -> Vec<ZmqError> { let mut errs = Vec::new(); let endpoints: Vec<_> = self .binds() .iter() .map(|(endpoint, _)| endpoint.clone()) .collect(); for endpoint in endpoints { if let Err(err) = self.unbind(endpoint).await { errs.push(err); } } errs } /// Connects to the given endpoint. async fn connect(&mut self, endpoint: &str) -> ZmqResult<()> { let backend = self.backend(); let endpoint = endpoint.try_into()?; let result = match util::connect_forever(endpoint).await { Ok((socket, endpoint)) => match util::peer_connected(socket, backend).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), }, Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = self.backend().monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Connected(endpoint, peer_id)); } Ok(()) } Err(e) => Err(e), } } /// Creates and setups new socket monitor /// /// Subsequent calls to this method each create a new monitor channel. /// Sender side of previous one is dropped. fn monitor(&mut self) -> mpsc::Receiver<SocketEvent>; // TODO: async fn connections(&self) ->? /// Disconnects from the given endpoint, blocking until finished. /// /// # Errors /// May give a `ZmqError::NoSuchConnection` if `endpoint` isn't connected. /// May also give any other zmq errors encountered when attempting to /// disconnect. // TODO: async fn disconnect(&mut self, endpoint: impl TryIntoEndpoint + 'async_trait) -> // ZmqResult<()>; /// Disconnects all connecttions, blocking until finished. // TODO: async fn disconnect_all(&mut self) -> ZmqResult<()>; /// Closes the socket, blocking until all associated binds are closed. /// This is equivalent to `drop()`, but with the benefit of blocking until /// resources are released, and getting any underlying errors. /// /// Returns any encountered errors. // TODO: Call disconnect_all() when added async fn close(mut self) -> Vec<ZmqError> { // self.disconnect_all().await?; self.unbind_all().await } } pub async fn proxy<Frontend: SocketSend + SocketRecv, Backend: SocketSend + SocketRecv>( mut frontend: Frontend, mut backend: Backend, mut capture: Option<Box<dyn CaptureSocket>>, ) -> ZmqResult<()> { loop { futures::select! { frontend_mess = frontend.recv().fuse() => { match frontend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } backend.send(message).await?; } Err(_) => { todo!() } } }, backend_mess = backend.recv().fuse() => { match backend_mess { Ok(message) => { if let Some(capture) = &mut capture { capture.send(message.clone()).await?; } frontend.send(message).await?; } Err(_) => { todo!() } } } }; } } pub mod prelude { //! Re-exports important traits. Consider glob-importing. pub use crate::{Socket, SocketRecv, SocketSend, TryIntoEndpoint}; }
{ let endpoint = endpoint.try_into()?; let cloned_backend = self.backend(); let cback = move |result| { let cloned_backend = cloned_backend.clone(); async move { let result = match result { Ok((socket, endpoint)) => { match util::peer_connected(socket, cloned_backend.clone()).await { Ok(peer_id) => Ok((endpoint, peer_id)), Err(e) => Err(e), } } Err(e) => Err(e), }; match result { Ok((endpoint, peer_id)) => { if let Some(monitor) = cloned_backend.monitor().lock().as_mut() { let _ = monitor.try_send(SocketEvent::Accepted(endpoint, peer_id));
identifier_body
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { // Interior mutability is desirable so that we can clone the TNC and have // different threads sending and receiving concurrently. tx_stream: Mutex<TcpStream>, rx_stream: Mutex<TcpStream>, buffer: Mutex<Vec<u8>>, is_shutdown: AtomicBool, } impl TcpKissInterface { pub(crate) fn
<A: ToSocketAddrs>(addr: A) -> io::Result<TcpKissInterface> { let tx_stream = TcpStream::connect(addr)?; let rx_stream = tx_stream.try_clone()?; Ok(TcpKissInterface { tx_stream: Mutex::new(tx_stream), rx_stream: Mutex::new(rx_stream), buffer: Mutex::new(Vec::new()), is_shutdown: AtomicBool::new(false), }) } pub(crate) fn receive_frame(&self) -> io::Result<Vec<u8>> { loop { { let mut buffer = self.buffer.lock().unwrap(); if let Some(frame) = make_frame_from_buffer(&mut buffer) { return Ok(frame); } } let mut buf = vec![0u8; 1024]; let n_bytes = { let mut rx_stream = self.rx_stream.lock().unwrap(); rx_stream.read(&mut buf)? }; { let mut buffer = self.buffer.lock().unwrap(); buffer.extend(buf.iter().take(n_bytes)); } } } pub(crate) fn send_frame(&self, frame: &[u8]) -> io::Result<()> { let mut tx_stream = self.tx_stream.lock().unwrap(); // 0x00 is the KISS command byte, which is two nybbles // port = 0 // command = 0 (all following bytes are a data frame to transmit) tx_stream.write_all(&[FEND, 0x00])?; tx_stream.write_all(frame)?; tx_stream.write_all(&[FEND])?; tx_stream.flush()?; Ok(()) } pub(crate) fn shutdown(&self) { if!self.is_shutdown.load(Ordering::SeqCst) { self.is_shutdown.store(true, Ordering::SeqCst); let tx_stream = self.tx_stream.lock().unwrap(); let _ = tx_stream.shutdown(Shutdown::Both); } } } impl Drop for TcpKissInterface { fn drop(&mut self) { self.shutdown(); } } fn make_frame_from_buffer(buffer: &mut Vec<u8>) -> Option<Vec<u8>> { let mut possible_frame = Vec::new(); enum Scan { LookingForStartMarker, Data, Escaped, } let mut state = Scan::LookingForStartMarker; let mut final_idx = 0; // Check for possible frame read-only until we know we have a complete frame // If we take one out, clear out buffer up to the final index for (idx, &c) in buffer.iter().enumerate() { match state { Scan::LookingForStartMarker => { if c == FEND { state = Scan::Data; } } Scan::Data => { if c == FEND { if!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } } else if c == FESC { state = Scan::Escaped; } else { possible_frame.push(c); } } Scan::Escaped => { if c == TFEND { possible_frame.push(FEND); } else if c == TFESC { possible_frame.push(FESC); } else if c == FEND &&!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } state = Scan::Data; } } } match final_idx { 0 => None, n => { // Draining up to "n" will leave the final FEND in place // This way we can use it as the start marker for the next frame buffer.drain(0..n); Some(possible_frame) } } } #[test] fn test_normal_frame() { let mut rx = vec![FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_trailing_data() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND, 0x03, 0x04]); } #[test] fn test_leading_data() { let mut rx = vec![0x03, 0x04, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_consecutive_marker() { let mut rx = vec![FEND, FEND, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_escapes() { let mut rx = vec![FEND, 0x01, FESC, TFESC, 0x02, FESC, TFEND, 0x03, FEND]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, FESC, 0x02, FEND, 0x03]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_incorrect_escape_skipped() { let mut rx = vec![ FEND, 0x01, FESC, 0x04, TFESC, /* passes normally without leading FESC */ 0x02, FEND, ]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, TFESC, 0x02]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_single_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_double_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); }
new
identifier_name
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { // Interior mutability is desirable so that we can clone the TNC and have // different threads sending and receiving concurrently. tx_stream: Mutex<TcpStream>, rx_stream: Mutex<TcpStream>, buffer: Mutex<Vec<u8>>, is_shutdown: AtomicBool, } impl TcpKissInterface { pub(crate) fn new<A: ToSocketAddrs>(addr: A) -> io::Result<TcpKissInterface> { let tx_stream = TcpStream::connect(addr)?; let rx_stream = tx_stream.try_clone()?; Ok(TcpKissInterface { tx_stream: Mutex::new(tx_stream), rx_stream: Mutex::new(rx_stream), buffer: Mutex::new(Vec::new()), is_shutdown: AtomicBool::new(false), }) } pub(crate) fn receive_frame(&self) -> io::Result<Vec<u8>> { loop { { let mut buffer = self.buffer.lock().unwrap(); if let Some(frame) = make_frame_from_buffer(&mut buffer) { return Ok(frame); } } let mut buf = vec![0u8; 1024]; let n_bytes = { let mut rx_stream = self.rx_stream.lock().unwrap(); rx_stream.read(&mut buf)? }; { let mut buffer = self.buffer.lock().unwrap(); buffer.extend(buf.iter().take(n_bytes)); } } } pub(crate) fn send_frame(&self, frame: &[u8]) -> io::Result<()> { let mut tx_stream = self.tx_stream.lock().unwrap(); // 0x00 is the KISS command byte, which is two nybbles // port = 0 // command = 0 (all following bytes are a data frame to transmit) tx_stream.write_all(&[FEND, 0x00])?; tx_stream.write_all(frame)?; tx_stream.write_all(&[FEND])?; tx_stream.flush()?; Ok(()) } pub(crate) fn shutdown(&self) { if!self.is_shutdown.load(Ordering::SeqCst) { self.is_shutdown.store(true, Ordering::SeqCst); let tx_stream = self.tx_stream.lock().unwrap(); let _ = tx_stream.shutdown(Shutdown::Both); } } } impl Drop for TcpKissInterface { fn drop(&mut self) { self.shutdown(); } } fn make_frame_from_buffer(buffer: &mut Vec<u8>) -> Option<Vec<u8>> { let mut possible_frame = Vec::new(); enum Scan { LookingForStartMarker, Data, Escaped, } let mut state = Scan::LookingForStartMarker; let mut final_idx = 0; // Check for possible frame read-only until we know we have a complete frame // If we take one out, clear out buffer up to the final index for (idx, &c) in buffer.iter().enumerate() { match state { Scan::LookingForStartMarker => { if c == FEND { state = Scan::Data; } } Scan::Data => { if c == FEND { if!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } } else if c == FESC { state = Scan::Escaped; } else { possible_frame.push(c); } } Scan::Escaped => { if c == TFEND { possible_frame.push(FEND); } else if c == TFESC { possible_frame.push(FESC); } else if c == FEND &&!possible_frame.is_empty()
state = Scan::Data; } } } match final_idx { 0 => None, n => { // Draining up to "n" will leave the final FEND in place // This way we can use it as the start marker for the next frame buffer.drain(0..n); Some(possible_frame) } } } #[test] fn test_normal_frame() { let mut rx = vec![FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_trailing_data() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND, 0x03, 0x04]); } #[test] fn test_leading_data() { let mut rx = vec![0x03, 0x04, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_consecutive_marker() { let mut rx = vec![FEND, FEND, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_escapes() { let mut rx = vec![FEND, 0x01, FESC, TFESC, 0x02, FESC, TFEND, 0x03, FEND]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, FESC, 0x02, FEND, 0x03]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_incorrect_escape_skipped() { let mut rx = vec![ FEND, 0x01, FESC, 0x04, TFESC, /* passes normally without leading FESC */ 0x02, FEND, ]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, TFESC, 0x02]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_single_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_double_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); }
{ // Successfully read a non-zero-length frame final_idx = idx; break; }
conditional_block
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { // Interior mutability is desirable so that we can clone the TNC and have // different threads sending and receiving concurrently. tx_stream: Mutex<TcpStream>, rx_stream: Mutex<TcpStream>, buffer: Mutex<Vec<u8>>, is_shutdown: AtomicBool, } impl TcpKissInterface { pub(crate) fn new<A: ToSocketAddrs>(addr: A) -> io::Result<TcpKissInterface>
pub(crate) fn receive_frame(&self) -> io::Result<Vec<u8>> { loop { { let mut buffer = self.buffer.lock().unwrap(); if let Some(frame) = make_frame_from_buffer(&mut buffer) { return Ok(frame); } } let mut buf = vec![0u8; 1024]; let n_bytes = { let mut rx_stream = self.rx_stream.lock().unwrap(); rx_stream.read(&mut buf)? }; { let mut buffer = self.buffer.lock().unwrap(); buffer.extend(buf.iter().take(n_bytes)); } } } pub(crate) fn send_frame(&self, frame: &[u8]) -> io::Result<()> { let mut tx_stream = self.tx_stream.lock().unwrap(); // 0x00 is the KISS command byte, which is two nybbles // port = 0 // command = 0 (all following bytes are a data frame to transmit) tx_stream.write_all(&[FEND, 0x00])?; tx_stream.write_all(frame)?; tx_stream.write_all(&[FEND])?; tx_stream.flush()?; Ok(()) } pub(crate) fn shutdown(&self) { if!self.is_shutdown.load(Ordering::SeqCst) { self.is_shutdown.store(true, Ordering::SeqCst); let tx_stream = self.tx_stream.lock().unwrap(); let _ = tx_stream.shutdown(Shutdown::Both); } } } impl Drop for TcpKissInterface { fn drop(&mut self) { self.shutdown(); } } fn make_frame_from_buffer(buffer: &mut Vec<u8>) -> Option<Vec<u8>> { let mut possible_frame = Vec::new(); enum Scan { LookingForStartMarker, Data, Escaped, } let mut state = Scan::LookingForStartMarker; let mut final_idx = 0; // Check for possible frame read-only until we know we have a complete frame // If we take one out, clear out buffer up to the final index for (idx, &c) in buffer.iter().enumerate() { match state { Scan::LookingForStartMarker => { if c == FEND { state = Scan::Data; } } Scan::Data => { if c == FEND { if!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } } else if c == FESC { state = Scan::Escaped; } else { possible_frame.push(c); } } Scan::Escaped => { if c == TFEND { possible_frame.push(FEND); } else if c == TFESC { possible_frame.push(FESC); } else if c == FEND &&!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } state = Scan::Data; } } } match final_idx { 0 => None, n => { // Draining up to "n" will leave the final FEND in place // This way we can use it as the start marker for the next frame buffer.drain(0..n); Some(possible_frame) } } } #[test] fn test_normal_frame() { let mut rx = vec![FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_trailing_data() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND, 0x03, 0x04]); } #[test] fn test_leading_data() { let mut rx = vec![0x03, 0x04, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_consecutive_marker() { let mut rx = vec![FEND, FEND, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_escapes() { let mut rx = vec![FEND, 0x01, FESC, TFESC, 0x02, FESC, TFEND, 0x03, FEND]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, FESC, 0x02, FEND, 0x03]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_incorrect_escape_skipped() { let mut rx = vec![ FEND, 0x01, FESC, 0x04, TFESC, /* passes normally without leading FESC */ 0x02, FEND, ]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, TFESC, 0x02]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_single_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_double_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); }
{ let tx_stream = TcpStream::connect(addr)?; let rx_stream = tx_stream.try_clone()?; Ok(TcpKissInterface { tx_stream: Mutex::new(tx_stream), rx_stream: Mutex::new(rx_stream), buffer: Mutex::new(Vec::new()), is_shutdown: AtomicBool::new(false), }) }
identifier_body
kiss.rs
use std::io; use std::io::prelude::*; use std::net::Shutdown; use std::net::TcpStream; use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; const FEND: u8 = 0xC0; const FESC: u8 = 0xDB; const TFEND: u8 = 0xDC; const TFESC: u8 = 0xDD; pub(crate) struct TcpKissInterface { // Interior mutability is desirable so that we can clone the TNC and have // different threads sending and receiving concurrently. tx_stream: Mutex<TcpStream>, rx_stream: Mutex<TcpStream>, buffer: Mutex<Vec<u8>>, is_shutdown: AtomicBool, } impl TcpKissInterface { pub(crate) fn new<A: ToSocketAddrs>(addr: A) -> io::Result<TcpKissInterface> { let tx_stream = TcpStream::connect(addr)?; let rx_stream = tx_stream.try_clone()?; Ok(TcpKissInterface { tx_stream: Mutex::new(tx_stream), rx_stream: Mutex::new(rx_stream), buffer: Mutex::new(Vec::new()), is_shutdown: AtomicBool::new(false), }) } pub(crate) fn receive_frame(&self) -> io::Result<Vec<u8>> { loop { { let mut buffer = self.buffer.lock().unwrap(); if let Some(frame) = make_frame_from_buffer(&mut buffer) { return Ok(frame); } } let mut buf = vec![0u8; 1024]; let n_bytes = { let mut rx_stream = self.rx_stream.lock().unwrap(); rx_stream.read(&mut buf)? }; { let mut buffer = self.buffer.lock().unwrap(); buffer.extend(buf.iter().take(n_bytes)); } } } pub(crate) fn send_frame(&self, frame: &[u8]) -> io::Result<()> { let mut tx_stream = self.tx_stream.lock().unwrap(); // 0x00 is the KISS command byte, which is two nybbles // port = 0 // command = 0 (all following bytes are a data frame to transmit) tx_stream.write_all(&[FEND, 0x00])?; tx_stream.write_all(frame)?; tx_stream.write_all(&[FEND])?; tx_stream.flush()?; Ok(()) } pub(crate) fn shutdown(&self) { if!self.is_shutdown.load(Ordering::SeqCst) { self.is_shutdown.store(true, Ordering::SeqCst); let tx_stream = self.tx_stream.lock().unwrap(); let _ = tx_stream.shutdown(Shutdown::Both); } } } impl Drop for TcpKissInterface { fn drop(&mut self) { self.shutdown(); } } fn make_frame_from_buffer(buffer: &mut Vec<u8>) -> Option<Vec<u8>> { let mut possible_frame = Vec::new(); enum Scan { LookingForStartMarker, Data, Escaped, } let mut state = Scan::LookingForStartMarker; let mut final_idx = 0; // Check for possible frame read-only until we know we have a complete frame // If we take one out, clear out buffer up to the final index for (idx, &c) in buffer.iter().enumerate() { match state { Scan::LookingForStartMarker => { if c == FEND { state = Scan::Data; } } Scan::Data => { if c == FEND { if!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } } else if c == FESC { state = Scan::Escaped; } else { possible_frame.push(c); } } Scan::Escaped => { if c == TFEND { possible_frame.push(FEND); } else if c == TFESC { possible_frame.push(FESC); } else if c == FEND &&!possible_frame.is_empty() { // Successfully read a non-zero-length frame final_idx = idx; break; } state = Scan::Data; } } } match final_idx { 0 => None, n => { // Draining up to "n" will leave the final FEND in place // This way we can use it as the start marker for the next frame buffer.drain(0..n); Some(possible_frame) } } } #[test] fn test_normal_frame() { let mut rx = vec![FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_trailing_data() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
let mut rx = vec![0x03, 0x04, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_consecutive_marker() { let mut rx = vec![FEND, FEND, FEND, 0x01, 0x02, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(rx, vec![FEND]); } #[test] fn test_escapes() { let mut rx = vec![FEND, 0x01, FESC, TFESC, 0x02, FESC, TFEND, 0x03, FEND]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, FESC, 0x02, FEND, 0x03]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_incorrect_escape_skipped() { let mut rx = vec![ FEND, 0x01, FESC, 0x04, TFESC, /* passes normally without leading FESC */ 0x02, FEND, ]; assert_eq!( make_frame_from_buffer(&mut rx), Some(vec![0x01, TFESC, 0x02]) ); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_single_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); } #[test] fn test_two_frames_double_fend() { let mut rx = vec![FEND, 0x01, 0x02, FEND, FEND, 0x03, 0x04, FEND]; assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02])); assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04])); assert_eq!(rx, vec![FEND]); }
assert_eq!(rx, vec![FEND, 0x03, 0x04]); } #[test] fn test_leading_data() {
random_line_split
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let res = Vector::new(ab[1], -ab[0]); Unit::try_new(res, N::default_epsilon()) } /// Computes the normal of a counter-clock-wise triangle. /// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn
<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
ccw_face_normal
identifier_name
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>>
/// Computes the normal of a counter-clock-wise triangle. /// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
{ let ab = pts[1] - pts[0]; let res = Vector::new(ab[1], -ab[0]); Unit::try_new(res, N::default_epsilon()) }
identifier_body
ccw_face_normal.rs
use crate::math::{Point, Vector}; use na::{RealField, Unit}; /// Computes the direction pointing toward the right-hand-side of an oriented segment. /// /// Returns `None` if the segment is degenerate. #[inline] #[cfg(feature = "dim2")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 2]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let res = Vector::new(ab[1], -ab[0]); Unit::try_new(res, N::default_epsilon()) }
/// /// Returns `None` if the triangle is degenerate. #[inline] #[cfg(feature = "dim3")] pub fn ccw_face_normal<N: RealField>(pts: [&Point<N>; 3]) -> Option<Unit<Vector<N>>> { let ab = pts[1] - pts[0]; let ac = pts[2] - pts[0]; let res = ab.cross(&ac); Unit::try_new(res, N::default_epsilon()) }
/// Computes the normal of a counter-clock-wise triangle.
random_line_split
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See the [fontconfig developer reference][1] for more information. //! //! [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/t1.html #![feature(phase, unsafe_destructor)] extern crate "fontconfig-sys" as fontconfig; #[phase(plugin, link)] extern crate log; use fontconfig::FcPattern; use std::c_str::CString; use std::kinds::marker; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; static FC_INIT: Once = ONCE_INIT; fn fc_init() { FC_INIT.doit(|| assert_eq!(unsafe { fontconfig::FcInit() }, 1)); } /// A very high-level view of a font, only concerned with the name and its file location. /// /// ##Example /// ```rust,ignore /// let font = Font::find("freeserif", Some("italic")).unwrap(); /// println!("Name: {}\nPath: {}", font.name, font.path.display()); /// ``` #[allow(dead_code)] pub struct Font { /// The true name of this font pub name: String, /// The location of this font on the filesystem. pub path: Path, } impl Font { /// Find a font of the given `family` (e.g. Dejavu Sans, FreeSerif), /// optionally filtering by `style`. Both fields are case-insensitive. pub fn find(family: &str, style: Option<&str>) -> Option<Font> { let mut pat = Pattern::new(); pat.add_string("family", family); if let Some(style) = style
let font_match = pat.font_match(); font_match.name().and_then(|name| font_match.filename().map(|filename| Font { name: name.into_string(), path: Path::new(filename), } )) } #[allow(dead_code)] fn print_debug(&self) { debug!("Name: {}\nPath: {}", self.name, self.path.display()); } } /// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern, /// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { fc_init(); Pattern { _m: marker::ContravariantLifetime, pat: unsafe{ fontconfig::FcPatternCreate() }, strings: Vec::new(), } } fn from_pattern(pat: *mut FcPattern) -> Pattern<'a> { unsafe { fontconfig::FcPatternReference(pat); } Pattern { _m: marker::ContravariantLifetime, pat: pat, strings: Vec::new(), } } /// Add a key-value pair to this pattern. /// /// See useful keys in the [fontconfig reference][1]. /// /// [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/x19.html pub fn add_string(&mut self, name: &str, val: &str) { let c_name = name.to_c_str(); // `val` is copied inside fontconfig so no need to allocate it again. val.with_c_str(|c_str| unsafe { fontconfig::FcPatternAddString(self.pat, c_name.as_ptr(), c_str as *const u8); }); self.strings.push(c_name); } /// Get the value for a key from this pattern. pub fn get_string<'a>(&'a self, name: &str) -> Option<&'a str> { name.with_c_str(|c_str| unsafe { let ret = mem::uninitialized(); if fontconfig::FcPatternGetString(&*self.pat, c_str, 0, ret) == 0 { Some(std::str::from_c_str(*ret as *const i8)) } else { None } }) } /// Print this pattern to stdout with all its values. #[allow(dead_code)] pub fn print(&self) { unsafe { fontconfig::FcPatternPrint(&*self.pat); } } fn default_substitute(&mut self) { unsafe { fontconfig::FcDefaultSubstitute(self.pat); } } fn config_substitute(&mut self) { unsafe { fontconfig::FcConfigSubstitute(ptr::null_mut(), self.pat, fontconfig::FcMatchPattern); } } /// Get the best available match for this pattern, returned as a new pattern. pub fn font_match<'a>(&'a mut self) -> Pattern<'a> { self.default_substitute(); self.config_substitute(); unsafe { let mut res = fontconfig::FcResultNoMatch; Pattern::from_pattern( fontconfig::FcFontMatch(ptr::null_mut(), self.pat, &mut res) ) } } /// Get the "fullname" (human-readable name) of this pattern. pub fn name(&self) -> Option<&str> { self.get_string("fullname") } /// Get the "file" (path on the filesystem) of this font pattern. pub fn filename(&self) -> Option<&str> { self.get_string("file") } } #[unsafe_destructor] impl<'a> Drop for Pattern<'a> { fn drop(&mut self) { unsafe { fontconfig::FcPatternDestroy(self.pat); } } } #[test] fn it_works() { fc_init(); } #[test] fn test_find_font() { Font::find("dejavu sans", None).unwrap().print_debug(); Font::find("dejavu sans", Some("oblique")).unwrap().print_debug(); }
{ pat.add_string("style", style); }
conditional_block
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See the [fontconfig developer reference][1] for more information. //! //! [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/t1.html #![feature(phase, unsafe_destructor)] extern crate "fontconfig-sys" as fontconfig; #[phase(plugin, link)] extern crate log; use fontconfig::FcPattern; use std::c_str::CString; use std::kinds::marker; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; static FC_INIT: Once = ONCE_INIT; fn fc_init() { FC_INIT.doit(|| assert_eq!(unsafe { fontconfig::FcInit() }, 1)); } /// A very high-level view of a font, only concerned with the name and its file location. /// /// ##Example /// ```rust,ignore /// let font = Font::find("freeserif", Some("italic")).unwrap(); /// println!("Name: {}\nPath: {}", font.name, font.path.display()); /// ``` #[allow(dead_code)] pub struct Font { /// The true name of this font pub name: String, /// The location of this font on the filesystem. pub path: Path, } impl Font { /// Find a font of the given `family` (e.g. Dejavu Sans, FreeSerif), /// optionally filtering by `style`. Both fields are case-insensitive. pub fn find(family: &str, style: Option<&str>) -> Option<Font> { let mut pat = Pattern::new(); pat.add_string("family", family); if let Some(style) = style { pat.add_string("style", style); } let font_match = pat.font_match(); font_match.name().and_then(|name| font_match.filename().map(|filename| Font { name: name.into_string(), path: Path::new(filename), } )) } #[allow(dead_code)] fn print_debug(&self) { debug!("Name: {}\nPath: {}", self.name, self.path.display()); } }
/// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { fc_init(); Pattern { _m: marker::ContravariantLifetime, pat: unsafe{ fontconfig::FcPatternCreate() }, strings: Vec::new(), } } fn from_pattern(pat: *mut FcPattern) -> Pattern<'a> { unsafe { fontconfig::FcPatternReference(pat); } Pattern { _m: marker::ContravariantLifetime, pat: pat, strings: Vec::new(), } } /// Add a key-value pair to this pattern. /// /// See useful keys in the [fontconfig reference][1]. /// /// [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/x19.html pub fn add_string(&mut self, name: &str, val: &str) { let c_name = name.to_c_str(); // `val` is copied inside fontconfig so no need to allocate it again. val.with_c_str(|c_str| unsafe { fontconfig::FcPatternAddString(self.pat, c_name.as_ptr(), c_str as *const u8); }); self.strings.push(c_name); } /// Get the value for a key from this pattern. pub fn get_string<'a>(&'a self, name: &str) -> Option<&'a str> { name.with_c_str(|c_str| unsafe { let ret = mem::uninitialized(); if fontconfig::FcPatternGetString(&*self.pat, c_str, 0, ret) == 0 { Some(std::str::from_c_str(*ret as *const i8)) } else { None } }) } /// Print this pattern to stdout with all its values. #[allow(dead_code)] pub fn print(&self) { unsafe { fontconfig::FcPatternPrint(&*self.pat); } } fn default_substitute(&mut self) { unsafe { fontconfig::FcDefaultSubstitute(self.pat); } } fn config_substitute(&mut self) { unsafe { fontconfig::FcConfigSubstitute(ptr::null_mut(), self.pat, fontconfig::FcMatchPattern); } } /// Get the best available match for this pattern, returned as a new pattern. pub fn font_match<'a>(&'a mut self) -> Pattern<'a> { self.default_substitute(); self.config_substitute(); unsafe { let mut res = fontconfig::FcResultNoMatch; Pattern::from_pattern( fontconfig::FcFontMatch(ptr::null_mut(), self.pat, &mut res) ) } } /// Get the "fullname" (human-readable name) of this pattern. pub fn name(&self) -> Option<&str> { self.get_string("fullname") } /// Get the "file" (path on the filesystem) of this font pattern. pub fn filename(&self) -> Option<&str> { self.get_string("file") } } #[unsafe_destructor] impl<'a> Drop for Pattern<'a> { fn drop(&mut self) { unsafe { fontconfig::FcPatternDestroy(self.pat); } } } #[test] fn it_works() { fc_init(); } #[test] fn test_find_font() { Font::find("dejavu sans", None).unwrap().print_debug(); Font::find("dejavu sans", Some("oblique")).unwrap().print_debug(); }
/// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern,
random_line_split
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See the [fontconfig developer reference][1] for more information. //! //! [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/t1.html #![feature(phase, unsafe_destructor)] extern crate "fontconfig-sys" as fontconfig; #[phase(plugin, link)] extern crate log; use fontconfig::FcPattern; use std::c_str::CString; use std::kinds::marker; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; static FC_INIT: Once = ONCE_INIT; fn fc_init() { FC_INIT.doit(|| assert_eq!(unsafe { fontconfig::FcInit() }, 1)); } /// A very high-level view of a font, only concerned with the name and its file location. /// /// ##Example /// ```rust,ignore /// let font = Font::find("freeserif", Some("italic")).unwrap(); /// println!("Name: {}\nPath: {}", font.name, font.path.display()); /// ``` #[allow(dead_code)] pub struct Font { /// The true name of this font pub name: String, /// The location of this font on the filesystem. pub path: Path, } impl Font { /// Find a font of the given `family` (e.g. Dejavu Sans, FreeSerif), /// optionally filtering by `style`. Both fields are case-insensitive. pub fn find(family: &str, style: Option<&str>) -> Option<Font> { let mut pat = Pattern::new(); pat.add_string("family", family); if let Some(style) = style { pat.add_string("style", style); } let font_match = pat.font_match(); font_match.name().and_then(|name| font_match.filename().map(|filename| Font { name: name.into_string(), path: Path::new(filename), } )) } #[allow(dead_code)] fn print_debug(&self)
} /// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern, /// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { fc_init(); Pattern { _m: marker::ContravariantLifetime, pat: unsafe{ fontconfig::FcPatternCreate() }, strings: Vec::new(), } } fn from_pattern(pat: *mut FcPattern) -> Pattern<'a> { unsafe { fontconfig::FcPatternReference(pat); } Pattern { _m: marker::ContravariantLifetime, pat: pat, strings: Vec::new(), } } /// Add a key-value pair to this pattern. /// /// See useful keys in the [fontconfig reference][1]. /// /// [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/x19.html pub fn add_string(&mut self, name: &str, val: &str) { let c_name = name.to_c_str(); // `val` is copied inside fontconfig so no need to allocate it again. val.with_c_str(|c_str| unsafe { fontconfig::FcPatternAddString(self.pat, c_name.as_ptr(), c_str as *const u8); }); self.strings.push(c_name); } /// Get the value for a key from this pattern. pub fn get_string<'a>(&'a self, name: &str) -> Option<&'a str> { name.with_c_str(|c_str| unsafe { let ret = mem::uninitialized(); if fontconfig::FcPatternGetString(&*self.pat, c_str, 0, ret) == 0 { Some(std::str::from_c_str(*ret as *const i8)) } else { None } }) } /// Print this pattern to stdout with all its values. #[allow(dead_code)] pub fn print(&self) { unsafe { fontconfig::FcPatternPrint(&*self.pat); } } fn default_substitute(&mut self) { unsafe { fontconfig::FcDefaultSubstitute(self.pat); } } fn config_substitute(&mut self) { unsafe { fontconfig::FcConfigSubstitute(ptr::null_mut(), self.pat, fontconfig::FcMatchPattern); } } /// Get the best available match for this pattern, returned as a new pattern. pub fn font_match<'a>(&'a mut self) -> Pattern<'a> { self.default_substitute(); self.config_substitute(); unsafe { let mut res = fontconfig::FcResultNoMatch; Pattern::from_pattern( fontconfig::FcFontMatch(ptr::null_mut(), self.pat, &mut res) ) } } /// Get the "fullname" (human-readable name) of this pattern. pub fn name(&self) -> Option<&str> { self.get_string("fullname") } /// Get the "file" (path on the filesystem) of this font pattern. pub fn filename(&self) -> Option<&str> { self.get_string("file") } } #[unsafe_destructor] impl<'a> Drop for Pattern<'a> { fn drop(&mut self) { unsafe { fontconfig::FcPatternDestroy(self.pat); } } } #[test] fn it_works() { fc_init(); } #[test] fn test_find_font() { Font::find("dejavu sans", None).unwrap().print_debug(); Font::find("dejavu sans", Some("oblique")).unwrap().print_debug(); }
{ debug!("Name: {}\nPath: {}", self.name, self.path.display()); }
identifier_body
lib.rs
//! A wrapper around freedesktop's `fontconfig` utility, for locating fontfiles on a //! Linux-based system. Requires `libfontconfig` to be installed. //! //! Use `Font` for a high-level search by family name and optional style (e.g. "FreeSerif" //! and "italic"), and `Pattern` for a more in-depth search. //! //! See the [fontconfig developer reference][1] for more information. //! //! [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/t1.html #![feature(phase, unsafe_destructor)] extern crate "fontconfig-sys" as fontconfig; #[phase(plugin, link)] extern crate log; use fontconfig::FcPattern; use std::c_str::CString; use std::kinds::marker; use std::mem; use std::ptr; use std::sync::{Once, ONCE_INIT}; static FC_INIT: Once = ONCE_INIT; fn fc_init() { FC_INIT.doit(|| assert_eq!(unsafe { fontconfig::FcInit() }, 1)); } /// A very high-level view of a font, only concerned with the name and its file location. /// /// ##Example /// ```rust,ignore /// let font = Font::find("freeserif", Some("italic")).unwrap(); /// println!("Name: {}\nPath: {}", font.name, font.path.display()); /// ``` #[allow(dead_code)] pub struct Font { /// The true name of this font pub name: String, /// The location of this font on the filesystem. pub path: Path, } impl Font { /// Find a font of the given `family` (e.g. Dejavu Sans, FreeSerif), /// optionally filtering by `style`. Both fields are case-insensitive. pub fn find(family: &str, style: Option<&str>) -> Option<Font> { let mut pat = Pattern::new(); pat.add_string("family", family); if let Some(style) = style { pat.add_string("style", style); } let font_match = pat.font_match(); font_match.name().and_then(|name| font_match.filename().map(|filename| Font { name: name.into_string(), path: Path::new(filename), } )) } #[allow(dead_code)] fn print_debug(&self) { debug!("Name: {}\nPath: {}", self.name, self.path.display()); } } /// A safe wrapper around fontconfig's `FcPattern`. pub struct Pattern<'a> { _m: marker::ContravariantLifetime<'a>, pat: *mut FcPattern, /// This is just to hold the RAII C-strings while the `FcPattern` is alive. strings: Vec<CString>, } impl<'a> Pattern<'a> { pub fn new() -> Pattern<'a> { fc_init(); Pattern { _m: marker::ContravariantLifetime, pat: unsafe{ fontconfig::FcPatternCreate() }, strings: Vec::new(), } } fn from_pattern(pat: *mut FcPattern) -> Pattern<'a> { unsafe { fontconfig::FcPatternReference(pat); } Pattern { _m: marker::ContravariantLifetime, pat: pat, strings: Vec::new(), } } /// Add a key-value pair to this pattern. /// /// See useful keys in the [fontconfig reference][1]. /// /// [1]: http://www.freedesktop.org/software/fontconfig/fontconfig-devel/x19.html pub fn add_string(&mut self, name: &str, val: &str) { let c_name = name.to_c_str(); // `val` is copied inside fontconfig so no need to allocate it again. val.with_c_str(|c_str| unsafe { fontconfig::FcPatternAddString(self.pat, c_name.as_ptr(), c_str as *const u8); }); self.strings.push(c_name); } /// Get the value for a key from this pattern. pub fn
<'a>(&'a self, name: &str) -> Option<&'a str> { name.with_c_str(|c_str| unsafe { let ret = mem::uninitialized(); if fontconfig::FcPatternGetString(&*self.pat, c_str, 0, ret) == 0 { Some(std::str::from_c_str(*ret as *const i8)) } else { None } }) } /// Print this pattern to stdout with all its values. #[allow(dead_code)] pub fn print(&self) { unsafe { fontconfig::FcPatternPrint(&*self.pat); } } fn default_substitute(&mut self) { unsafe { fontconfig::FcDefaultSubstitute(self.pat); } } fn config_substitute(&mut self) { unsafe { fontconfig::FcConfigSubstitute(ptr::null_mut(), self.pat, fontconfig::FcMatchPattern); } } /// Get the best available match for this pattern, returned as a new pattern. pub fn font_match<'a>(&'a mut self) -> Pattern<'a> { self.default_substitute(); self.config_substitute(); unsafe { let mut res = fontconfig::FcResultNoMatch; Pattern::from_pattern( fontconfig::FcFontMatch(ptr::null_mut(), self.pat, &mut res) ) } } /// Get the "fullname" (human-readable name) of this pattern. pub fn name(&self) -> Option<&str> { self.get_string("fullname") } /// Get the "file" (path on the filesystem) of this font pattern. pub fn filename(&self) -> Option<&str> { self.get_string("file") } } #[unsafe_destructor] impl<'a> Drop for Pattern<'a> { fn drop(&mut self) { unsafe { fontconfig::FcPatternDestroy(self.pat); } } } #[test] fn it_works() { fc_init(); } #[test] fn test_find_font() { Font::find("dejavu sans", None).unwrap().print_debug(); Font::find("dejavu sans", Some("oblique")).unwrap().print_debug(); }
get_string
identifier_name
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[u8]) -> Vec<u8> { let iv = Some(key); let ptxt = decrypt(symm::Cipher::aes_128_cbc(), key, iv, data).unwrap(); let invalid = ptxt.iter() .find(|&&b| b < 32 || b >= 127) .is_some(); if invalid
ptxt } // k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); let key: [u8; 16] = rng.gen(); let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64() .unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(); new_ctxt.extend_from_slice(&[0_u8; 16]); new_ctxt.extend_from_slice(&ctxt[0..16]); new_ctxt.extend_from_slice(&ctxt[48..]); let ptxt = decryption_oracle(&key, &new_ctxt); let key_recovered = xor_bytes(&ptxt[0..16], &ptxt[32..48]); assert_eq!(&key_recovered, &key); }
{ println!("Oh no there's an error!"); }
conditional_block
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[u8]) -> Vec<u8>
// k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); let key: [u8; 16] = rng.gen(); let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64() .unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(); new_ctxt.extend_from_slice(&[0_u8; 16]); new_ctxt.extend_from_slice(&ctxt[0..16]); new_ctxt.extend_from_slice(&ctxt[48..]); let ptxt = decryption_oracle(&key, &new_ctxt); let key_recovered = xor_bytes(&ptxt[0..16], &ptxt[32..48]); assert_eq!(&key_recovered, &key); }
{ let iv = Some(key); let ptxt = decrypt(symm::Cipher::aes_128_cbc(), key, iv, data).unwrap(); let invalid = ptxt.iter() .find(|&&b| b < 32 || b >= 127) .is_some(); if invalid { println!("Oh no there's an error!"); } ptxt }
identifier_body
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[u8]) -> Vec<u8> { let iv = Some(key); let ptxt = decrypt(symm::Cipher::aes_128_cbc(), key, iv, data).unwrap(); let invalid = ptxt.iter() .find(|&&b| b < 32 || b >= 127) .is_some(); if invalid { println!("Oh no there's an error!"); } ptxt } // k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn run() { let mut rng = weak_rng(); let key: [u8; 16] = rng.gen();
.unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(); new_ctxt.extend_from_slice(&[0_u8; 16]); new_ctxt.extend_from_slice(&ctxt[0..16]); new_ctxt.extend_from_slice(&ctxt[48..]); let ptxt = decryption_oracle(&key, &new_ctxt); let key_recovered = xor_bytes(&ptxt[0..16], &ptxt[32..48]); assert_eq!(&key_recovered, &key); }
let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64()
random_line_split
p27.rs
use rand::{Rng, weak_rng}; use serialize::base64::FromBase64; use ssl::symm::{self, encrypt, decrypt}; use util::xor_bytes; fn encryption_oracle(key: &[u8], input: &[u8]) -> Vec<u8> { let iv = Some(key); encrypt(symm::Cipher::aes_128_cbc(), key, iv, input).unwrap() } fn decryption_oracle(key: &[u8], data: &[u8]) -> Vec<u8> { let iv = Some(key); let ptxt = decrypt(symm::Cipher::aes_128_cbc(), key, iv, data).unwrap(); let invalid = ptxt.iter() .find(|&&b| b < 32 || b >= 127) .is_some(); if invalid { println!("Oh no there's an error!"); } ptxt } // k=IV recovery attack // --- // C_1' = C_1 // C_2' = 0 // C_3' = C_1 // P_1' = D_k(C_1') ^ k // = D_k(C_1) ^ k // P_3' = D_k(C_3') ^ C_2' // = D_k(C_1) ^ 0 // = D_k(C_1) // k = P_1' ^ P_3' // = D_k(C_1') ^ k ^ D_k(C_1) // = k #[test] fn
() { let mut rng = weak_rng(); let key: [u8; 16] = rng.gen(); let msg = "RE9TJ1QgVEhPVSBQUkFURSwgUk9HVUU/PyBET1MnVCBUSE9VIEpFRVIgQU5EIFQ\ tVEFVTlQgTUUgSU4gVEhFIFRFRVRIPz8K" .from_base64() .unwrap(); let ctxt = encryption_oracle(&key, &msg); let mut new_ctxt = ctxt[0..16].to_vec(); new_ctxt.extend_from_slice(&[0_u8; 16]); new_ctxt.extend_from_slice(&ctxt[0..16]); new_ctxt.extend_from_slice(&ctxt[48..]); let ptxt = decryption_oracle(&key, &new_ctxt); let key_recovered = xor_bytes(&ptxt[0..16], &ptxt[32..48]); assert_eq!(&key_recovered, &key); }
run
identifier_name
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &SimpleType) -> bool
pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.facets { let s = if let Facet::Enumeration(s) = facet { s } else { return Err(CreateError::new("expected enumeration")); }; members.push(Symbol::new(s.as_str())); } let default = members .first() .ok_or_else(|| make_create_err!("no members!"))? .clone(); let enm = Enumeration { name: Symbol::new(st.name.as_str()), members, documentation: st.documentation(), default, other_field: None, }; Ok(Some(vec![Def::Enumeration(enm)])) }
{ match &st.payload { Payload::Restriction(r) => { if r.facets.is_empty() { return false; } for facet in &r.facets { match facet { Facet::Enumeration(_) => continue, _ => return false, } } return true; } _ => false, } }
identifier_body
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &SimpleType) -> bool { match &st.payload { Payload::Restriction(r) => { if r.facets.is_empty() { return false; } for facet in &r.facets { match facet { Facet::Enumeration(_) => continue, _ => return false, } } return true; } _ => false, } } pub(super) fn
(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.facets { let s = if let Facet::Enumeration(s) = facet { s } else { return Err(CreateError::new("expected enumeration")); }; members.push(Symbol::new(s.as_str())); } let default = members .first() .ok_or_else(|| make_create_err!("no members!"))? .clone(); let enm = Enumeration { name: Symbol::new(st.name.as_str()), members, documentation: st.documentation(), default, other_field: None, }; Ok(Some(vec![Def::Enumeration(enm)])) }
model_enumeration
identifier_name
enumeration.rs
use crate::model::create::{CreateError, CreateResult}; use crate::model::enumeration::Enumeration; use crate::model::symbol::Symbol; use crate::model::Def; use crate::xsd::restriction::Facet; use crate::xsd::simple_type::{Payload, SimpleType}; use crate::xsd::{simple_type, Xsd}; pub(super) fn is_enumeration(st: &SimpleType) -> bool { match &st.payload { Payload::Restriction(r) => { if r.facets.is_empty() { return false; } for facet in &r.facets { match facet {
Facet::Enumeration(_) => continue, _ => return false, } } return true; } _ => false, } } pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult { let restriction = if let simple_type::Payload::Restriction(r) = &st.payload { r } else { return Err(CreateError::new("expected restriction")); }; let mut members = Vec::new(); for facet in &restriction.facets { let s = if let Facet::Enumeration(s) = facet { s } else { return Err(CreateError::new("expected enumeration")); }; members.push(Symbol::new(s.as_str())); } let default = members .first() .ok_or_else(|| make_create_err!("no members!"))? .clone(); let enm = Enumeration { name: Symbol::new(st.name.as_str()), members, documentation: st.documentation(), default, other_field: None, }; Ok(Some(vec![Def::Enumeration(enm)])) }
random_line_split
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::network::Network; pub use self::friend::{ Friend, FriendManage }; pub use self::chat::Chat; pub use self::custom::Packet; pub use self::events::{ Event, Listen }; pub use self::file::File; #[cfg(feature = "groupchat")] pub use self::group::Group; #[cfg(feature = "groupchat")] pub use self::peer::Peer; /// Tox. #[derive(Clone, Debug)] pub struct Tox { pub core: *mut ffi::Tox } impl Tox { /// from ToxOptions create Tox. pub fn new(opts: ToxOptions) -> Result<Tox, error::NewErr> { out!(err err, ffi::tox_new(&opts.opts, &mut err)) .map(Tox::from) } /// from raw ptr create Tox. pub fn from(core: *mut ffi::Tox) -> Tox { Tox { core: core } } /// Get Tox Profile data. pub fn save(&self) -> Vec<u8>
/// Get Address. pub fn address(&self) -> ::address::Address { out!( get out <- vec_with!(vars::TOX_ADDRESS_SIZE), ffi::tox_self_get_address(self.core, out.as_mut_ptr()) ).into() } /// Get SecretKey. pub fn secretkey(&self) -> Vec<u8> { out!( get out <- vec_with!(vars::TOX_SECRET_KEY_SIZE), ffi::tox_self_get_secret_key(self.core, out.as_mut_ptr()) ) } /// Get Nospam code. pub fn nospam(&self) -> u32 { unsafe { ffi::tox_self_get_nospam(self.core) } } /// Set Name. pub fn set_name<S: AsRef<[u8]>>(&self, name: S) -> Result<(), error::InfoSetErr> { let name = name.as_ref(); out!( bool err, ffi::tox_self_set_name( self.core, name.as_ptr(), name.len(), &mut err ) ) } /// Set Nospam code. pub fn set_nospam(&self, nospam: u32) { unsafe { ffi::tox_self_set_nospam(self.core, nospam) } } /// Set Status (NONE, AWAY, BUYS). pub fn set_status(&self, status: status::UserStatus) { unsafe { ffi::tox_self_set_status(self.core, status) } } /// Set Status Message. pub fn set_status_message<S: AsRef<[u8]>>(&self, message: S) -> Result<(), error::InfoSetErr> { let message = message.as_ref(); out!( bool err, ffi::tox_self_set_status_message( self.core, message.as_ptr(), message.len(), &mut err ) ) } } impl Drop for Tox { fn drop(&mut self) { unsafe { ffi::tox_kill(self.core); } } } pub fn version_major() -> usize { unsafe { ffi::tox_version_major() as usize } } pub fn version_minor() -> usize { unsafe { ffi::tox_version_minor() as usize } } pub fn version_patch() -> usize { unsafe { ffi::tox_version_patch() as usize } } pub fn version_is_compatible(major: usize, minor: usize, patch: usize) -> bool { unsafe { ffi::tox_version_is_compatible( major as ::libc::uint32_t, minor as ::libc::uint32_t, patch as ::libc::uint32_t ) } }
{ out!( get out <- vec_with!(ffi::tox_get_savedata_size(self.core)), ffi::tox_get_savedata(self.core, out.as_mut_ptr()) ) }
identifier_body
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::network::Network; pub use self::friend::{ Friend, FriendManage }; pub use self::chat::Chat; pub use self::custom::Packet; pub use self::events::{ Event, Listen }; pub use self::file::File; #[cfg(feature = "groupchat")] pub use self::group::Group; #[cfg(feature = "groupchat")] pub use self::peer::Peer; /// Tox. #[derive(Clone, Debug)] pub struct Tox { pub core: *mut ffi::Tox } impl Tox { /// from ToxOptions create Tox. pub fn new(opts: ToxOptions) -> Result<Tox, error::NewErr> { out!(err err, ffi::tox_new(&opts.opts, &mut err)) .map(Tox::from) } /// from raw ptr create Tox. pub fn from(core: *mut ffi::Tox) -> Tox { Tox { core: core } } /// Get Tox Profile data. pub fn save(&self) -> Vec<u8> { out!( get out <- vec_with!(ffi::tox_get_savedata_size(self.core)), ffi::tox_get_savedata(self.core, out.as_mut_ptr()) ) } /// Get Address. pub fn address(&self) -> ::address::Address { out!( get out <- vec_with!(vars::TOX_ADDRESS_SIZE), ffi::tox_self_get_address(self.core, out.as_mut_ptr()) ).into() } /// Get SecretKey. pub fn secretkey(&self) -> Vec<u8> { out!( get out <- vec_with!(vars::TOX_SECRET_KEY_SIZE), ffi::tox_self_get_secret_key(self.core, out.as_mut_ptr()) ) } /// Get Nospam code. pub fn nospam(&self) -> u32 { unsafe { ffi::tox_self_get_nospam(self.core) } } /// Set Name. pub fn set_name<S: AsRef<[u8]>>(&self, name: S) -> Result<(), error::InfoSetErr> { let name = name.as_ref(); out!( bool err, ffi::tox_self_set_name( self.core, name.as_ptr(), name.len(), &mut err ) ) } /// Set Nospam code. pub fn set_nospam(&self, nospam: u32) { unsafe { ffi::tox_self_set_nospam(self.core, nospam) } } /// Set Status (NONE, AWAY, BUYS). pub fn set_status(&self, status: status::UserStatus) { unsafe { ffi::tox_self_set_status(self.core, status) } } /// Set Status Message. pub fn
<S: AsRef<[u8]>>(&self, message: S) -> Result<(), error::InfoSetErr> { let message = message.as_ref(); out!( bool err, ffi::tox_self_set_status_message( self.core, message.as_ptr(), message.len(), &mut err ) ) } } impl Drop for Tox { fn drop(&mut self) { unsafe { ffi::tox_kill(self.core); } } } pub fn version_major() -> usize { unsafe { ffi::tox_version_major() as usize } } pub fn version_minor() -> usize { unsafe { ffi::tox_version_minor() as usize } } pub fn version_patch() -> usize { unsafe { ffi::tox_version_patch() as usize } } pub fn version_is_compatible(major: usize, minor: usize, patch: usize) -> bool { unsafe { ffi::tox_version_is_compatible( major as ::libc::uint32_t, minor as ::libc::uint32_t, patch as ::libc::uint32_t ) } }
set_status_message
identifier_name
mod.rs
mod ffi; pub mod error; pub mod vars; pub mod options; pub mod status; pub mod chat; pub mod file; mod friend; mod network; mod custom; mod events; #[cfg(feature = "groupchat")] pub mod group; #[cfg(feature = "groupchat")] mod peer; pub use self::options::ToxOptions; pub use self::status::Status; pub use self::network::Network; pub use self::friend::{ Friend, FriendManage }; pub use self::chat::Chat; pub use self::custom::Packet; pub use self::events::{ Event, Listen }; pub use self::file::File; #[cfg(feature = "groupchat")] pub use self::group::Group;
pub use self::peer::Peer; /// Tox. #[derive(Clone, Debug)] pub struct Tox { pub core: *mut ffi::Tox } impl Tox { /// from ToxOptions create Tox. pub fn new(opts: ToxOptions) -> Result<Tox, error::NewErr> { out!(err err, ffi::tox_new(&opts.opts, &mut err)) .map(Tox::from) } /// from raw ptr create Tox. pub fn from(core: *mut ffi::Tox) -> Tox { Tox { core: core } } /// Get Tox Profile data. pub fn save(&self) -> Vec<u8> { out!( get out <- vec_with!(ffi::tox_get_savedata_size(self.core)), ffi::tox_get_savedata(self.core, out.as_mut_ptr()) ) } /// Get Address. pub fn address(&self) -> ::address::Address { out!( get out <- vec_with!(vars::TOX_ADDRESS_SIZE), ffi::tox_self_get_address(self.core, out.as_mut_ptr()) ).into() } /// Get SecretKey. pub fn secretkey(&self) -> Vec<u8> { out!( get out <- vec_with!(vars::TOX_SECRET_KEY_SIZE), ffi::tox_self_get_secret_key(self.core, out.as_mut_ptr()) ) } /// Get Nospam code. pub fn nospam(&self) -> u32 { unsafe { ffi::tox_self_get_nospam(self.core) } } /// Set Name. pub fn set_name<S: AsRef<[u8]>>(&self, name: S) -> Result<(), error::InfoSetErr> { let name = name.as_ref(); out!( bool err, ffi::tox_self_set_name( self.core, name.as_ptr(), name.len(), &mut err ) ) } /// Set Nospam code. pub fn set_nospam(&self, nospam: u32) { unsafe { ffi::tox_self_set_nospam(self.core, nospam) } } /// Set Status (NONE, AWAY, BUYS). pub fn set_status(&self, status: status::UserStatus) { unsafe { ffi::tox_self_set_status(self.core, status) } } /// Set Status Message. pub fn set_status_message<S: AsRef<[u8]>>(&self, message: S) -> Result<(), error::InfoSetErr> { let message = message.as_ref(); out!( bool err, ffi::tox_self_set_status_message( self.core, message.as_ptr(), message.len(), &mut err ) ) } } impl Drop for Tox { fn drop(&mut self) { unsafe { ffi::tox_kill(self.core); } } } pub fn version_major() -> usize { unsafe { ffi::tox_version_major() as usize } } pub fn version_minor() -> usize { unsafe { ffi::tox_version_minor() as usize } } pub fn version_patch() -> usize { unsafe { ffi::tox_version_patch() as usize } } pub fn version_is_compatible(major: usize, minor: usize, patch: usize) -> bool { unsafe { ffi::tox_version_is_compatible( major as ::libc::uint32_t, minor as ::libc::uint32_t, patch as ::libc::uint32_t ) } }
#[cfg(feature = "groupchat")]
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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. Blockstack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>. */ pub mod burndb; use std::fmt; use std::error; use rusqlite::Error as sqlite_error; use rusqlite::Row; use rusqlite::Connection; pub type DBConn = Connection; use serde_json::Error as serde_error; use burnchains::{Txid, BurnchainHeaderHash, Address}; use util::vrf::*; use util::hash::{hex_bytes, Hash160, Sha512Trunc256Sum}; use chainstate::burn::{ConsensusHash, VRFSeed, BlockHeaderHash, OpsHash, SortitionHash}; use util::db; use util::db::FromColumn; use util::db::Error as db_error; use chainstate::stacks::index::TrieHash; use chainstate::stacks::StacksPublicKey; use util::secp256k1::MessageSignature; impl_byte_array_from_column!(Txid); impl_byte_array_from_column!(ConsensusHash); impl_byte_array_from_column!(Hash160); impl_byte_array_from_column!(BlockHeaderHash); impl_byte_array_from_column!(VRFSeed); impl_byte_array_from_column!(OpsHash); impl_byte_array_from_column!(BurnchainHeaderHash); impl_byte_array_from_column!(SortitionHash); impl_byte_array_from_column!(Sha512Trunc256Sum); impl_byte_array_from_column!(VRFProof); impl_byte_array_from_column!(TrieHash); impl_byte_array_from_column!(MessageSignature); impl FromColumn<VRFPublicKey> for VRFPublicKey { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<VRFPublicKey, db_error>
} impl<A: Address> FromColumn<A> for A { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
{ let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) } }
identifier_body
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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. Blockstack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>. */ pub mod burndb; use std::fmt; use std::error; use rusqlite::Error as sqlite_error; use rusqlite::Row; use rusqlite::Connection; pub type DBConn = Connection; use serde_json::Error as serde_error; use burnchains::{Txid, BurnchainHeaderHash, Address}; use util::vrf::*; use util::hash::{hex_bytes, Hash160, Sha512Trunc256Sum}; use chainstate::burn::{ConsensusHash, VRFSeed, BlockHeaderHash, OpsHash, SortitionHash}; use util::db; use util::db::FromColumn; use util::db::Error as db_error; use chainstate::stacks::index::TrieHash; use chainstate::stacks::StacksPublicKey; use util::secp256k1::MessageSignature; impl_byte_array_from_column!(Txid); impl_byte_array_from_column!(ConsensusHash); impl_byte_array_from_column!(Hash160); impl_byte_array_from_column!(BlockHeaderHash); impl_byte_array_from_column!(VRFSeed); impl_byte_array_from_column!(OpsHash); impl_byte_array_from_column!(BurnchainHeaderHash); impl_byte_array_from_column!(SortitionHash); impl_byte_array_from_column!(Sha512Trunc256Sum); impl_byte_array_from_column!(VRFProof); impl_byte_array_from_column!(TrieHash); impl_byte_array_from_column!(MessageSignature); impl FromColumn<VRFPublicKey> for VRFPublicKey { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<VRFPublicKey, db_error> {
} } impl<A: Address> FromColumn<A> for A { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) }
random_line_split
mod.rs
/* copyright: (c) 2013-2018 by Blockstack PBC, a public benefit corporation. This file is part of Blockstack. Blockstack is free software. You may redistribute 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. Blockstack is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without 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 Blockstack. If not, see <http://www.gnu.org/licenses/>. */ pub mod burndb; use std::fmt; use std::error; use rusqlite::Error as sqlite_error; use rusqlite::Row; use rusqlite::Connection; pub type DBConn = Connection; use serde_json::Error as serde_error; use burnchains::{Txid, BurnchainHeaderHash, Address}; use util::vrf::*; use util::hash::{hex_bytes, Hash160, Sha512Trunc256Sum}; use chainstate::burn::{ConsensusHash, VRFSeed, BlockHeaderHash, OpsHash, SortitionHash}; use util::db; use util::db::FromColumn; use util::db::Error as db_error; use chainstate::stacks::index::TrieHash; use chainstate::stacks::StacksPublicKey; use util::secp256k1::MessageSignature; impl_byte_array_from_column!(Txid); impl_byte_array_from_column!(ConsensusHash); impl_byte_array_from_column!(Hash160); impl_byte_array_from_column!(BlockHeaderHash); impl_byte_array_from_column!(VRFSeed); impl_byte_array_from_column!(OpsHash); impl_byte_array_from_column!(BurnchainHeaderHash); impl_byte_array_from_column!(SortitionHash); impl_byte_array_from_column!(Sha512Trunc256Sum); impl_byte_array_from_column!(VRFProof); impl_byte_array_from_column!(TrieHash); impl_byte_array_from_column!(MessageSignature); impl FromColumn<VRFPublicKey> for VRFPublicKey { fn from_column<'a>(row: &'a Row, column_name: &str) -> Result<VRFPublicKey, db_error> { let pubkey_hex : String = row.get(column_name); match VRFPublicKey::from_hex(&pubkey_hex) { Some(pubk) => Ok(pubk), None => Err(db_error::ParseError) } } } impl<A: Address> FromColumn<A> for A { fn
<'a>(row: &'a Row, column_name: &str) -> Result<A, db_error> { let address_str : String = row.get(column_name); match A::from_string(&address_str) { Some(a) => Ok(a), None => Err(db_error::ParseError) } } }
from_column
identifier_name
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] pub struct ConvexPolygon<N: RealField> { points: Vec<Point<N>>, normals: Vec<Unit<Vector<N>>>, } impl<N: RealField> ConvexPolygon<N> { /// Creates a new 2D convex polygon from an arbitrary set of points. /// /// This explicitly computes the convex hull of the given set of points. Use /// Returns `None` if the convex hull computation failed. pub fn try_from_points(points: &[Point<N>]) -> Option<Self> { let hull = transformation::convex_hull(points); let mut vertices = hull.unwrap().0; vertices.reverse(); // FIXME: it is unfortunate to have to do this reverse. Self::try_new(vertices) } /// Creates a new 2D convex polygon from a set of points assumed to describe a counter-clockwise convex polyline. /// /// Convexity of the input polyline is not checked. /// Returns `None` if some consecutive points are identical (or too close to being so). pub fn try_new(mut points: Vec<Point<N>>) -> Option<Self>
if normals[i1].dot(&*normals[i2]) > N::one() - eps { // Remove nremoved += 1; } else { points[i2 - nremoved] = points[i2]; normals[i2 - nremoved] = normals[i2]; } } let new_length = points.len() - nremoved; points.truncate(new_length); normals.truncate(new_length); if points.len()!= 0 { Some(ConvexPolygon { points, normals }) } else { None } } /// The vertices of this convex polygon. #[inline] pub fn points(&self) -> &[Point<N>] { &self.points } /// The normals of the edges of this convex polygon. #[inline] pub fn normals(&self) -> &[Unit<Vector<N>>] { &self.normals } /// Checks that the given direction in world-space is on the tangent cone of the given `feature`. pub fn tangent_cone_contains_dir( &self, feature: FeatureId, m: &Isometry<N>, dir: &Unit<Vector<N>>, ) -> bool { let local_dir = m.inverse_transform_unit_vector(dir); match feature { FeatureId::Face(id) => self.normals[id].dot(&local_dir) <= N::zero(), FeatureId::Vertex(id2) => { let id1 = if id2 == 0 { self.normals.len() - 1 } else { id2 - 1 }; self.normals[id1].dot(&local_dir) <= N::zero() && self.normals[id2].dot(&local_dir) <= N::zero() } _ => unreachable!(), } } } impl<N: RealField> SupportMap<N> for ConvexPolygon<N> { #[inline] fn local_support_point(&self, dir: &Vector<N>) -> Point<N> { utils::point_cloud_support_point(dir, self.points()) } } impl<N: RealField> ConvexPolyhedron<N> for ConvexPolygon<N> { fn vertex(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % self.points.len(); out.push(self.points[ia], FeatureId::Vertex(ia)); out.push(self.points[ib], FeatureId::Vertex(ib)); out.set_normal(self.normals[ia]); out.set_feature_id(FeatureId::Face(ia)); } fn feature_normal(&self, feature: FeatureId) -> Unit<Vector<N>> { match feature { FeatureId::Face(id) => self.normals[id], FeatureId::Vertex(id2) => { let id1 = if id2 == 0 { self.normals.len() - 1 } else { id2 - 1 }; Unit::new_normalize(*self.normals[id1] + *self.normals[id2]) } _ => panic!("Invalid feature ID: {:?}", feature), } } fn support_face_toward( &self, m: &Isometry<N>, dir: &Unit<Vector<N>>, out: &mut ConvexPolygonalFeature<N>, ) { let ls_dir = m.inverse_transform_vector(dir); let mut best_face = 0; let mut max_dot = self.normals[0].dot(&ls_dir); for i in 1..self.points.len() { let dot = self.normals[i].dot(&ls_dir); if dot > max_dot { max_dot = dot; best_face = i; } } self.face(FeatureId::Face(best_face), out); out.transform_by(m); } fn support_feature_toward( &self, transform: &Isometry<N>, dir: &Unit<Vector<N>>, _angle: N, out: &mut ConvexPolygonalFeature<N>, ) { out.clear(); // FIXME: actualy find the support feature. self.support_face_toward(transform, dir, out) } fn support_feature_id_toward(&self, local_dir: &Unit<Vector<N>>) -> FeatureId { let eps: N = na::convert(f64::consts::PI / 180.0); let ceps = eps.cos(); // Check faces. for i in 0..self.normals.len() { let normal = &self.normals[i]; if normal.dot(local_dir.as_ref()) >= ceps { return FeatureId::Face(i); } } // Support vertex. FeatureId::Vertex(utils::point_cloud_support_point_id( local_dir.as_ref(), &self.points, )) } }
{ let eps = N::default_epsilon().sqrt(); let mut normals = Vec::with_capacity(points.len()); // First, compute all normals. for i1 in 0..points.len() { let i2 = (i1 + 1) % points.len(); normals.push(utils::ccw_face_normal([&points[i1], &points[i2]])?); } let mut nremoved = 0; // See if the first vexrtex must be removed. if normals[0].dot(&*normals[normals.len() - 1]) > N::one() - eps { nremoved = 1; } // Second, find vertices that can be removed because // of collinearity of adjascent faces. for i2 in 1..points.len() { let i1 = i2 - 1;
identifier_body
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] pub struct ConvexPolygon<N: RealField> { points: Vec<Point<N>>, normals: Vec<Unit<Vector<N>>>, } impl<N: RealField> ConvexPolygon<N> { /// Creates a new 2D convex polygon from an arbitrary set of points. /// /// This explicitly computes the convex hull of the given set of points. Use /// Returns `None` if the convex hull computation failed. pub fn try_from_points(points: &[Point<N>]) -> Option<Self> { let hull = transformation::convex_hull(points); let mut vertices = hull.unwrap().0; vertices.reverse(); // FIXME: it is unfortunate to have to do this reverse. Self::try_new(vertices) } /// Creates a new 2D convex polygon from a set of points assumed to describe a counter-clockwise convex polyline. /// /// Convexity of the input polyline is not checked. /// Returns `None` if some consecutive points are identical (or too close to being so). pub fn try_new(mut points: Vec<Point<N>>) -> Option<Self> { let eps = N::default_epsilon().sqrt(); let mut normals = Vec::with_capacity(points.len()); // First, compute all normals. for i1 in 0..points.len() { let i2 = (i1 + 1) % points.len(); normals.push(utils::ccw_face_normal([&points[i1], &points[i2]])?); } let mut nremoved = 0; // See if the first vexrtex must be removed. if normals[0].dot(&*normals[normals.len() - 1]) > N::one() - eps { nremoved = 1; } // Second, find vertices that can be removed because // of collinearity of adjascent faces. for i2 in 1..points.len() { let i1 = i2 - 1; if normals[i1].dot(&*normals[i2]) > N::one() - eps { // Remove nremoved += 1; } else { points[i2 - nremoved] = points[i2]; normals[i2 - nremoved] = normals[i2]; } } let new_length = points.len() - nremoved; points.truncate(new_length); normals.truncate(new_length); if points.len()!= 0 { Some(ConvexPolygon { points, normals }) } else { None } } /// The vertices of this convex polygon. #[inline] pub fn points(&self) -> &[Point<N>] { &self.points } /// The normals of the edges of this convex polygon. #[inline] pub fn normals(&self) -> &[Unit<Vector<N>>] { &self.normals } /// Checks that the given direction in world-space is on the tangent cone of the given `feature`. pub fn tangent_cone_contains_dir( &self, feature: FeatureId, m: &Isometry<N>, dir: &Unit<Vector<N>>, ) -> bool { let local_dir = m.inverse_transform_unit_vector(dir); match feature { FeatureId::Face(id) => self.normals[id].dot(&local_dir) <= N::zero(), FeatureId::Vertex(id2) => { let id1 = if id2 == 0 { self.normals.len() - 1 } else { id2 - 1 }; self.normals[id1].dot(&local_dir) <= N::zero() && self.normals[id2].dot(&local_dir) <= N::zero() } _ => unreachable!(), } } } impl<N: RealField> SupportMap<N> for ConvexPolygon<N> { #[inline] fn local_support_point(&self, dir: &Vector<N>) -> Point<N> { utils::point_cloud_support_point(dir, self.points())
} impl<N: RealField> ConvexPolyhedron<N> for ConvexPolygon<N> { fn vertex(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % self.points.len(); out.push(self.points[ia], FeatureId::Vertex(ia)); out.push(self.points[ib], FeatureId::Vertex(ib)); out.set_normal(self.normals[ia]); out.set_feature_id(FeatureId::Face(ia)); } fn feature_normal(&self, feature: FeatureId) -> Unit<Vector<N>> { match feature { FeatureId::Face(id) => self.normals[id], FeatureId::Vertex(id2) => { let id1 = if id2 == 0 { self.normals.len() - 1 } else { id2 - 1 }; Unit::new_normalize(*self.normals[id1] + *self.normals[id2]) } _ => panic!("Invalid feature ID: {:?}", feature), } } fn support_face_toward( &self, m: &Isometry<N>, dir: &Unit<Vector<N>>, out: &mut ConvexPolygonalFeature<N>, ) { let ls_dir = m.inverse_transform_vector(dir); let mut best_face = 0; let mut max_dot = self.normals[0].dot(&ls_dir); for i in 1..self.points.len() { let dot = self.normals[i].dot(&ls_dir); if dot > max_dot { max_dot = dot; best_face = i; } } self.face(FeatureId::Face(best_face), out); out.transform_by(m); } fn support_feature_toward( &self, transform: &Isometry<N>, dir: &Unit<Vector<N>>, _angle: N, out: &mut ConvexPolygonalFeature<N>, ) { out.clear(); // FIXME: actualy find the support feature. self.support_face_toward(transform, dir, out) } fn support_feature_id_toward(&self, local_dir: &Unit<Vector<N>>) -> FeatureId { let eps: N = na::convert(f64::consts::PI / 180.0); let ceps = eps.cos(); // Check faces. for i in 0..self.normals.len() { let normal = &self.normals[i]; if normal.dot(local_dir.as_ref()) >= ceps { return FeatureId::Face(i); } } // Support vertex. FeatureId::Vertex(utils::point_cloud_support_point_id( local_dir.as_ref(), &self.points, )) } }
}
random_line_split
convex_polygon.rs
use crate::math::{Isometry, Point, Vector}; use crate::shape::{ConvexPolygonalFeature, ConvexPolyhedron, FeatureId, SupportMap}; use crate::transformation; use crate::utils; use na::{self, RealField, Unit}; use std::f64; /// A 2D convex polygon. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, Debug)] pub struct ConvexPolygon<N: RealField> { points: Vec<Point<N>>, normals: Vec<Unit<Vector<N>>>, } impl<N: RealField> ConvexPolygon<N> { /// Creates a new 2D convex polygon from an arbitrary set of points. /// /// This explicitly computes the convex hull of the given set of points. Use /// Returns `None` if the convex hull computation failed. pub fn try_from_points(points: &[Point<N>]) -> Option<Self> { let hull = transformation::convex_hull(points); let mut vertices = hull.unwrap().0; vertices.reverse(); // FIXME: it is unfortunate to have to do this reverse. Self::try_new(vertices) } /// Creates a new 2D convex polygon from a set of points assumed to describe a counter-clockwise convex polyline. /// /// Convexity of the input polyline is not checked. /// Returns `None` if some consecutive points are identical (or too close to being so). pub fn try_new(mut points: Vec<Point<N>>) -> Option<Self> { let eps = N::default_epsilon().sqrt(); let mut normals = Vec::with_capacity(points.len()); // First, compute all normals. for i1 in 0..points.len() { let i2 = (i1 + 1) % points.len(); normals.push(utils::ccw_face_normal([&points[i1], &points[i2]])?); } let mut nremoved = 0; // See if the first vexrtex must be removed. if normals[0].dot(&*normals[normals.len() - 1]) > N::one() - eps { nremoved = 1; } // Second, find vertices that can be removed because // of collinearity of adjascent faces. for i2 in 1..points.len() { let i1 = i2 - 1; if normals[i1].dot(&*normals[i2]) > N::one() - eps { // Remove nremoved += 1; } else { points[i2 - nremoved] = points[i2]; normals[i2 - nremoved] = normals[i2]; } } let new_length = points.len() - nremoved; points.truncate(new_length); normals.truncate(new_length); if points.len()!= 0 { Some(ConvexPolygon { points, normals }) } else { None } } /// The vertices of this convex polygon. #[inline] pub fn points(&self) -> &[Point<N>] { &self.points } /// The normals of the edges of this convex polygon. #[inline] pub fn normals(&self) -> &[Unit<Vector<N>>] { &self.normals } /// Checks that the given direction in world-space is on the tangent cone of the given `feature`. pub fn tangent_cone_contains_dir( &self, feature: FeatureId, m: &Isometry<N>, dir: &Unit<Vector<N>>, ) -> bool { let local_dir = m.inverse_transform_unit_vector(dir); match feature { FeatureId::Face(id) => self.normals[id].dot(&local_dir) <= N::zero(), FeatureId::Vertex(id2) => { let id1 = if id2 == 0 { self.normals.len() - 1 } else { id2 - 1 }; self.normals[id1].dot(&local_dir) <= N::zero() && self.normals[id2].dot(&local_dir) <= N::zero() } _ => unreachable!(), } } } impl<N: RealField> SupportMap<N> for ConvexPolygon<N> { #[inline] fn local_support_point(&self, dir: &Vector<N>) -> Point<N> { utils::point_cloud_support_point(dir, self.points()) } } impl<N: RealField> ConvexPolyhedron<N> for ConvexPolygon<N> { fn
(&self, id: FeatureId) -> Point<N> { self.points[id.unwrap_vertex()] } fn face(&self, id: FeatureId, out: &mut ConvexPolygonalFeature<N>) { out.clear(); let ia = id.unwrap_face(); let ib = (ia + 1) % self.points.len(); out.push(self.points[ia], FeatureId::Vertex(ia)); out.push(self.points[ib], FeatureId::Vertex(ib)); out.set_normal(self.normals[ia]); out.set_feature_id(FeatureId::Face(ia)); } fn feature_normal(&self, feature: FeatureId) -> Unit<Vector<N>> { match feature { FeatureId::Face(id) => self.normals[id], FeatureId::Vertex(id2) => { let id1 = if id2 == 0 { self.normals.len() - 1 } else { id2 - 1 }; Unit::new_normalize(*self.normals[id1] + *self.normals[id2]) } _ => panic!("Invalid feature ID: {:?}", feature), } } fn support_face_toward( &self, m: &Isometry<N>, dir: &Unit<Vector<N>>, out: &mut ConvexPolygonalFeature<N>, ) { let ls_dir = m.inverse_transform_vector(dir); let mut best_face = 0; let mut max_dot = self.normals[0].dot(&ls_dir); for i in 1..self.points.len() { let dot = self.normals[i].dot(&ls_dir); if dot > max_dot { max_dot = dot; best_face = i; } } self.face(FeatureId::Face(best_face), out); out.transform_by(m); } fn support_feature_toward( &self, transform: &Isometry<N>, dir: &Unit<Vector<N>>, _angle: N, out: &mut ConvexPolygonalFeature<N>, ) { out.clear(); // FIXME: actualy find the support feature. self.support_face_toward(transform, dir, out) } fn support_feature_id_toward(&self, local_dir: &Unit<Vector<N>>) -> FeatureId { let eps: N = na::convert(f64::consts::PI / 180.0); let ceps = eps.cos(); // Check faces. for i in 0..self.normals.len() { let normal = &self.normals[i]; if normal.dot(local_dir.as_ref()) >= ceps { return FeatureId::Face(i); } } // Support vertex. FeatureId::Vertex(utils::point_cloud_support_point_id( local_dir.as_ref(), &self.points, )) } }
vertex
identifier_name
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependencies] * ladspa = "*" * * [lib] * name = "my_ladspa_plugin" * crate-type = ["dylib"] * ``` * This will pull in the correct dependency and ensure that the library generated when you build * your plugin is compatible with LADSPA hosts. * * ## Writing the code * You'll want to implement * ```get_ladspa_descriptor``` in your src/lib.rs. This function is expected to return 1 or more * ```PluginDescriptor```s describing the plugins exposed by your library. See the documentation * for ```get_ladspa_descriptor``` and the examples * [on Github](https://github.com/nwoeanhinnogaehr/ladspa.rs/tree/master/examples) for more * information. * * ## Testing it out * There is a list of host software supporting LADSPA on the * [LADSPA home page](http://www.ladspa.org/). In order for a host to find your plugin, you will * either need to copy the *.so file from target/ after building to /usr/lib/ladspa/ (on most * systems, it may be different on your system) or set the enviornment variable ```LADSPA_PATH``` * to equal the directory where you store your plugins. */ extern crate libc; #[macro_use] extern crate bitflags; extern crate vec_map; #[doc(hidden)] pub mod ffi; use ffi::ladspa_h; #[doc(hidden)] pub use ffi::ladspa_descriptor; use std::cell::{RefCell, RefMut}; use std::default::Default; #[allow(improper_ctypes)] extern { /** * Your plugin must implement this function. * ```get_ladspa_descriptor``` returns a description of a supported plugin for a given plugin * index. When the index is out of bounds for the number of plugins supported by your library, * you are expected to return ```None```. * * Example no-op implementation: * * ```rust{.ignore} * #[no_mangle] * pub extern fn get_ladspa_descriptor(index: u64) -> Option<ladspa::PluginDescriptor> { * None * } * ``` */ pub fn get_ladspa_descriptor(index: u64) -> Option<PluginDescriptor>; } /// The data type used internally by LADSPA for audio and control ports. pub type Data = f32; /// Describes the properties of a ```Plugin``` to be exposed as a LADSPA plugin. pub struct PluginDescriptor { /// Unique IDs are an unfortunate remnant of the LADSPA API. During development, it is /// suggested to pick one under 1000, but it should be changed before release. More information /// is available here: http://www.ladspa.org/ladspa_sdk/unique_ids.html pub unique_id: u64, /// Plugin labels are expected to be a unique descriptor string for this specific plugin within /// the library. Labels are case sensitive and expected not to contain spaces. pub label: &'static str, /// The properties of a plugin describe restrictions and features for it's use. See /// documentation for ```Properties``` for info on available options. pub properties: Properties, /// The name of the plugin. This is usually how it is identified. pub name: &'static str, /// The maker of the plugin. Can be empty. pub maker: &'static str, /// Indicates copyright of the plugin. If no copyright applies, "None" should be used. pub copyright: &'static str, /// A vector of input and output ports exposed by the plugin. See the documentation for /// ```Port``` for more information. pub ports: Vec<Port>, /// A function which creates a new instance of the plugin. /// /// Note: Initialization, such as resetting plugin state, should go in ```Plugin::activate``` rather /// than here. This should just return a basic instance, ready to be activated. /// If your plugin has no internal state, you may optionally not implement ```Plugin::activate``` /// and do everything here. pub new: fn(desc: &PluginDescriptor, sample_rate: u64) -> Box<Plugin + Send>, } #[derive(Copy, Clone, Default)] /// Represents an input or output to the plugin representing either audio or /// control data. pub struct Port { /// The name of the port. For control ports, this will likely be shown by the host in an /// automatically generated GUI next to the control. For audio ports, it is mostly just /// for identification in your code but some hosts may display it. pub name: &'static str, /// Describes the type of port: audio or control, input or output. pub desc: PortDescriptor, /// Most useful on control inputs but can be used on any type of port. pub hint: Option<ControlHint>, /// Most useful on control inputs but can be used on any type of port. pub default: Option<DefaultValue>, /// The lower bound of values to accepted by default (the host may ignore this). pub lower_bound: Option<Data>, /// The upper bound of values to accepted by default (the host may ignore this). pub upper_bound: Option<Data>, } #[derive(Copy, Clone)] /// Represents the 4 types of ports: audio or control, input or output. pub enum PortDescriptor { Invalid = 0, AudioInput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_INPUT) as isize, AudioOutput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_OUTPUT) as isize, ControlInput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_INPUT) as isize, ControlOutput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_OUTPUT) as isize, } impl Default for PortDescriptor { fn default() -> PortDescriptor { PortDescriptor::Invalid } } bitflags!( #[doc="Represents the special properties a control port may hold. These are merely hints as to the use of the port and may be completely ignored by the host. For audio ports, use ```CONTROL_HINT_NONE```. To attach multiple properties, bitwise-or them together. See documentation for the constants beginning with HINT_ for the more information."] pub flags ControlHint: i32 { #[doc="Indicates that this is a toggled port. Toggled ports may only have default values of zero or one, although the host may send any value, where <= 0 is false and > 0 is true."] const HINT_TOGGLED = ::ffi::ladspa_h::HINT_TOGGLED, #[doc="Indicates that all values related to the port will be multiplied by the sample rate by the host before passing them to your plugin. This includes the lower and upper bounds. If you want an upper bound of 22050 with this property and a sample rate of 44100, set the upper bound to 0.5"] const HINT_SAMPLE_RATE = ::ffi::ladspa_h::HINT_SAMPLE_RATE, #[doc="Indicates that the data passed through this port would be better represented on a logarithmic scale"] const HINT_LOGARITHMIC = ::ffi::ladspa_h::HINT_LOGARITHMIC, #[doc="Indicates that the data passed through this port should be represented as integers. Bounds may be interpreted exclusively depending on the host"] const HINT_INTEGER = ::ffi::ladspa_h::HINT_INTEGER, } ); #[derive(Copy, Clone)] /// The default values that a control port may hold. For audio ports, use DefaultControlValue::None. pub enum DefaultValue { /// Equal to the ```lower_bound``` of the ```Port```. Minimum = ladspa_h::HINT_DEFAULT_MINIMUM as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.75 + /// log(upper_bound) * 0.25)```. Otherwise, this should be ```(lower_bound * 0.75 + /// upper_bound * 0.25)```. Low = ladspa_h::HINT_DEFAULT_LOW as isize, /// For ports with /// ```CONTROL_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.5 + /// log(upper_bound) * 0.5)```. Otherwise, this should be ```(lower_bound * 0.5 + /// upper_bound * 0.5)```. Middle = ladspa_h::HINT_DEFAULT_MIDDLE as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.25 + /// log(upper_bound) * 0.75)```. Otherwise, this should be ```(lower_bound * 0.25 + /// upper_bound * 0.75)```. High = ladspa_h::HINT_DEFAULT_HIGH as isize, /// Equal to the ```upper_bound``` of the ```Port```. Maximum = ladspa_h::HINT_DEFAULT_MAXIMUM as isize, /// Equal to 0 or false for toggled values. Value0 = ladspa_h::HINT_DEFAULT_0 as isize, /// Equal to 1 or true for toggled values. Value1 = ladspa_h::HINT_DEFAULT_1 as isize, /// Equal to 100. Value100 = ladspa_h::HINT_DEFAULT_100 as isize, /// Equal to 440, concert A. This may be off by a few Hz if the host is using an alternate /// tuning. Value440 = ladspa_h::HINT_DEFAULT_440 as isize, } /// Represents a connection between a port and the data attached to the port by the plugin /// host. pub struct PortConnection<'a> { /// The port which the data is connected to. pub port: Port, /// The data connected to the port. It's usually simpler to use the various unwrap_* functions /// than to interface with this directly. pub data: PortData<'a>, } /// Represents the four types of data a port can hold. pub enum
<'a> { AudioInput(&'a [Data]), AudioOutput(RefCell<&'a mut [Data]>), ControlInput(&'a Data), ControlOutput(RefCell<&'a mut Data>), } unsafe impl<'a> Sync for PortData<'a> { } impl<'a> PortConnection<'a> { /// Returns a slice pointing to the internal data of an audio input port. Panics if this port /// is not an ```AudioIn``` port. pub fn unwrap_audio(&'a self) -> &'a [Data] { if let PortData::AudioInput(ref data) = self.data { data } else { panic!("PortConnection::unwrap_audio called on a non audio input port!") } } /// Returns a mutable slice pointing to the internal data of an audio output port. Panics if /// this port is not an ```AudioOut``` port. pub fn unwrap_audio_mut(&'a self) -> RefMut<'a, &'a mut [Data]> { if let PortData::AudioOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_audio_mut called on a non audio output port!") } } /// Returns a refrence to the internal data of an control input port. Panics if this port /// is not an ```ControlIn``` port. pub fn unwrap_control(&'a self) -> &'a Data { if let PortData::ControlInput(data) = self.data { data } else { panic!("PortConnection::unwrap_control called on a non control input port!") } } /// Returns a mutable refrence to the internal data of an audio output port. Panics if /// this port is not an ```ControlOut``` port. pub fn unwrap_control_mut(&'a self) -> RefMut<'a, &'a mut Data> { if let PortData::ControlOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_control called on a non control output port!") } } } bitflags!( #[doc="Represents the special properties a LADSPA plugin can have. To attach multiple properties, bitwise-or them together, for example ```PROP_REALTIME | PROP_INPLACE_BROKEN```. See documentation for the constants beginning with PROP_ for the more information."] pub flags Properties: i32 { #[doc="No properties."] const PROP_NONE = 0, #[doc="Indicates that the plugin has a realtime dependency so it's output may not be cached."] const PROP_REALTIME = ::ffi::ladspa_h::PROPERTY_REALTIME, #[doc="Indicates that the plugin will not function correctly if the input and output audio data has the same memory location. This could be an issue if you copy input to output then refer back to previous values of the input as they will be overwritten. It is recommended that you avoid using this flag if possible as it can decrease the speed of the plugin."] const PROP_INPLACE_BROKEN = ::ffi::ladspa_h::PROPERTY_INPLACE_BROKEN, #[doc="Indicates that the plugin is capable of running not only in a conventional host but also in a 'hard real-time' environment. To qualify for this the plugin must satisfy all of the following: * The plugin must not use malloc(), free() or other heap memory management within its run() function. All new memory used in run() must be managed via the stack. These restrictions only apply to the run() function. * The plugin will not attempt to make use of any library functions with the exceptions of functions in the ANSI standard C and C maths libraries, which the host is expected to provide. * The plugin will not access files, devices, pipes, sockets, IPC or any other mechanism that might result in process or thread blocking. * The plugin will take an amount of time to execute a run() call approximately of form (A+B*SampleCount) where A and B depend on the machine and host in use. This amount of time may not depend on input signals or plugin state. The host is left the responsibility to perform timings to estimate upper bounds for A and B."] const PROP_HARD_REALTIME_CAPABLE = ::ffi::ladspa_h::PROPERTY_HARD_RT_CAPABLE, } ); /// Represents an instance of a plugin which may be exposed as a LADSPA plugin using /// ```get_ladspa_descriptor```. It is not necessary to implement activate to deactivate. pub trait Plugin { /// The plugin instance must reset all state information dependent /// on the history of the plugin instance here. /// Will be called before `run` is called for the first time. fn activate(&mut self) { } /// Runs the plugin on a number of samples, given the connected ports. fn run<'a>(&mut self, sample_count: usize, ports: &[&'a PortConnection<'a>]); /// Indicates the plugin is no longer live. fn deactivate(&mut self) { } }
PortData
identifier_name
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependencies] * ladspa = "*" * * [lib] * name = "my_ladspa_plugin" * crate-type = ["dylib"] * ``` * This will pull in the correct dependency and ensure that the library generated when you build * your plugin is compatible with LADSPA hosts. * * ## Writing the code * You'll want to implement * ```get_ladspa_descriptor``` in your src/lib.rs. This function is expected to return 1 or more * ```PluginDescriptor```s describing the plugins exposed by your library. See the documentation * for ```get_ladspa_descriptor``` and the examples * [on Github](https://github.com/nwoeanhinnogaehr/ladspa.rs/tree/master/examples) for more * information. * * ## Testing it out * There is a list of host software supporting LADSPA on the * [LADSPA home page](http://www.ladspa.org/). In order for a host to find your plugin, you will * either need to copy the *.so file from target/ after building to /usr/lib/ladspa/ (on most * systems, it may be different on your system) or set the enviornment variable ```LADSPA_PATH``` * to equal the directory where you store your plugins. */ extern crate libc; #[macro_use] extern crate bitflags; extern crate vec_map; #[doc(hidden)] pub mod ffi; use ffi::ladspa_h; #[doc(hidden)] pub use ffi::ladspa_descriptor; use std::cell::{RefCell, RefMut}; use std::default::Default; #[allow(improper_ctypes)] extern { /** * Your plugin must implement this function. * ```get_ladspa_descriptor``` returns a description of a supported plugin for a given plugin * index. When the index is out of bounds for the number of plugins supported by your library, * you are expected to return ```None```. * * Example no-op implementation: * * ```rust{.ignore} * #[no_mangle] * pub extern fn get_ladspa_descriptor(index: u64) -> Option<ladspa::PluginDescriptor> { * None * } * ``` */ pub fn get_ladspa_descriptor(index: u64) -> Option<PluginDescriptor>; } /// The data type used internally by LADSPA for audio and control ports. pub type Data = f32; /// Describes the properties of a ```Plugin``` to be exposed as a LADSPA plugin. pub struct PluginDescriptor { /// Unique IDs are an unfortunate remnant of the LADSPA API. During development, it is /// suggested to pick one under 1000, but it should be changed before release. More information /// is available here: http://www.ladspa.org/ladspa_sdk/unique_ids.html pub unique_id: u64, /// Plugin labels are expected to be a unique descriptor string for this specific plugin within /// the library. Labels are case sensitive and expected not to contain spaces. pub label: &'static str, /// The properties of a plugin describe restrictions and features for it's use. See /// documentation for ```Properties``` for info on available options. pub properties: Properties, /// The name of the plugin. This is usually how it is identified. pub name: &'static str, /// The maker of the plugin. Can be empty. pub maker: &'static str, /// Indicates copyright of the plugin. If no copyright applies, "None" should be used. pub copyright: &'static str, /// A vector of input and output ports exposed by the plugin. See the documentation for /// ```Port``` for more information. pub ports: Vec<Port>, /// A function which creates a new instance of the plugin. /// /// Note: Initialization, such as resetting plugin state, should go in ```Plugin::activate``` rather /// than here. This should just return a basic instance, ready to be activated. /// If your plugin has no internal state, you may optionally not implement ```Plugin::activate``` /// and do everything here. pub new: fn(desc: &PluginDescriptor, sample_rate: u64) -> Box<Plugin + Send>, } #[derive(Copy, Clone, Default)] /// Represents an input or output to the plugin representing either audio or /// control data. pub struct Port { /// The name of the port. For control ports, this will likely be shown by the host in an /// automatically generated GUI next to the control. For audio ports, it is mostly just /// for identification in your code but some hosts may display it. pub name: &'static str, /// Describes the type of port: audio or control, input or output. pub desc: PortDescriptor, /// Most useful on control inputs but can be used on any type of port. pub hint: Option<ControlHint>, /// Most useful on control inputs but can be used on any type of port. pub default: Option<DefaultValue>, /// The lower bound of values to accepted by default (the host may ignore this). pub lower_bound: Option<Data>, /// The upper bound of values to accepted by default (the host may ignore this). pub upper_bound: Option<Data>, } #[derive(Copy, Clone)] /// Represents the 4 types of ports: audio or control, input or output. pub enum PortDescriptor { Invalid = 0, AudioInput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_INPUT) as isize, AudioOutput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_OUTPUT) as isize, ControlInput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_INPUT) as isize, ControlOutput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_OUTPUT) as isize, } impl Default for PortDescriptor { fn default() -> PortDescriptor { PortDescriptor::Invalid } } bitflags!( #[doc="Represents the special properties a control port may hold. These are merely hints as to the use of the port and may be completely ignored by the host. For audio ports, use ```CONTROL_HINT_NONE```. To attach multiple properties, bitwise-or them together. See documentation for the constants beginning with HINT_ for the more information."] pub flags ControlHint: i32 { #[doc="Indicates that this is a toggled port. Toggled ports may only have default values of zero or one, although the host may send any value, where <= 0 is false and > 0 is true."] const HINT_TOGGLED = ::ffi::ladspa_h::HINT_TOGGLED, #[doc="Indicates that all values related to the port will be multiplied by the sample rate by the host before passing them to your plugin. This includes the lower and upper bounds. If you want an upper bound of 22050 with this property and a sample rate of 44100, set the upper bound to 0.5"] const HINT_SAMPLE_RATE = ::ffi::ladspa_h::HINT_SAMPLE_RATE, #[doc="Indicates that the data passed through this port would be better represented on a logarithmic scale"] const HINT_LOGARITHMIC = ::ffi::ladspa_h::HINT_LOGARITHMIC, #[doc="Indicates that the data passed through this port should be represented as integers. Bounds may be interpreted exclusively depending on the host"] const HINT_INTEGER = ::ffi::ladspa_h::HINT_INTEGER, } ); #[derive(Copy, Clone)] /// The default values that a control port may hold. For audio ports, use DefaultControlValue::None. pub enum DefaultValue { /// Equal to the ```lower_bound``` of the ```Port```. Minimum = ladspa_h::HINT_DEFAULT_MINIMUM as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.75 + /// log(upper_bound) * 0.25)```. Otherwise, this should be ```(lower_bound * 0.75 + /// upper_bound * 0.25)```. Low = ladspa_h::HINT_DEFAULT_LOW as isize, /// For ports with /// ```CONTROL_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.5 + /// log(upper_bound) * 0.5)```. Otherwise, this should be ```(lower_bound * 0.5 + /// upper_bound * 0.5)```. Middle = ladspa_h::HINT_DEFAULT_MIDDLE as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.25 + /// log(upper_bound) * 0.75)```. Otherwise, this should be ```(lower_bound * 0.25 + /// upper_bound * 0.75)```. High = ladspa_h::HINT_DEFAULT_HIGH as isize, /// Equal to the ```upper_bound``` of the ```Port```. Maximum = ladspa_h::HINT_DEFAULT_MAXIMUM as isize, /// Equal to 0 or false for toggled values. Value0 = ladspa_h::HINT_DEFAULT_0 as isize, /// Equal to 1 or true for toggled values. Value1 = ladspa_h::HINT_DEFAULT_1 as isize, /// Equal to 100. Value100 = ladspa_h::HINT_DEFAULT_100 as isize, /// Equal to 440, concert A. This may be off by a few Hz if the host is using an alternate /// tuning. Value440 = ladspa_h::HINT_DEFAULT_440 as isize, } /// Represents a connection between a port and the data attached to the port by the plugin /// host. pub struct PortConnection<'a> { /// The port which the data is connected to. pub port: Port, /// The data connected to the port. It's usually simpler to use the various unwrap_* functions /// than to interface with this directly. pub data: PortData<'a>, } /// Represents the four types of data a port can hold. pub enum PortData<'a> { AudioInput(&'a [Data]), AudioOutput(RefCell<&'a mut [Data]>), ControlInput(&'a Data), ControlOutput(RefCell<&'a mut Data>), } unsafe impl<'a> Sync for PortData<'a> { } impl<'a> PortConnection<'a> { /// Returns a slice pointing to the internal data of an audio input port. Panics if this port /// is not an ```AudioIn``` port. pub fn unwrap_audio(&'a self) -> &'a [Data] { if let PortData::AudioInput(ref data) = self.data { data } else { panic!("PortConnection::unwrap_audio called on a non audio input port!") } } /// Returns a mutable slice pointing to the internal data of an audio output port. Panics if /// this port is not an ```AudioOut``` port. pub fn unwrap_audio_mut(&'a self) -> RefMut<'a, &'a mut [Data]> { if let PortData::AudioOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_audio_mut called on a non audio output port!") } } /// Returns a refrence to the internal data of an control input port. Panics if this port /// is not an ```ControlIn``` port. pub fn unwrap_control(&'a self) -> &'a Data { if let PortData::ControlInput(data) = self.data { data } else
} /// Returns a mutable refrence to the internal data of an audio output port. Panics if /// this port is not an ```ControlOut``` port. pub fn unwrap_control_mut(&'a self) -> RefMut<'a, &'a mut Data> { if let PortData::ControlOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_control called on a non control output port!") } } } bitflags!( #[doc="Represents the special properties a LADSPA plugin can have. To attach multiple properties, bitwise-or them together, for example ```PROP_REALTIME | PROP_INPLACE_BROKEN```. See documentation for the constants beginning with PROP_ for the more information."] pub flags Properties: i32 { #[doc="No properties."] const PROP_NONE = 0, #[doc="Indicates that the plugin has a realtime dependency so it's output may not be cached."] const PROP_REALTIME = ::ffi::ladspa_h::PROPERTY_REALTIME, #[doc="Indicates that the plugin will not function correctly if the input and output audio data has the same memory location. This could be an issue if you copy input to output then refer back to previous values of the input as they will be overwritten. It is recommended that you avoid using this flag if possible as it can decrease the speed of the plugin."] const PROP_INPLACE_BROKEN = ::ffi::ladspa_h::PROPERTY_INPLACE_BROKEN, #[doc="Indicates that the plugin is capable of running not only in a conventional host but also in a 'hard real-time' environment. To qualify for this the plugin must satisfy all of the following: * The plugin must not use malloc(), free() or other heap memory management within its run() function. All new memory used in run() must be managed via the stack. These restrictions only apply to the run() function. * The plugin will not attempt to make use of any library functions with the exceptions of functions in the ANSI standard C and C maths libraries, which the host is expected to provide. * The plugin will not access files, devices, pipes, sockets, IPC or any other mechanism that might result in process or thread blocking. * The plugin will take an amount of time to execute a run() call approximately of form (A+B*SampleCount) where A and B depend on the machine and host in use. This amount of time may not depend on input signals or plugin state. The host is left the responsibility to perform timings to estimate upper bounds for A and B."] const PROP_HARD_REALTIME_CAPABLE = ::ffi::ladspa_h::PROPERTY_HARD_RT_CAPABLE, } ); /// Represents an instance of a plugin which may be exposed as a LADSPA plugin using /// ```get_ladspa_descriptor```. It is not necessary to implement activate to deactivate. pub trait Plugin { /// The plugin instance must reset all state information dependent /// on the history of the plugin instance here. /// Will be called before `run` is called for the first time. fn activate(&mut self) { } /// Runs the plugin on a number of samples, given the connected ports. fn run<'a>(&mut self, sample_count: usize, ports: &[&'a PortConnection<'a>]); /// Indicates the plugin is no longer live. fn deactivate(&mut self) { } }
{ panic!("PortConnection::unwrap_control called on a non control input port!") }
conditional_block
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependencies] * ladspa = "*" * * [lib] * name = "my_ladspa_plugin" * crate-type = ["dylib"] * ``` * This will pull in the correct dependency and ensure that the library generated when you build * your plugin is compatible with LADSPA hosts. * * ## Writing the code * You'll want to implement * ```get_ladspa_descriptor``` in your src/lib.rs. This function is expected to return 1 or more * ```PluginDescriptor```s describing the plugins exposed by your library. See the documentation * for ```get_ladspa_descriptor``` and the examples * [on Github](https://github.com/nwoeanhinnogaehr/ladspa.rs/tree/master/examples) for more * information. * * ## Testing it out * There is a list of host software supporting LADSPA on the * [LADSPA home page](http://www.ladspa.org/). In order for a host to find your plugin, you will * either need to copy the *.so file from target/ after building to /usr/lib/ladspa/ (on most * systems, it may be different on your system) or set the enviornment variable ```LADSPA_PATH``` * to equal the directory where you store your plugins. */ extern crate libc; #[macro_use] extern crate bitflags; extern crate vec_map; #[doc(hidden)] pub mod ffi; use ffi::ladspa_h; #[doc(hidden)] pub use ffi::ladspa_descriptor; use std::cell::{RefCell, RefMut}; use std::default::Default; #[allow(improper_ctypes)] extern { /** * Your plugin must implement this function. * ```get_ladspa_descriptor``` returns a description of a supported plugin for a given plugin * index. When the index is out of bounds for the number of plugins supported by your library, * you are expected to return ```None```. * * Example no-op implementation: * * ```rust{.ignore} * #[no_mangle] * pub extern fn get_ladspa_descriptor(index: u64) -> Option<ladspa::PluginDescriptor> { * None * } * ``` */ pub fn get_ladspa_descriptor(index: u64) -> Option<PluginDescriptor>; } /// The data type used internally by LADSPA for audio and control ports. pub type Data = f32; /// Describes the properties of a ```Plugin``` to be exposed as a LADSPA plugin. pub struct PluginDescriptor { /// Unique IDs are an unfortunate remnant of the LADSPA API. During development, it is /// suggested to pick one under 1000, but it should be changed before release. More information /// is available here: http://www.ladspa.org/ladspa_sdk/unique_ids.html pub unique_id: u64, /// Plugin labels are expected to be a unique descriptor string for this specific plugin within /// the library. Labels are case sensitive and expected not to contain spaces. pub label: &'static str, /// The properties of a plugin describe restrictions and features for it's use. See /// documentation for ```Properties``` for info on available options. pub properties: Properties, /// The name of the plugin. This is usually how it is identified. pub name: &'static str, /// The maker of the plugin. Can be empty. pub maker: &'static str, /// Indicates copyright of the plugin. If no copyright applies, "None" should be used. pub copyright: &'static str, /// A vector of input and output ports exposed by the plugin. See the documentation for /// ```Port``` for more information. pub ports: Vec<Port>, /// A function which creates a new instance of the plugin. /// /// Note: Initialization, such as resetting plugin state, should go in ```Plugin::activate``` rather /// than here. This should just return a basic instance, ready to be activated. /// If your plugin has no internal state, you may optionally not implement ```Plugin::activate``` /// and do everything here. pub new: fn(desc: &PluginDescriptor, sample_rate: u64) -> Box<Plugin + Send>, } #[derive(Copy, Clone, Default)] /// Represents an input or output to the plugin representing either audio or /// control data. pub struct Port { /// The name of the port. For control ports, this will likely be shown by the host in an /// automatically generated GUI next to the control. For audio ports, it is mostly just /// for identification in your code but some hosts may display it. pub name: &'static str, /// Describes the type of port: audio or control, input or output. pub desc: PortDescriptor, /// Most useful on control inputs but can be used on any type of port. pub hint: Option<ControlHint>, /// Most useful on control inputs but can be used on any type of port. pub default: Option<DefaultValue>, /// The lower bound of values to accepted by default (the host may ignore this). pub lower_bound: Option<Data>, /// The upper bound of values to accepted by default (the host may ignore this). pub upper_bound: Option<Data>, } #[derive(Copy, Clone)] /// Represents the 4 types of ports: audio or control, input or output. pub enum PortDescriptor { Invalid = 0, AudioInput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_INPUT) as isize, AudioOutput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_OUTPUT) as isize, ControlInput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_INPUT) as isize, ControlOutput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_OUTPUT) as isize, } impl Default for PortDescriptor { fn default() -> PortDescriptor { PortDescriptor::Invalid } } bitflags!( #[doc="Represents the special properties a control port may hold. These are merely hints as to the use of the port and may be completely ignored by the host. For audio ports, use ```CONTROL_HINT_NONE```. To attach multiple properties, bitwise-or them together. See documentation for the constants beginning with HINT_ for the more information."] pub flags ControlHint: i32 { #[doc="Indicates that this is a toggled port. Toggled ports may only have default values of zero or one, although the host may send any value, where <= 0 is false and > 0 is true."] const HINT_TOGGLED = ::ffi::ladspa_h::HINT_TOGGLED, #[doc="Indicates that all values related to the port will be multiplied by the sample rate by the host before passing them to your plugin. This includes the lower and upper bounds. If you want an upper bound of 22050 with this property and a sample rate of 44100, set the upper bound to 0.5"] const HINT_SAMPLE_RATE = ::ffi::ladspa_h::HINT_SAMPLE_RATE, #[doc="Indicates that the data passed through this port would be better represented on a logarithmic scale"] const HINT_LOGARITHMIC = ::ffi::ladspa_h::HINT_LOGARITHMIC, #[doc="Indicates that the data passed through this port should be represented as integers. Bounds may be interpreted exclusively depending on the host"] const HINT_INTEGER = ::ffi::ladspa_h::HINT_INTEGER, } ); #[derive(Copy, Clone)] /// The default values that a control port may hold. For audio ports, use DefaultControlValue::None. pub enum DefaultValue { /// Equal to the ```lower_bound``` of the ```Port```. Minimum = ladspa_h::HINT_DEFAULT_MINIMUM as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.75 + /// log(upper_bound) * 0.25)```. Otherwise, this should be ```(lower_bound * 0.75 + /// upper_bound * 0.25)```. Low = ladspa_h::HINT_DEFAULT_LOW as isize, /// For ports with /// ```CONTROL_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.5 + /// log(upper_bound) * 0.5)```. Otherwise, this should be ```(lower_bound * 0.5 + /// upper_bound * 0.5)```. Middle = ladspa_h::HINT_DEFAULT_MIDDLE as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.25 + /// log(upper_bound) * 0.75)```. Otherwise, this should be ```(lower_bound * 0.25 + /// upper_bound * 0.75)```. High = ladspa_h::HINT_DEFAULT_HIGH as isize, /// Equal to the ```upper_bound``` of the ```Port```. Maximum = ladspa_h::HINT_DEFAULT_MAXIMUM as isize, /// Equal to 0 or false for toggled values. Value0 = ladspa_h::HINT_DEFAULT_0 as isize, /// Equal to 1 or true for toggled values. Value1 = ladspa_h::HINT_DEFAULT_1 as isize, /// Equal to 100. Value100 = ladspa_h::HINT_DEFAULT_100 as isize, /// Equal to 440, concert A. This may be off by a few Hz if the host is using an alternate /// tuning. Value440 = ladspa_h::HINT_DEFAULT_440 as isize, } /// Represents a connection between a port and the data attached to the port by the plugin /// host. pub struct PortConnection<'a> { /// The port which the data is connected to. pub port: Port, /// The data connected to the port. It's usually simpler to use the various unwrap_* functions /// than to interface with this directly. pub data: PortData<'a>, } /// Represents the four types of data a port can hold. pub enum PortData<'a> { AudioInput(&'a [Data]), AudioOutput(RefCell<&'a mut [Data]>), ControlInput(&'a Data), ControlOutput(RefCell<&'a mut Data>), } unsafe impl<'a> Sync for PortData<'a> { } impl<'a> PortConnection<'a> { /// Returns a slice pointing to the internal data of an audio input port. Panics if this port /// is not an ```AudioIn``` port. pub fn unwrap_audio(&'a self) -> &'a [Data] { if let PortData::AudioInput(ref data) = self.data { data } else { panic!("PortConnection::unwrap_audio called on a non audio input port!") } } /// Returns a mutable slice pointing to the internal data of an audio output port. Panics if
} else { panic!("PortConnection::unwrap_audio_mut called on a non audio output port!") } } /// Returns a refrence to the internal data of an control input port. Panics if this port /// is not an ```ControlIn``` port. pub fn unwrap_control(&'a self) -> &'a Data { if let PortData::ControlInput(data) = self.data { data } else { panic!("PortConnection::unwrap_control called on a non control input port!") } } /// Returns a mutable refrence to the internal data of an audio output port. Panics if /// this port is not an ```ControlOut``` port. pub fn unwrap_control_mut(&'a self) -> RefMut<'a, &'a mut Data> { if let PortData::ControlOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_control called on a non control output port!") } } } bitflags!( #[doc="Represents the special properties a LADSPA plugin can have. To attach multiple properties, bitwise-or them together, for example ```PROP_REALTIME | PROP_INPLACE_BROKEN```. See documentation for the constants beginning with PROP_ for the more information."] pub flags Properties: i32 { #[doc="No properties."] const PROP_NONE = 0, #[doc="Indicates that the plugin has a realtime dependency so it's output may not be cached."] const PROP_REALTIME = ::ffi::ladspa_h::PROPERTY_REALTIME, #[doc="Indicates that the plugin will not function correctly if the input and output audio data has the same memory location. This could be an issue if you copy input to output then refer back to previous values of the input as they will be overwritten. It is recommended that you avoid using this flag if possible as it can decrease the speed of the plugin."] const PROP_INPLACE_BROKEN = ::ffi::ladspa_h::PROPERTY_INPLACE_BROKEN, #[doc="Indicates that the plugin is capable of running not only in a conventional host but also in a 'hard real-time' environment. To qualify for this the plugin must satisfy all of the following: * The plugin must not use malloc(), free() or other heap memory management within its run() function. All new memory used in run() must be managed via the stack. These restrictions only apply to the run() function. * The plugin will not attempt to make use of any library functions with the exceptions of functions in the ANSI standard C and C maths libraries, which the host is expected to provide. * The plugin will not access files, devices, pipes, sockets, IPC or any other mechanism that might result in process or thread blocking. * The plugin will take an amount of time to execute a run() call approximately of form (A+B*SampleCount) where A and B depend on the machine and host in use. This amount of time may not depend on input signals or plugin state. The host is left the responsibility to perform timings to estimate upper bounds for A and B."] const PROP_HARD_REALTIME_CAPABLE = ::ffi::ladspa_h::PROPERTY_HARD_RT_CAPABLE, } ); /// Represents an instance of a plugin which may be exposed as a LADSPA plugin using /// ```get_ladspa_descriptor```. It is not necessary to implement activate to deactivate. pub trait Plugin { /// The plugin instance must reset all state information dependent /// on the history of the plugin instance here. /// Will be called before `run` is called for the first time. fn activate(&mut self) { } /// Runs the plugin on a number of samples, given the connected ports. fn run<'a>(&mut self, sample_count: usize, ports: &[&'a PortConnection<'a>]); /// Indicates the plugin is no longer live. fn deactivate(&mut self) { } }
/// this port is not an ```AudioOut``` port. pub fn unwrap_audio_mut(&'a self) -> RefMut<'a, &'a mut [Data]> { if let PortData::AudioOutput(ref data) = self.data { data.borrow_mut()
random_line_split
lib.rs
/*! * The ```ladspa``` crate provides an interface for writing [LADSPA](http://www.ladspa.org/) * plugins safely in Rust. * * ##Creating the project * * Run ```cargo new my_ladspa_plugin``` to generate a Cargo project for your plugin, then add * the following to the generated Cargo.toml: * * ``` * [dependencies] * ladspa = "*" * * [lib] * name = "my_ladspa_plugin" * crate-type = ["dylib"] * ``` * This will pull in the correct dependency and ensure that the library generated when you build * your plugin is compatible with LADSPA hosts. * * ## Writing the code * You'll want to implement * ```get_ladspa_descriptor``` in your src/lib.rs. This function is expected to return 1 or more * ```PluginDescriptor```s describing the plugins exposed by your library. See the documentation * for ```get_ladspa_descriptor``` and the examples * [on Github](https://github.com/nwoeanhinnogaehr/ladspa.rs/tree/master/examples) for more * information. * * ## Testing it out * There is a list of host software supporting LADSPA on the * [LADSPA home page](http://www.ladspa.org/). In order for a host to find your plugin, you will * either need to copy the *.so file from target/ after building to /usr/lib/ladspa/ (on most * systems, it may be different on your system) or set the enviornment variable ```LADSPA_PATH``` * to equal the directory where you store your plugins. */ extern crate libc; #[macro_use] extern crate bitflags; extern crate vec_map; #[doc(hidden)] pub mod ffi; use ffi::ladspa_h; #[doc(hidden)] pub use ffi::ladspa_descriptor; use std::cell::{RefCell, RefMut}; use std::default::Default; #[allow(improper_ctypes)] extern { /** * Your plugin must implement this function. * ```get_ladspa_descriptor``` returns a description of a supported plugin for a given plugin * index. When the index is out of bounds for the number of plugins supported by your library, * you are expected to return ```None```. * * Example no-op implementation: * * ```rust{.ignore} * #[no_mangle] * pub extern fn get_ladspa_descriptor(index: u64) -> Option<ladspa::PluginDescriptor> { * None * } * ``` */ pub fn get_ladspa_descriptor(index: u64) -> Option<PluginDescriptor>; } /// The data type used internally by LADSPA for audio and control ports. pub type Data = f32; /// Describes the properties of a ```Plugin``` to be exposed as a LADSPA plugin. pub struct PluginDescriptor { /// Unique IDs are an unfortunate remnant of the LADSPA API. During development, it is /// suggested to pick one under 1000, but it should be changed before release. More information /// is available here: http://www.ladspa.org/ladspa_sdk/unique_ids.html pub unique_id: u64, /// Plugin labels are expected to be a unique descriptor string for this specific plugin within /// the library. Labels are case sensitive and expected not to contain spaces. pub label: &'static str, /// The properties of a plugin describe restrictions and features for it's use. See /// documentation for ```Properties``` for info on available options. pub properties: Properties, /// The name of the plugin. This is usually how it is identified. pub name: &'static str, /// The maker of the plugin. Can be empty. pub maker: &'static str, /// Indicates copyright of the plugin. If no copyright applies, "None" should be used. pub copyright: &'static str, /// A vector of input and output ports exposed by the plugin. See the documentation for /// ```Port``` for more information. pub ports: Vec<Port>, /// A function which creates a new instance of the plugin. /// /// Note: Initialization, such as resetting plugin state, should go in ```Plugin::activate``` rather /// than here. This should just return a basic instance, ready to be activated. /// If your plugin has no internal state, you may optionally not implement ```Plugin::activate``` /// and do everything here. pub new: fn(desc: &PluginDescriptor, sample_rate: u64) -> Box<Plugin + Send>, } #[derive(Copy, Clone, Default)] /// Represents an input or output to the plugin representing either audio or /// control data. pub struct Port { /// The name of the port. For control ports, this will likely be shown by the host in an /// automatically generated GUI next to the control. For audio ports, it is mostly just /// for identification in your code but some hosts may display it. pub name: &'static str, /// Describes the type of port: audio or control, input or output. pub desc: PortDescriptor, /// Most useful on control inputs but can be used on any type of port. pub hint: Option<ControlHint>, /// Most useful on control inputs but can be used on any type of port. pub default: Option<DefaultValue>, /// The lower bound of values to accepted by default (the host may ignore this). pub lower_bound: Option<Data>, /// The upper bound of values to accepted by default (the host may ignore this). pub upper_bound: Option<Data>, } #[derive(Copy, Clone)] /// Represents the 4 types of ports: audio or control, input or output. pub enum PortDescriptor { Invalid = 0, AudioInput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_INPUT) as isize, AudioOutput = (ladspa_h::PORT_AUDIO | ladspa_h::PORT_OUTPUT) as isize, ControlInput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_INPUT) as isize, ControlOutput = (ladspa_h::PORT_CONTROL | ladspa_h::PORT_OUTPUT) as isize, } impl Default for PortDescriptor { fn default() -> PortDescriptor { PortDescriptor::Invalid } } bitflags!( #[doc="Represents the special properties a control port may hold. These are merely hints as to the use of the port and may be completely ignored by the host. For audio ports, use ```CONTROL_HINT_NONE```. To attach multiple properties, bitwise-or them together. See documentation for the constants beginning with HINT_ for the more information."] pub flags ControlHint: i32 { #[doc="Indicates that this is a toggled port. Toggled ports may only have default values of zero or one, although the host may send any value, where <= 0 is false and > 0 is true."] const HINT_TOGGLED = ::ffi::ladspa_h::HINT_TOGGLED, #[doc="Indicates that all values related to the port will be multiplied by the sample rate by the host before passing them to your plugin. This includes the lower and upper bounds. If you want an upper bound of 22050 with this property and a sample rate of 44100, set the upper bound to 0.5"] const HINT_SAMPLE_RATE = ::ffi::ladspa_h::HINT_SAMPLE_RATE, #[doc="Indicates that the data passed through this port would be better represented on a logarithmic scale"] const HINT_LOGARITHMIC = ::ffi::ladspa_h::HINT_LOGARITHMIC, #[doc="Indicates that the data passed through this port should be represented as integers. Bounds may be interpreted exclusively depending on the host"] const HINT_INTEGER = ::ffi::ladspa_h::HINT_INTEGER, } ); #[derive(Copy, Clone)] /// The default values that a control port may hold. For audio ports, use DefaultControlValue::None. pub enum DefaultValue { /// Equal to the ```lower_bound``` of the ```Port```. Minimum = ladspa_h::HINT_DEFAULT_MINIMUM as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.75 + /// log(upper_bound) * 0.25)```. Otherwise, this should be ```(lower_bound * 0.75 + /// upper_bound * 0.25)```. Low = ladspa_h::HINT_DEFAULT_LOW as isize, /// For ports with /// ```CONTROL_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.5 + /// log(upper_bound) * 0.5)```. Otherwise, this should be ```(lower_bound * 0.5 + /// upper_bound * 0.5)```. Middle = ladspa_h::HINT_DEFAULT_MIDDLE as isize, /// For ports with /// ```LADSPA_HINT_LOGARITHMIC```, this should be ```exp(log(lower_bound) * 0.25 + /// log(upper_bound) * 0.75)```. Otherwise, this should be ```(lower_bound * 0.25 + /// upper_bound * 0.75)```. High = ladspa_h::HINT_DEFAULT_HIGH as isize, /// Equal to the ```upper_bound``` of the ```Port```. Maximum = ladspa_h::HINT_DEFAULT_MAXIMUM as isize, /// Equal to 0 or false for toggled values. Value0 = ladspa_h::HINT_DEFAULT_0 as isize, /// Equal to 1 or true for toggled values. Value1 = ladspa_h::HINT_DEFAULT_1 as isize, /// Equal to 100. Value100 = ladspa_h::HINT_DEFAULT_100 as isize, /// Equal to 440, concert A. This may be off by a few Hz if the host is using an alternate /// tuning. Value440 = ladspa_h::HINT_DEFAULT_440 as isize, } /// Represents a connection between a port and the data attached to the port by the plugin /// host. pub struct PortConnection<'a> { /// The port which the data is connected to. pub port: Port, /// The data connected to the port. It's usually simpler to use the various unwrap_* functions /// than to interface with this directly. pub data: PortData<'a>, } /// Represents the four types of data a port can hold. pub enum PortData<'a> { AudioInput(&'a [Data]), AudioOutput(RefCell<&'a mut [Data]>), ControlInput(&'a Data), ControlOutput(RefCell<&'a mut Data>), } unsafe impl<'a> Sync for PortData<'a> { } impl<'a> PortConnection<'a> { /// Returns a slice pointing to the internal data of an audio input port. Panics if this port /// is not an ```AudioIn``` port. pub fn unwrap_audio(&'a self) -> &'a [Data] { if let PortData::AudioInput(ref data) = self.data { data } else { panic!("PortConnection::unwrap_audio called on a non audio input port!") } } /// Returns a mutable slice pointing to the internal data of an audio output port. Panics if /// this port is not an ```AudioOut``` port. pub fn unwrap_audio_mut(&'a self) -> RefMut<'a, &'a mut [Data]> { if let PortData::AudioOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_audio_mut called on a non audio output port!") } } /// Returns a refrence to the internal data of an control input port. Panics if this port /// is not an ```ControlIn``` port. pub fn unwrap_control(&'a self) -> &'a Data { if let PortData::ControlInput(data) = self.data { data } else { panic!("PortConnection::unwrap_control called on a non control input port!") } } /// Returns a mutable refrence to the internal data of an audio output port. Panics if /// this port is not an ```ControlOut``` port. pub fn unwrap_control_mut(&'a self) -> RefMut<'a, &'a mut Data> { if let PortData::ControlOutput(ref data) = self.data { data.borrow_mut() } else { panic!("PortConnection::unwrap_control called on a non control output port!") } } } bitflags!( #[doc="Represents the special properties a LADSPA plugin can have. To attach multiple properties, bitwise-or them together, for example ```PROP_REALTIME | PROP_INPLACE_BROKEN```. See documentation for the constants beginning with PROP_ for the more information."] pub flags Properties: i32 { #[doc="No properties."] const PROP_NONE = 0, #[doc="Indicates that the plugin has a realtime dependency so it's output may not be cached."] const PROP_REALTIME = ::ffi::ladspa_h::PROPERTY_REALTIME, #[doc="Indicates that the plugin will not function correctly if the input and output audio data has the same memory location. This could be an issue if you copy input to output then refer back to previous values of the input as they will be overwritten. It is recommended that you avoid using this flag if possible as it can decrease the speed of the plugin."] const PROP_INPLACE_BROKEN = ::ffi::ladspa_h::PROPERTY_INPLACE_BROKEN, #[doc="Indicates that the plugin is capable of running not only in a conventional host but also in a 'hard real-time' environment. To qualify for this the plugin must satisfy all of the following: * The plugin must not use malloc(), free() or other heap memory management within its run() function. All new memory used in run() must be managed via the stack. These restrictions only apply to the run() function. * The plugin will not attempt to make use of any library functions with the exceptions of functions in the ANSI standard C and C maths libraries, which the host is expected to provide. * The plugin will not access files, devices, pipes, sockets, IPC or any other mechanism that might result in process or thread blocking. * The plugin will take an amount of time to execute a run() call approximately of form (A+B*SampleCount) where A and B depend on the machine and host in use. This amount of time may not depend on input signals or plugin state. The host is left the responsibility to perform timings to estimate upper bounds for A and B."] const PROP_HARD_REALTIME_CAPABLE = ::ffi::ladspa_h::PROPERTY_HARD_RT_CAPABLE, } ); /// Represents an instance of a plugin which may be exposed as a LADSPA plugin using /// ```get_ladspa_descriptor```. It is not necessary to implement activate to deactivate. pub trait Plugin { /// The plugin instance must reset all state information dependent /// on the history of the plugin instance here. /// Will be called before `run` is called for the first time. fn activate(&mut self)
/// Runs the plugin on a number of samples, given the connected ports. fn run<'a>(&mut self, sample_count: usize, ports: &[&'a PortConnection<'a>]); /// Indicates the plugin is no longer live. fn deactivate(&mut self) { } }
{ }
identifier_body
enum_iterator.rs
#[macro_use] extern crate custom_derive; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:ident,)*) ) => { type NameIter = ::std::vec::IntoIter<&'static str>; type VariantIter = ::std::vec::IntoIter<$name>; impl $name { #[allow(dead_code)] pub fn iter_variants() -> VariantIter { vec![$($name::$var_names),*].into_iter() } #[allow(dead_code)] pub fn iter_variant_names() -> NameIter { vec![$(stringify!($var_names)),*].into_iter() } } }; ( @collect_variants $fixed:tt, ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*) ) => { EnumIterator! { @collect_variants $fixed, ($($tail)*) -> ($($var_names)* $var,) } }; ( @collect_variants ($name:ident), ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*) ) => { const _error: () = concat!( "cannot derive EnumIterator for ", stringify!($name), ", due to non-unitary variant ", stringify!($var), "." ); }; } custom_derive! { #[derive(Debug, PartialEq, EnumIterator)] enum Get { Up, Down, AllAround }
} #[test] fn test_enum_iterator() { let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); }
random_line_split
enum_iterator.rs
#[macro_use] extern crate custom_derive; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:ident,)*) ) => { type NameIter = ::std::vec::IntoIter<&'static str>; type VariantIter = ::std::vec::IntoIter<$name>; impl $name { #[allow(dead_code)] pub fn iter_variants() -> VariantIter { vec![$($name::$var_names),*].into_iter() } #[allow(dead_code)] pub fn iter_variant_names() -> NameIter { vec![$(stringify!($var_names)),*].into_iter() } } }; ( @collect_variants $fixed:tt, ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*) ) => { EnumIterator! { @collect_variants $fixed, ($($tail)*) -> ($($var_names)* $var,) } }; ( @collect_variants ($name:ident), ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*) ) => { const _error: () = concat!( "cannot derive EnumIterator for ", stringify!($name), ", due to non-unitary variant ", stringify!($var), "." ); }; } custom_derive! { #[derive(Debug, PartialEq, EnumIterator)] enum Get { Up, Down, AllAround } } #[test] fn test_enum_iterator()
{ let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); }
identifier_body
enum_iterator.rs
#[macro_use] extern crate custom_derive; macro_rules! EnumIterator { (() $(pub)* enum $name:ident { $($body:tt)* }) => { EnumIterator! { @collect_variants ($name), ($($body)*,) -> () } }; ( @collect_variants ($name:ident), ($(,)*) -> ($($var_names:ident,)*) ) => { type NameIter = ::std::vec::IntoIter<&'static str>; type VariantIter = ::std::vec::IntoIter<$name>; impl $name { #[allow(dead_code)] pub fn iter_variants() -> VariantIter { vec![$($name::$var_names),*].into_iter() } #[allow(dead_code)] pub fn iter_variant_names() -> NameIter { vec![$(stringify!($var_names)),*].into_iter() } } }; ( @collect_variants $fixed:tt, ($var:ident $(= $_val:expr)*, $($tail:tt)*) -> ($($var_names:tt)*) ) => { EnumIterator! { @collect_variants $fixed, ($($tail)*) -> ($($var_names)* $var,) } }; ( @collect_variants ($name:ident), ($var:ident $_struct:tt, $($tail:tt)*) -> ($($var_names:tt)*) ) => { const _error: () = concat!( "cannot derive EnumIterator for ", stringify!($name), ", due to non-unitary variant ", stringify!($var), "." ); }; } custom_derive! { #[derive(Debug, PartialEq, EnumIterator)] enum Get { Up, Down, AllAround } } #[test] fn
() { let vs: Vec<_> = Get::iter_variant_names().zip(Get::iter_variants()).collect(); assert_eq!(&*vs, &[("Up", Get::Up), ("Down", Get::Down), ("AllAround", Get::AllAround)]); }
test_enum_iterator
identifier_name
lib.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(allocator_api)] #![feature(box_syntax)] #![feature(drain_filter)] #![feature(exact_size_is_empty)] #![feature(pattern)] #![feature(slice_sort_by_cached_key)] #![feature(str_escape)] #![feature(try_reserve)] #![feature(unboxed_closures)] #![feature(repeat_generic_slice)] extern crate core; extern crate rand; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; mod arc; mod binary_heap; mod btree; mod cow_str; mod fmt; mod heap; mod linked_list; mod rc; mod slice; mod str; mod string; mod vec_deque; mod vec; fn
<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } // FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten. // See https://github.com/kripken/emscripten-fastcomp/issues/169 #[cfg(not(target_os = "emscripten"))] #[test] fn test_boxed_hasher() { let ordinary_hash = hash(&5u32); let mut hasher_1 = Box::new(DefaultHasher::new()); 5u32.hash(&mut hasher_1); assert_eq!(ordinary_hash, hasher_1.finish()); let mut hasher_2 = Box::new(DefaultHasher::new()) as Box<dyn Hasher>; 5u32.hash(&mut hasher_2); assert_eq!(ordinary_hash, hasher_2.finish()); }
hash
identifier_name
lib.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(allocator_api)] #![feature(box_syntax)] #![feature(drain_filter)] #![feature(exact_size_is_empty)] #![feature(pattern)] #![feature(slice_sort_by_cached_key)] #![feature(str_escape)] #![feature(try_reserve)] #![feature(unboxed_closures)] #![feature(repeat_generic_slice)] extern crate core; extern crate rand; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher; mod arc; mod binary_heap; mod btree; mod cow_str; mod fmt; mod heap; mod linked_list; mod rc; mod slice; mod str; mod string; mod vec_deque; mod vec; fn hash<T: Hash>(t: &T) -> u64
// FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten. // See https://github.com/kripken/emscripten-fastcomp/issues/169 #[cfg(not(target_os = "emscripten"))] #[test] fn test_boxed_hasher() { let ordinary_hash = hash(&5u32); let mut hasher_1 = Box::new(DefaultHasher::new()); 5u32.hash(&mut hasher_1); assert_eq!(ordinary_hash, hasher_1.finish()); let mut hasher_2 = Box::new(DefaultHasher::new()) as Box<dyn Hasher>; 5u32.hash(&mut hasher_2); assert_eq!(ordinary_hash, hasher_2.finish()); }
{ let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() }
identifier_body
lib.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(allocator_api)] #![feature(box_syntax)] #![feature(drain_filter)] #![feature(exact_size_is_empty)] #![feature(pattern)] #![feature(slice_sort_by_cached_key)] #![feature(str_escape)] #![feature(try_reserve)] #![feature(unboxed_closures)] #![feature(repeat_generic_slice)] extern crate core; extern crate rand; use std::hash::{Hash, Hasher}; use std::collections::hash_map::DefaultHasher;
mod arc; mod binary_heap; mod btree; mod cow_str; mod fmt; mod heap; mod linked_list; mod rc; mod slice; mod str; mod string; mod vec_deque; mod vec; fn hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } // FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten. // See https://github.com/kripken/emscripten-fastcomp/issues/169 #[cfg(not(target_os = "emscripten"))] #[test] fn test_boxed_hasher() { let ordinary_hash = hash(&5u32); let mut hasher_1 = Box::new(DefaultHasher::new()); 5u32.hash(&mut hasher_1); assert_eq!(ordinary_hash, hasher_1.finish()); let mut hasher_2 = Box::new(DefaultHasher::new()) as Box<dyn Hasher>; 5u32.hash(&mut hasher_2); assert_eq!(ordinary_hash, hasher_2.finish()); }
random_line_split
lib.rs
pub fn sing(start: i32, end: i32) -> String { let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; } pub fn
(num: i32) -> String { let mut out = String::new(); match num { 0 => { out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }, 1 => { out.push_str(format!("{x} bottle of beer on the wall, {x} bottle of beer.\n", x = num).as_str()); out.push_str(format!("Take it down and pass it around, no more bottles of beer on the wall.\n").as_str()); }, 2 => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottle of beer on the wall.\n", x = num - 1).as_str()); }, _ => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottles of beer on the wall.\n", x = num - 1).as_str()); } } return out; }
verse
identifier_name
lib.rs
pub fn sing(start: i32, end: i32) -> String
pub fn verse(num: i32) -> String { let mut out = String::new(); match num { 0 => { out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }, 1 => { out.push_str(format!("{x} bottle of beer on the wall, {x} bottle of beer.\n", x = num).as_str()); out.push_str(format!("Take it down and pass it around, no more bottles of beer on the wall.\n").as_str()); }, 2 => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottle of beer on the wall.\n", x = num - 1).as_str()); }, _ => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottles of beer on the wall.\n", x = num - 1).as_str()); } } return out; }
{ let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; }
identifier_body
lib.rs
pub fn sing(start: i32, end: i32) -> String { let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; } pub fn verse(num: i32) -> String { let mut out = String::new(); match num { 0 =>
, 1 => { out.push_str(format!("{x} bottle of beer on the wall, {x} bottle of beer.\n", x = num).as_str()); out.push_str(format!("Take it down and pass it around, no more bottles of beer on the wall.\n").as_str()); }, 2 => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottle of beer on the wall.\n", x = num - 1).as_str()); }, _ => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottles of beer on the wall.\n", x = num - 1).as_str()); } } return out; }
{ out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }
conditional_block
lib.rs
pub fn sing(start: i32, end: i32) -> String { let mut out = String::new(); let mut count = start; while count >= end { out.push_str(verse(count).as_str()); out.push('\n'); count -= 1; } out.pop(); return out; } pub fn verse(num: i32) -> String { let mut out = String::new(); match num { 0 => { out.push_str(format!("No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n").as_str()); }, 1 => { out.push_str(format!("{x} bottle of beer on the wall, {x} bottle of beer.\n", x = num).as_str()); out.push_str(format!("Take it down and pass it around, no more bottles of beer on the wall.\n").as_str());
2 => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottle of beer on the wall.\n", x = num - 1).as_str()); }, _ => { out.push_str(format!("{x} bottles of beer on the wall, {x} bottles of beer.\n", x = num).as_str()); out.push_str(format!("Take one down and pass it around, {x} bottles of beer on the wall.\n", x = num - 1).as_str()); } } return out; }
},
random_line_split
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn filter_types(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for operation in service.operations.values() { if let Some(ref output) = operation.output { let output_shape = service.shapes .get(&output.shape) .expect("Shape type missing from service definition"); if!can_skip_deserializer(service, output_shape) { recurse_find_shapes(service, &mut deserialized_types, &output.shape); } } if let Some(ref input) = operation.input { recurse_find_shapes(service, &mut serialized_types, &input.shape); } } (serialized_types, deserialized_types) } fn recurse_find_shapes(service: &Service, types: &mut HashSet<String>, shape_name: &str) { types.insert(mutate_type_name(shape_name).to_owned()); let shape = service.shapes.get(shape_name).expect("Shape type missing from service definition"); match shape.shape_type { ShapeType::Structure => { if let Some(ref members) = shape.members { for member in members.values() { if Some(true)!= member.deprecated && member.location!= Some("header".to_owned()) && member.location!= Some("headers".to_owned()) && !types.contains(&member.shape) { recurse_find_shapes(service, types, &member.shape); } } } } ShapeType::Map => { recurse_find_shapes(service, types, shape.key_type()); recurse_find_shapes(service, types, shape.value_type()); } ShapeType::List =>
_ => {} } } // output shapes with a payload blob don't get deserialized // unless they have non-payload elements from the headers etc. fn can_skip_deserializer(service: &Service, output_shape: &Shape) -> bool { match output_shape.payload { None => false, Some(ref payload_member) => { let payload_shape_type = &output_shape.members.as_ref().unwrap()[payload_member].shape; let payload_shape = &service.shapes[payload_shape_type]; let has_streaming_payload = payload_shape.shape_type == ShapeType::Blob || payload_shape.shape_type == ShapeType::String; let mut has_other_members = false; for member in output_shape.members.as_ref().unwrap().values() { if member.location.is_some() { has_other_members = true; break; } } has_streaming_payload &&!has_other_members } } }
{ recurse_find_shapes(service, types, shape.member_type()); }
conditional_block
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn filter_types(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for operation in service.operations.values() { if let Some(ref output) = operation.output { let output_shape = service.shapes .get(&output.shape) .expect("Shape type missing from service definition"); if!can_skip_deserializer(service, output_shape) { recurse_find_shapes(service, &mut deserialized_types, &output.shape); } } if let Some(ref input) = operation.input { recurse_find_shapes(service, &mut serialized_types, &input.shape); } } (serialized_types, deserialized_types) } fn recurse_find_shapes(service: &Service, types: &mut HashSet<String>, shape_name: &str) { types.insert(mutate_type_name(shape_name).to_owned()); let shape = service.shapes.get(shape_name).expect("Shape type missing from service definition"); match shape.shape_type { ShapeType::Structure => { if let Some(ref members) = shape.members { for member in members.values() { if Some(true)!= member.deprecated &&
member.location!= Some("headers".to_owned()) && !types.contains(&member.shape) { recurse_find_shapes(service, types, &member.shape); } } } } ShapeType::Map => { recurse_find_shapes(service, types, shape.key_type()); recurse_find_shapes(service, types, shape.value_type()); } ShapeType::List => { recurse_find_shapes(service, types, shape.member_type()); } _ => {} } } // output shapes with a payload blob don't get deserialized // unless they have non-payload elements from the headers etc. fn can_skip_deserializer(service: &Service, output_shape: &Shape) -> bool { match output_shape.payload { None => false, Some(ref payload_member) => { let payload_shape_type = &output_shape.members.as_ref().unwrap()[payload_member].shape; let payload_shape = &service.shapes[payload_shape_type]; let has_streaming_payload = payload_shape.shape_type == ShapeType::Blob || payload_shape.shape_type == ShapeType::String; let mut has_other_members = false; for member in output_shape.members.as_ref().unwrap().values() { if member.location.is_some() { has_other_members = true; break; } } has_streaming_payload &&!has_other_members } } }
member.location != Some("header".to_owned()) &&
random_line_split
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn
(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for operation in service.operations.values() { if let Some(ref output) = operation.output { let output_shape = service.shapes .get(&output.shape) .expect("Shape type missing from service definition"); if!can_skip_deserializer(service, output_shape) { recurse_find_shapes(service, &mut deserialized_types, &output.shape); } } if let Some(ref input) = operation.input { recurse_find_shapes(service, &mut serialized_types, &input.shape); } } (serialized_types, deserialized_types) } fn recurse_find_shapes(service: &Service, types: &mut HashSet<String>, shape_name: &str) { types.insert(mutate_type_name(shape_name).to_owned()); let shape = service.shapes.get(shape_name).expect("Shape type missing from service definition"); match shape.shape_type { ShapeType::Structure => { if let Some(ref members) = shape.members { for member in members.values() { if Some(true)!= member.deprecated && member.location!= Some("header".to_owned()) && member.location!= Some("headers".to_owned()) && !types.contains(&member.shape) { recurse_find_shapes(service, types, &member.shape); } } } } ShapeType::Map => { recurse_find_shapes(service, types, shape.key_type()); recurse_find_shapes(service, types, shape.value_type()); } ShapeType::List => { recurse_find_shapes(service, types, shape.member_type()); } _ => {} } } // output shapes with a payload blob don't get deserialized // unless they have non-payload elements from the headers etc. fn can_skip_deserializer(service: &Service, output_shape: &Shape) -> bool { match output_shape.payload { None => false, Some(ref payload_member) => { let payload_shape_type = &output_shape.members.as_ref().unwrap()[payload_member].shape; let payload_shape = &service.shapes[payload_shape_type]; let has_streaming_payload = payload_shape.shape_type == ShapeType::Blob || payload_shape.shape_type == ShapeType::String; let mut has_other_members = false; for member in output_shape.members.as_ref().unwrap().values() { if member.location.is_some() { has_other_members = true; break; } } has_streaming_payload &&!has_other_members } } }
filter_types
identifier_name
type_filter.rs
use std::collections::HashSet; use botocore::{Service, ShapeType, Shape}; use super::mutate_type_name; pub fn filter_types(service: &Service) -> (HashSet<String>, HashSet<String>) { let mut deserialized_types: HashSet<String> = HashSet::new(); let mut serialized_types: HashSet<String> = HashSet::new(); for operation in service.operations.values() { if let Some(ref output) = operation.output { let output_shape = service.shapes .get(&output.shape) .expect("Shape type missing from service definition"); if!can_skip_deserializer(service, output_shape) { recurse_find_shapes(service, &mut deserialized_types, &output.shape); } } if let Some(ref input) = operation.input { recurse_find_shapes(service, &mut serialized_types, &input.shape); } } (serialized_types, deserialized_types) } fn recurse_find_shapes(service: &Service, types: &mut HashSet<String>, shape_name: &str)
ShapeType::List => { recurse_find_shapes(service, types, shape.member_type()); } _ => {} } } // output shapes with a payload blob don't get deserialized // unless they have non-payload elements from the headers etc. fn can_skip_deserializer(service: &Service, output_shape: &Shape) -> bool { match output_shape.payload { None => false, Some(ref payload_member) => { let payload_shape_type = &output_shape.members.as_ref().unwrap()[payload_member].shape; let payload_shape = &service.shapes[payload_shape_type]; let has_streaming_payload = payload_shape.shape_type == ShapeType::Blob || payload_shape.shape_type == ShapeType::String; let mut has_other_members = false; for member in output_shape.members.as_ref().unwrap().values() { if member.location.is_some() { has_other_members = true; break; } } has_streaming_payload &&!has_other_members } } }
{ types.insert(mutate_type_name(shape_name).to_owned()); let shape = service.shapes.get(shape_name).expect("Shape type missing from service definition"); match shape.shape_type { ShapeType::Structure => { if let Some(ref members) = shape.members { for member in members.values() { if Some(true) != member.deprecated && member.location != Some("header".to_owned()) && member.location != Some("headers".to_owned()) && !types.contains(&member.shape) { recurse_find_shapes(service, types, &member.shape); } } } } ShapeType::Map => { recurse_find_shapes(service, types, shape.key_type()); recurse_find_shapes(service, types, shape.value_type()); }
identifier_body
lint-unnecessary-parens.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. #[deny(unnecessary_parens)]; fn foo() -> int { return (1); //~ ERROR unnecessary parentheses around `return` value } fn main() { foo();
if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } }
random_line_split
lint-unnecessary-parens.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. #[deny(unnecessary_parens)]; fn foo() -> int { return (1); //~ ERROR unnecessary parentheses around `return` value } fn main()
{ foo(); if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } }
identifier_body
lint-unnecessary-parens.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. #[deny(unnecessary_parens)]; fn foo() -> int { return (1); //~ ERROR unnecessary parentheses around `return` value } fn main() { foo(); if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ =>
} }
{}
conditional_block
lint-unnecessary-parens.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. #[deny(unnecessary_parens)]; fn foo() -> int { return (1); //~ ERROR unnecessary parentheses around `return` value } fn
() { foo(); if (true) {} //~ ERROR unnecessary parentheses around `if` condition while (true) {} //~ ERROR unnecessary parentheses around `while` condition match (true) { //~ ERROR unnecessary parentheses around `match` head expression _ => {} } }
main
identifier_name
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::sync::{Arc, Mutex}; extern crate env_logger; extern crate getopts; extern crate irc; extern crate postgres; extern crate rand; extern crate regex; #[macro_use] extern crate log; fn init_pg_tables() -> Connection
fn main() { env_logger::init().unwrap(); let mut opts = getopts::Options::new(); opts.reqopt("", "host", "irc server hostname", "HOSTNAME"); opts.optopt("", "port", "irc server port", "PORT"); opts.reqopt("n", "nick", "nickname", "NICK"); opts.optmulti("c", "chan", "channels to join", "CHAN"); let args: Vec<String> = env::args().collect(); let matches = opts.parse(&args[1..]).unwrap(); let host = matches.opt_str("host").expect("must provide --host"); let mut port = 6667; if matches.opt_present("port") { port = u16::from_str(&matches.opt_str("port").expect("must provide argument to --port")).unwrap(); } let addr = (host.as_ref(), port); let nick = matches.opt_str("nick").expect("must provide --nick"); let channels = matches.opt_strs("chan"); let choice_nick = nick.clone(); let choice_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&choice_nick)) { let choices: Vec<_> = regex!(r"\s+or\s+") .split(pm.msg) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if choices.len() > 1 { let mut rng = thread_rng(); if let Some(reply_to) = pm.reply_target(&choice_nick) { return Response::respond(protocol::Privmsg::new(reply_to, rng.choose(&choices).unwrap()).format()); } } } Response::nothing() }; let pg = Arc::new(Mutex::new(init_pg_tables())); // { // // TODO: Seed our knowledge // let mut knowledge = knowledge_mutex.lock().unwrap(); // knowledge.insert(format!("{}: info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // knowledge.insert(format!("{}, info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // } let learning_pg = pg.clone(); let learning_nick = nick.clone(); let learning_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&learning_nick)) { let assignment: Vec<_> = regex!(r"\s+is\s+") .splitn(pm.msg, 2) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if assignment.len() == 2 { let conn = learning_pg.lock().unwrap(); conn.execute(sql!("INSERT INTO knowledge (key, val) VALUES ($1, $2)"), &[&assignment[0], &assignment[1]]).unwrap(); } } Response::nothing() }; let info_pg = pg.clone(); let info_nick = nick.clone(); let info_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(reply_to) = pm.reply_target(&info_nick) { let mut rng = thread_rng(); let conn = info_pg.lock().unwrap(); let info_stmt = conn.prepare(sql!("SELECT val FROM knowledge WHERE key = $1")).unwrap(); if let Some(choice) = rand::sample(&mut rng, info_stmt.query(&[&pm.msg]).unwrap().into_iter().map(|r| { r.get::<_, String>(0) }), 1).get(0) { if let Some(c) = regex!(r"^<action>\s+(.*)$").captures(choice) { return Response::respond(protocol::Privmsg::new(reply_to, &protocol::ctcp_action(c.at(1).expect("Bad regex match"))).format()); } else { return Response::respond(protocol::Privmsg::new(reply_to, choice).format()); } } } } Response::nothing() }; let karma_pg = pg.clone(); let karma_nick = nick.clone(); let karma_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(c) = regex!(r"^([^-+\s]+)(\+\+|--)$").captures(pm.msg) { let n = c.at(1).expect("Bad match group"); let inc = c.at(2).expect("Bad match group") == "++"; let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT count(nick) FROM karma WHERE nick = $1")).unwrap(); let count: i64 = stmt.query(&[&n]).unwrap().into_iter().next().unwrap().get(0); let change = if inc { 1 } else { -1 }; if count == 0 { conn.execute(sql!("INSERT INTO karma (nick, karma) VALUES ($1, $2)"), &[&n, &change]).unwrap(); } else { conn.execute(sql!("UPDATE karma SET karma = karma + $2 WHERE nick = $1"), &[&n, &change]).unwrap(); } } else if let Some(c) = regex!(r"^karma\s+([^\s]+)$").captures(pm.msg) { if let Some(reply_to) = pm.reply_target(&karma_nick) { let n = c.at(1).expect("Bad match group"); let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT karma FROM karma WHERE nick = $1")).unwrap(); let k: i32 = stmt.query(&[&n]).unwrap() .into_iter().next().and_then(|r| r.get(0)).or(Some(0)).unwrap(); return Response::respond(protocol::Privmsg::new(reply_to, &format!("{}: {}", n, k)).format()) } } } Response::nothing() }; let join_nick = nick.clone(); let join_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&join_nick)) { if let Some(c) = regex!(r"^(join|part) (#[^\s]+)").captures(pm.msg) { let action = c.at(1).expect("Bad match group"); let chan = c.at(2).expect("Bad match group"); let success_msg = format!("{} channel {}!", if action == "join" { "Joined" } else { "Left" }, chan); if let Ok(joined_regex) = Regex::new(&format!(r"{}\s+:?{}", action.to_ascii_uppercase(), chan)) { let joined_handler = box move |joined_line: &str| { if joined_regex.is_match(joined_line) { info!("{}", success_msg); return Response(None, HandlerAction::Remove, Action::Skip); } Response::nothing() }; info!("{} channel {}...", if action == "join" { "Joining" } else { "Leaving" }, chan); return Response(Some(format!("{} {}", action.to_ascii_uppercase(), chan)), HandlerAction::Add(joined_handler), Action::Skip); } } } Response::nothing() }; let echo_nick = nick.clone(); let echo_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&echo_nick)) { if regex!(r"^[Hh]i$").is_match(pm.msg) { if let Some(reply_to) = pm.reply_target(&echo_nick) { if let Some(protocol::Source::User(ref user_info)) = pm.src { return Response::respond(protocol::Privmsg::new(reply_to, &format!("Hi, {}!", user_info.nick)).format()); } } } else if regex!(r"^go away$").is_match(pm.msg) { return Response(None, HandlerAction::Keep, Action::Stop); } } Response::nothing() }; let (mut client, join_handle) = irc::Client::connect( &addr, &nick, &channels.iter().map(|s| s.as_ref()).collect::<Vec<&str>>(), "leifw_rustbot", "leifw's rust robot") .ok().expect(&format!("Error connecting to {:?}.", addr)); client.add_handler(choice_handler); client.add_handler(learning_handler); client.add_handler(karma_handler); client.add_handler(info_handler); client.add_handler(join_handler); client.add_handler(echo_handler); join_handle.join().unwrap_or_else(|_| { error!("Unknown error!"); }); }
{ let pg = Connection::connect("postgres://leif@localhost", &SslMode::None).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS knowledge ( key VARCHAR, val VARCHAR, PRIMARY KEY(key, val) )", &[]).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS karma ( nick VARCHAR PRIMARY KEY, karma INTEGER NOT NULL DEFAULT 0 )", &[]).unwrap(); pg }
identifier_body
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::sync::{Arc, Mutex}; extern crate env_logger; extern crate getopts; extern crate irc; extern crate postgres; extern crate rand; extern crate regex; #[macro_use] extern crate log; fn init_pg_tables() -> Connection { let pg = Connection::connect("postgres://leif@localhost", &SslMode::None).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS knowledge ( key VARCHAR, val VARCHAR, PRIMARY KEY(key, val) )", &[]).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS karma ( nick VARCHAR PRIMARY KEY, karma INTEGER NOT NULL DEFAULT 0 )", &[]).unwrap(); pg } fn
() { env_logger::init().unwrap(); let mut opts = getopts::Options::new(); opts.reqopt("", "host", "irc server hostname", "HOSTNAME"); opts.optopt("", "port", "irc server port", "PORT"); opts.reqopt("n", "nick", "nickname", "NICK"); opts.optmulti("c", "chan", "channels to join", "CHAN"); let args: Vec<String> = env::args().collect(); let matches = opts.parse(&args[1..]).unwrap(); let host = matches.opt_str("host").expect("must provide --host"); let mut port = 6667; if matches.opt_present("port") { port = u16::from_str(&matches.opt_str("port").expect("must provide argument to --port")).unwrap(); } let addr = (host.as_ref(), port); let nick = matches.opt_str("nick").expect("must provide --nick"); let channels = matches.opt_strs("chan"); let choice_nick = nick.clone(); let choice_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&choice_nick)) { let choices: Vec<_> = regex!(r"\s+or\s+") .split(pm.msg) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if choices.len() > 1 { let mut rng = thread_rng(); if let Some(reply_to) = pm.reply_target(&choice_nick) { return Response::respond(protocol::Privmsg::new(reply_to, rng.choose(&choices).unwrap()).format()); } } } Response::nothing() }; let pg = Arc::new(Mutex::new(init_pg_tables())); // { // // TODO: Seed our knowledge // let mut knowledge = knowledge_mutex.lock().unwrap(); // knowledge.insert(format!("{}: info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // knowledge.insert(format!("{}, info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // } let learning_pg = pg.clone(); let learning_nick = nick.clone(); let learning_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&learning_nick)) { let assignment: Vec<_> = regex!(r"\s+is\s+") .splitn(pm.msg, 2) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if assignment.len() == 2 { let conn = learning_pg.lock().unwrap(); conn.execute(sql!("INSERT INTO knowledge (key, val) VALUES ($1, $2)"), &[&assignment[0], &assignment[1]]).unwrap(); } } Response::nothing() }; let info_pg = pg.clone(); let info_nick = nick.clone(); let info_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(reply_to) = pm.reply_target(&info_nick) { let mut rng = thread_rng(); let conn = info_pg.lock().unwrap(); let info_stmt = conn.prepare(sql!("SELECT val FROM knowledge WHERE key = $1")).unwrap(); if let Some(choice) = rand::sample(&mut rng, info_stmt.query(&[&pm.msg]).unwrap().into_iter().map(|r| { r.get::<_, String>(0) }), 1).get(0) { if let Some(c) = regex!(r"^<action>\s+(.*)$").captures(choice) { return Response::respond(protocol::Privmsg::new(reply_to, &protocol::ctcp_action(c.at(1).expect("Bad regex match"))).format()); } else { return Response::respond(protocol::Privmsg::new(reply_to, choice).format()); } } } } Response::nothing() }; let karma_pg = pg.clone(); let karma_nick = nick.clone(); let karma_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(c) = regex!(r"^([^-+\s]+)(\+\+|--)$").captures(pm.msg) { let n = c.at(1).expect("Bad match group"); let inc = c.at(2).expect("Bad match group") == "++"; let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT count(nick) FROM karma WHERE nick = $1")).unwrap(); let count: i64 = stmt.query(&[&n]).unwrap().into_iter().next().unwrap().get(0); let change = if inc { 1 } else { -1 }; if count == 0 { conn.execute(sql!("INSERT INTO karma (nick, karma) VALUES ($1, $2)"), &[&n, &change]).unwrap(); } else { conn.execute(sql!("UPDATE karma SET karma = karma + $2 WHERE nick = $1"), &[&n, &change]).unwrap(); } } else if let Some(c) = regex!(r"^karma\s+([^\s]+)$").captures(pm.msg) { if let Some(reply_to) = pm.reply_target(&karma_nick) { let n = c.at(1).expect("Bad match group"); let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT karma FROM karma WHERE nick = $1")).unwrap(); let k: i32 = stmt.query(&[&n]).unwrap() .into_iter().next().and_then(|r| r.get(0)).or(Some(0)).unwrap(); return Response::respond(protocol::Privmsg::new(reply_to, &format!("{}: {}", n, k)).format()) } } } Response::nothing() }; let join_nick = nick.clone(); let join_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&join_nick)) { if let Some(c) = regex!(r"^(join|part) (#[^\s]+)").captures(pm.msg) { let action = c.at(1).expect("Bad match group"); let chan = c.at(2).expect("Bad match group"); let success_msg = format!("{} channel {}!", if action == "join" { "Joined" } else { "Left" }, chan); if let Ok(joined_regex) = Regex::new(&format!(r"{}\s+:?{}", action.to_ascii_uppercase(), chan)) { let joined_handler = box move |joined_line: &str| { if joined_regex.is_match(joined_line) { info!("{}", success_msg); return Response(None, HandlerAction::Remove, Action::Skip); } Response::nothing() }; info!("{} channel {}...", if action == "join" { "Joining" } else { "Leaving" }, chan); return Response(Some(format!("{} {}", action.to_ascii_uppercase(), chan)), HandlerAction::Add(joined_handler), Action::Skip); } } } Response::nothing() }; let echo_nick = nick.clone(); let echo_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&echo_nick)) { if regex!(r"^[Hh]i$").is_match(pm.msg) { if let Some(reply_to) = pm.reply_target(&echo_nick) { if let Some(protocol::Source::User(ref user_info)) = pm.src { return Response::respond(protocol::Privmsg::new(reply_to, &format!("Hi, {}!", user_info.nick)).format()); } } } else if regex!(r"^go away$").is_match(pm.msg) { return Response(None, HandlerAction::Keep, Action::Stop); } } Response::nothing() }; let (mut client, join_handle) = irc::Client::connect( &addr, &nick, &channels.iter().map(|s| s.as_ref()).collect::<Vec<&str>>(), "leifw_rustbot", "leifw's rust robot") .ok().expect(&format!("Error connecting to {:?}.", addr)); client.add_handler(choice_handler); client.add_handler(learning_handler); client.add_handler(karma_handler); client.add_handler(info_handler); client.add_handler(join_handler); client.add_handler(echo_handler); join_handle.join().unwrap_or_else(|_| { error!("Unknown error!"); }); }
main
identifier_name
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::sync::{Arc, Mutex}; extern crate env_logger; extern crate getopts; extern crate irc; extern crate postgres; extern crate rand; extern crate regex; #[macro_use] extern crate log; fn init_pg_tables() -> Connection { let pg = Connection::connect("postgres://leif@localhost", &SslMode::None).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS knowledge ( key VARCHAR, val VARCHAR, PRIMARY KEY(key, val) )", &[]).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS karma ( nick VARCHAR PRIMARY KEY, karma INTEGER NOT NULL DEFAULT 0 )", &[]).unwrap(); pg } fn main() { env_logger::init().unwrap(); let mut opts = getopts::Options::new(); opts.reqopt("", "host", "irc server hostname", "HOSTNAME"); opts.optopt("", "port", "irc server port", "PORT"); opts.reqopt("n", "nick", "nickname", "NICK"); opts.optmulti("c", "chan", "channels to join", "CHAN"); let args: Vec<String> = env::args().collect(); let matches = opts.parse(&args[1..]).unwrap(); let host = matches.opt_str("host").expect("must provide --host"); let mut port = 6667; if matches.opt_present("port") { port = u16::from_str(&matches.opt_str("port").expect("must provide argument to --port")).unwrap(); } let addr = (host.as_ref(), port); let nick = matches.opt_str("nick").expect("must provide --nick"); let channels = matches.opt_strs("chan"); let choice_nick = nick.clone(); let choice_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&choice_nick)) { let choices: Vec<_> = regex!(r"\s+or\s+") .split(pm.msg) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if choices.len() > 1 { let mut rng = thread_rng(); if let Some(reply_to) = pm.reply_target(&choice_nick) { return Response::respond(protocol::Privmsg::new(reply_to, rng.choose(&choices).unwrap()).format()); } } } Response::nothing() }; let pg = Arc::new(Mutex::new(init_pg_tables())); // { // // TODO: Seed our knowledge // let mut knowledge = knowledge_mutex.lock().unwrap(); // knowledge.insert(format!("{}: info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // knowledge.insert(format!("{}, info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // } let learning_pg = pg.clone(); let learning_nick = nick.clone(); let learning_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&learning_nick)) { let assignment: Vec<_> = regex!(r"\s+is\s+") .splitn(pm.msg, 2) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if assignment.len() == 2 { let conn = learning_pg.lock().unwrap(); conn.execute(sql!("INSERT INTO knowledge (key, val) VALUES ($1, $2)"), &[&assignment[0], &assignment[1]]).unwrap(); } } Response::nothing() }; let info_pg = pg.clone(); let info_nick = nick.clone(); let info_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(reply_to) = pm.reply_target(&info_nick) { let mut rng = thread_rng(); let conn = info_pg.lock().unwrap(); let info_stmt = conn.prepare(sql!("SELECT val FROM knowledge WHERE key = $1")).unwrap(); if let Some(choice) = rand::sample(&mut rng, info_stmt.query(&[&pm.msg]).unwrap().into_iter().map(|r| { r.get::<_, String>(0) }), 1).get(0) { if let Some(c) = regex!(r"^<action>\s+(.*)$").captures(choice) { return Response::respond(protocol::Privmsg::new(reply_to, &protocol::ctcp_action(c.at(1).expect("Bad regex match"))).format()); } else { return Response::respond(protocol::Privmsg::new(reply_to, choice).format()); } } } } Response::nothing() }; let karma_pg = pg.clone(); let karma_nick = nick.clone(); let karma_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(c) = regex!(r"^([^-+\s]+)(\+\+|--)$").captures(pm.msg) { let n = c.at(1).expect("Bad match group"); let inc = c.at(2).expect("Bad match group") == "++"; let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT count(nick) FROM karma WHERE nick = $1")).unwrap(); let count: i64 = stmt.query(&[&n]).unwrap().into_iter().next().unwrap().get(0); let change = if inc { 1 } else
; if count == 0 { conn.execute(sql!("INSERT INTO karma (nick, karma) VALUES ($1, $2)"), &[&n, &change]).unwrap(); } else { conn.execute(sql!("UPDATE karma SET karma = karma + $2 WHERE nick = $1"), &[&n, &change]).unwrap(); } } else if let Some(c) = regex!(r"^karma\s+([^\s]+)$").captures(pm.msg) { if let Some(reply_to) = pm.reply_target(&karma_nick) { let n = c.at(1).expect("Bad match group"); let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT karma FROM karma WHERE nick = $1")).unwrap(); let k: i32 = stmt.query(&[&n]).unwrap() .into_iter().next().and_then(|r| r.get(0)).or(Some(0)).unwrap(); return Response::respond(protocol::Privmsg::new(reply_to, &format!("{}: {}", n, k)).format()) } } } Response::nothing() }; let join_nick = nick.clone(); let join_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&join_nick)) { if let Some(c) = regex!(r"^(join|part) (#[^\s]+)").captures(pm.msg) { let action = c.at(1).expect("Bad match group"); let chan = c.at(2).expect("Bad match group"); let success_msg = format!("{} channel {}!", if action == "join" { "Joined" } else { "Left" }, chan); if let Ok(joined_regex) = Regex::new(&format!(r"{}\s+:?{}", action.to_ascii_uppercase(), chan)) { let joined_handler = box move |joined_line: &str| { if joined_regex.is_match(joined_line) { info!("{}", success_msg); return Response(None, HandlerAction::Remove, Action::Skip); } Response::nothing() }; info!("{} channel {}...", if action == "join" { "Joining" } else { "Leaving" }, chan); return Response(Some(format!("{} {}", action.to_ascii_uppercase(), chan)), HandlerAction::Add(joined_handler), Action::Skip); } } } Response::nothing() }; let echo_nick = nick.clone(); let echo_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&echo_nick)) { if regex!(r"^[Hh]i$").is_match(pm.msg) { if let Some(reply_to) = pm.reply_target(&echo_nick) { if let Some(protocol::Source::User(ref user_info)) = pm.src { return Response::respond(protocol::Privmsg::new(reply_to, &format!("Hi, {}!", user_info.nick)).format()); } } } else if regex!(r"^go away$").is_match(pm.msg) { return Response(None, HandlerAction::Keep, Action::Stop); } } Response::nothing() }; let (mut client, join_handle) = irc::Client::connect( &addr, &nick, &channels.iter().map(|s| s.as_ref()).collect::<Vec<&str>>(), "leifw_rustbot", "leifw's rust robot") .ok().expect(&format!("Error connecting to {:?}.", addr)); client.add_handler(choice_handler); client.add_handler(learning_handler); client.add_handler(karma_handler); client.add_handler(info_handler); client.add_handler(join_handler); client.add_handler(echo_handler); join_handle.join().unwrap_or_else(|_| { error!("Unknown error!"); }); }
{ -1 }
conditional_block
hiphopabotamus.rs
#![feature(box_syntax)] #![feature(plugin)] #![plugin(postgres_macros,regex_macros)] use irc::event_stream::{Action, HandlerAction, Response}; use irc::protocol; use postgres::{Connection, SslMode}; use regex::Regex; use rand::{thread_rng, Rng}; use std::ascii::AsciiExt; use std::env; use std::str::FromStr; use std::sync::{Arc, Mutex}; extern crate env_logger; extern crate getopts; extern crate irc; extern crate postgres; extern crate rand; extern crate regex; #[macro_use] extern crate log; fn init_pg_tables() -> Connection { let pg = Connection::connect("postgres://leif@localhost", &SslMode::None).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS knowledge ( key VARCHAR, val VARCHAR, PRIMARY KEY(key, val) )", &[]).unwrap(); pg.execute("CREATE TABLE IF NOT EXISTS karma ( nick VARCHAR PRIMARY KEY, karma INTEGER NOT NULL DEFAULT 0 )", &[]).unwrap(); pg } fn main() { env_logger::init().unwrap(); let mut opts = getopts::Options::new(); opts.reqopt("", "host", "irc server hostname", "HOSTNAME"); opts.optopt("", "port", "irc server port", "PORT"); opts.reqopt("n", "nick", "nickname", "NICK"); opts.optmulti("c", "chan", "channels to join", "CHAN"); let args: Vec<String> = env::args().collect(); let matches = opts.parse(&args[1..]).unwrap(); let host = matches.opt_str("host").expect("must provide --host"); let mut port = 6667; if matches.opt_present("port") { port = u16::from_str(&matches.opt_str("port").expect("must provide argument to --port")).unwrap(); } let addr = (host.as_ref(), port); let nick = matches.opt_str("nick").expect("must provide --nick"); let channels = matches.opt_strs("chan"); let choice_nick = nick.clone(); let choice_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&choice_nick)) { let choices: Vec<_> = regex!(r"\s+or\s+") .split(pm.msg) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if choices.len() > 1 { let mut rng = thread_rng(); if let Some(reply_to) = pm.reply_target(&choice_nick) { return Response::respond(protocol::Privmsg::new(reply_to, rng.choose(&choices).unwrap()).format()); } } } Response::nothing() }; let pg = Arc::new(Mutex::new(init_pg_tables())); // { // // TODO: Seed our knowledge // let mut knowledge = knowledge_mutex.lock().unwrap(); // knowledge.insert(format!("{}: info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // knowledge.insert(format!("{}, info", nick), vec!["I'm a robot running https://github.com/leifwalsh/irc, feel free to contribute!".to_string()]); // } let learning_pg = pg.clone(); let learning_nick = nick.clone(); let learning_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&learning_nick)) { let assignment: Vec<_> = regex!(r"\s+is\s+") .splitn(pm.msg, 2) .map(|s| s.trim()) .filter(|s|!s.is_empty()) .collect(); if assignment.len() == 2 { let conn = learning_pg.lock().unwrap(); conn.execute(sql!("INSERT INTO knowledge (key, val) VALUES ($1, $2)"), &[&assignment[0], &assignment[1]]).unwrap(); } } Response::nothing() }; let info_pg = pg.clone(); let info_nick = nick.clone(); let info_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(reply_to) = pm.reply_target(&info_nick) { let mut rng = thread_rng(); let conn = info_pg.lock().unwrap(); let info_stmt = conn.prepare(sql!("SELECT val FROM knowledge WHERE key = $1")).unwrap(); if let Some(choice) = rand::sample(&mut rng, info_stmt.query(&[&pm.msg]).unwrap().into_iter().map(|r| { r.get::<_, String>(0) }), 1).get(0) { if let Some(c) = regex!(r"^<action>\s+(.*)$").captures(choice) { return Response::respond(protocol::Privmsg::new(reply_to, &protocol::ctcp_action(c.at(1).expect("Bad regex match"))).format()); } else { return Response::respond(protocol::Privmsg::new(reply_to, choice).format()); } } } } Response::nothing() }; let karma_pg = pg.clone(); let karma_nick = nick.clone(); let karma_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line) { if let Some(c) = regex!(r"^([^-+\s]+)(\+\+|--)$").captures(pm.msg) { let n = c.at(1).expect("Bad match group"); let inc = c.at(2).expect("Bad match group") == "++"; let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT count(nick) FROM karma WHERE nick = $1")).unwrap(); let count: i64 = stmt.query(&[&n]).unwrap().into_iter().next().unwrap().get(0); let change = if inc { 1 } else { -1 }; if count == 0 { conn.execute(sql!("INSERT INTO karma (nick, karma) VALUES ($1, $2)"), &[&n, &change]).unwrap(); } else { conn.execute(sql!("UPDATE karma SET karma = karma + $2 WHERE nick = $1"), &[&n, &change]).unwrap(); } } else if let Some(c) = regex!(r"^karma\s+([^\s]+)$").captures(pm.msg) { if let Some(reply_to) = pm.reply_target(&karma_nick) { let n = c.at(1).expect("Bad match group"); let conn = karma_pg.lock().unwrap(); let stmt = conn.prepare(sql!("SELECT karma FROM karma WHERE nick = $1")).unwrap(); let k: i32 = stmt.query(&[&n]).unwrap()
} } Response::nothing() }; let join_nick = nick.clone(); let join_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&join_nick)) { if let Some(c) = regex!(r"^(join|part) (#[^\s]+)").captures(pm.msg) { let action = c.at(1).expect("Bad match group"); let chan = c.at(2).expect("Bad match group"); let success_msg = format!("{} channel {}!", if action == "join" { "Joined" } else { "Left" }, chan); if let Ok(joined_regex) = Regex::new(&format!(r"{}\s+:?{}", action.to_ascii_uppercase(), chan)) { let joined_handler = box move |joined_line: &str| { if joined_regex.is_match(joined_line) { info!("{}", success_msg); return Response(None, HandlerAction::Remove, Action::Skip); } Response::nothing() }; info!("{} channel {}...", if action == "join" { "Joining" } else { "Leaving" }, chan); return Response(Some(format!("{} {}", action.to_ascii_uppercase(), chan)), HandlerAction::Add(joined_handler), Action::Skip); } } } Response::nothing() }; let echo_nick = nick.clone(); let echo_handler = box move |line: &str| { if let Some(pm) = protocol::Privmsg::parse(line).and_then(|pm| pm.targeted_msg(&echo_nick)) { if regex!(r"^[Hh]i$").is_match(pm.msg) { if let Some(reply_to) = pm.reply_target(&echo_nick) { if let Some(protocol::Source::User(ref user_info)) = pm.src { return Response::respond(protocol::Privmsg::new(reply_to, &format!("Hi, {}!", user_info.nick)).format()); } } } else if regex!(r"^go away$").is_match(pm.msg) { return Response(None, HandlerAction::Keep, Action::Stop); } } Response::nothing() }; let (mut client, join_handle) = irc::Client::connect( &addr, &nick, &channels.iter().map(|s| s.as_ref()).collect::<Vec<&str>>(), "leifw_rustbot", "leifw's rust robot") .ok().expect(&format!("Error connecting to {:?}.", addr)); client.add_handler(choice_handler); client.add_handler(learning_handler); client.add_handler(karma_handler); client.add_handler(info_handler); client.add_handler(join_handler); client.add_handler(echo_handler); join_handle.join().unwrap_or_else(|_| { error!("Unknown error!"); }); }
.into_iter().next().and_then(|r| r.get(0)).or(Some(0)).unwrap(); return Response::respond(protocol::Privmsg::new(reply_to, &format!("{}: {}", n, k)).format()) }
random_line_split
hello.rs
use std::ops::Add; fn main() { println!("hello, world"); println!("> Primitives"); primitives(); println!("> Tuples"); tuples(); println!("> Arrays"); arrays(); println!("> Structs"); structs(); println!("> References"); references(); println!("> Enums"); enums(); } fn primitives()
fn tuples() { fn reverse(pair: (i32, i32)) -> (i32, i32) { let (x, y) = pair; (y, x) } let pair = (3, 2); let reversed = reverse(pair); println!("reversed: ({}, {})", reversed.0, reversed.1); } fn arrays() { fn sum(slice: &[i32]) -> i32 { let mut total = 0; for i in 0..slice.len() { total += slice[i] } total } let x = [1, 2, 3]; println!("total: {}", sum(&x)); let y = [1, 2, 3, 4, 5]; println!("total: {}", sum(&y)); } fn structs() { // this is used to override move semantics. #[derive(Copy, Clone)] struct Point { x: i32, y: i32, } fn add(p1: Point, p2: Point) -> Point { Point { x: p1.x + p2.x, y: p1.y + p2.y, } } impl Add for Point { // operator overloading! type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } } } fn print_point(p: Point) { println!("({},{})", p.x, p.y); } let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 4, y: 5 }; let p3 = add(p1, p2); let p4 = p1 + p2; print_point(p3); print_point(p4); } fn references() { // testing mutable reference. let mut x: i32 = 5; println!("x: {}", x); fn increment(x: &mut i32) { *x = *x + 1; } increment(&mut x); println!("x: {}", x); // testing immutable references fn print_twice(x: &i32) { println!("first: {}", x); println!("second: {}", x); } print_twice(&3); print_twice(&x); /* this code does not compile - taking multiple mutable references. { let y = &mut x; let z = &mut x; } */ /* this code does not compile - taking mutable & immutable references (they form read-write-lock). { let y = & x; let z = &mut x; } */ } fn enums() { // standard enum. enum Color { RED, GREEN, BLACK, }; fn categorize_color(c: Color) { match c { Color::RED => println!("color is red!"), Color::GREEN => println!("color is green!"), _ => println!("Unknown color."), } } categorize_color(Color::RED); categorize_color(Color::GREEN); categorize_color(Color::BLACK); // pattern matching enum. enum Option { None, Some(i32), } fn app(o: Option, function: fn(i32) -> i32) -> Option { match o { Option::None => Option::None, Option::Some(x) => Option::Some(function(x)), } } fn add_one(x: i32) -> i32 { x + 1 } fn print_value(x: i32) -> i32 { println!("value: {}", x); return 0; } app(app(Option::Some(10), add_one), print_value); app(app(Option::None, add_one), print_value); }
{ // List of Rust primitive types // https://doc.rust-lang.org/book/primitive-types.html println!("1 + 2 = {}", 1 + 2); println!("1 - 2 = {}", 1 - 2); println!("true and true = {}", true && true); let x: char = 'x'; println!("x = {}", x); let y: f32 = 3.14; println!("y = {}", y); }
identifier_body
hello.rs
use std::ops::Add; fn main() { println!("hello, world"); println!("> Primitives"); primitives(); println!("> Tuples"); tuples(); println!("> Arrays"); arrays(); println!("> Structs"); structs(); println!("> References"); references(); println!("> Enums"); enums(); } fn primitives() { // List of Rust primitive types // https://doc.rust-lang.org/book/primitive-types.html println!("1 + 2 = {}", 1 + 2); println!("1 - 2 = {}", 1 - 2); println!("true and true = {}", true && true); let x: char = 'x'; println!("x = {}", x); let y: f32 = 3.14; println!("y = {}", y); } fn tuples() { fn reverse(pair: (i32, i32)) -> (i32, i32) { let (x, y) = pair; (y, x) } let pair = (3, 2); let reversed = reverse(pair); println!("reversed: ({}, {})", reversed.0, reversed.1); } fn arrays() { fn sum(slice: &[i32]) -> i32 { let mut total = 0; for i in 0..slice.len() { total += slice[i] } total } let x = [1, 2, 3]; println!("total: {}", sum(&x)); let y = [1, 2, 3, 4, 5]; println!("total: {}", sum(&y)); } fn structs() { // this is used to override move semantics. #[derive(Copy, Clone)] struct Point { x: i32, y: i32, } fn add(p1: Point, p2: Point) -> Point { Point { x: p1.x + p2.x, y: p1.y + p2.y, } } impl Add for Point { // operator overloading! type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } } } fn print_point(p: Point) { println!("({},{})", p.x, p.y); } let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 4, y: 5 }; let p3 = add(p1, p2); let p4 = p1 + p2; print_point(p3); print_point(p4); } fn references() { // testing mutable reference. let mut x: i32 = 5; println!("x: {}", x); fn increment(x: &mut i32) { *x = *x + 1; } increment(&mut x); println!("x: {}", x); // testing immutable references fn print_twice(x: &i32) { println!("first: {}", x); println!("second: {}", x); } print_twice(&3); print_twice(&x); /* this code does not compile - taking multiple mutable references. { let y = &mut x; let z = &mut x; } */ /* this code does not compile - taking mutable & immutable references (they form read-write-lock). { let y = & x; let z = &mut x; } */ } fn
() { // standard enum. enum Color { RED, GREEN, BLACK, }; fn categorize_color(c: Color) { match c { Color::RED => println!("color is red!"), Color::GREEN => println!("color is green!"), _ => println!("Unknown color."), } } categorize_color(Color::RED); categorize_color(Color::GREEN); categorize_color(Color::BLACK); // pattern matching enum. enum Option { None, Some(i32), } fn app(o: Option, function: fn(i32) -> i32) -> Option { match o { Option::None => Option::None, Option::Some(x) => Option::Some(function(x)), } } fn add_one(x: i32) -> i32 { x + 1 } fn print_value(x: i32) -> i32 { println!("value: {}", x); return 0; } app(app(Option::Some(10), add_one), print_value); app(app(Option::None, add_one), print_value); }
enums
identifier_name
hello.rs
use std::ops::Add; fn main() { println!("hello, world"); println!("> Primitives"); primitives(); println!("> Tuples"); tuples(); println!("> Arrays"); arrays(); println!("> Structs"); structs(); println!("> References"); references(); println!("> Enums"); enums(); } fn primitives() { // List of Rust primitive types // https://doc.rust-lang.org/book/primitive-types.html println!("1 + 2 = {}", 1 + 2); println!("1 - 2 = {}", 1 - 2); println!("true and true = {}", true && true); let x: char = 'x'; println!("x = {}", x); let y: f32 = 3.14; println!("y = {}", y); } fn tuples() { fn reverse(pair: (i32, i32)) -> (i32, i32) { let (x, y) = pair; (y, x) } let pair = (3, 2); let reversed = reverse(pair); println!("reversed: ({}, {})", reversed.0, reversed.1); } fn arrays() { fn sum(slice: &[i32]) -> i32 { let mut total = 0; for i in 0..slice.len() { total += slice[i] } total } let x = [1, 2, 3]; println!("total: {}", sum(&x)); let y = [1, 2, 3, 4, 5]; println!("total: {}", sum(&y)); } fn structs() { // this is used to override move semantics. #[derive(Copy, Clone)] struct Point { x: i32, y: i32, } fn add(p1: Point, p2: Point) -> Point { Point { x: p1.x + p2.x, y: p1.y + p2.y, } } impl Add for Point { // operator overloading! type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } } } fn print_point(p: Point) { println!("({},{})", p.x, p.y); } let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 4, y: 5 }; let p3 = add(p1, p2); let p4 = p1 + p2; print_point(p3); print_point(p4); } fn references() { // testing mutable reference. let mut x: i32 = 5; println!("x: {}", x); fn increment(x: &mut i32) { *x = *x + 1; } increment(&mut x); println!("x: {}", x); // testing immutable references fn print_twice(x: &i32) { println!("first: {}", x); println!("second: {}", x); } print_twice(&3); print_twice(&x); /* this code does not compile - taking multiple mutable references. { let y = &mut x; let z = &mut x; } */ /* this code does not compile - taking mutable & immutable references (they form read-write-lock). { let y = & x; let z = &mut x; } */ } fn enums() { // standard enum. enum Color { RED, GREEN, BLACK, }; fn categorize_color(c: Color) { match c { Color::RED => println!("color is red!"), Color::GREEN => println!("color is green!"), _ => println!("Unknown color."), } } categorize_color(Color::RED); categorize_color(Color::GREEN);
enum Option { None, Some(i32), } fn app(o: Option, function: fn(i32) -> i32) -> Option { match o { Option::None => Option::None, Option::Some(x) => Option::Some(function(x)), } } fn add_one(x: i32) -> i32 { x + 1 } fn print_value(x: i32) -> i32 { println!("value: {}", x); return 0; } app(app(Option::Some(10), add_one), print_value); app(app(Option::None, add_one), print_value); }
categorize_color(Color::BLACK); // pattern matching enum.
random_line_split
9_billion_names_of_god_the_integer.rs
// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer extern crate num; use std::cmp::min; use num::{BigUint, Zero, One}; pub struct Solver { // The `cache` is a private implementation detail, // it would be an improvement to throw away unused values // from the cache (to reduce memory for larger inputs) cache: Vec<Vec<BigUint>> } impl Solver { pub fn new() -> Solver { // Setup the cache with the initial row Solver { cache: vec![vec![One::one()]] } } // Returns a string representing a line pub fn row_string(&mut self, idx: usize) -> String { let r = self.cumulative(idx); (0..idx).map(|i| &r[i+1] - &r[i]) .map(|n| n.to_string()) .collect::<Vec<String>>() .join(", ") } // Convenience method to access the last column in a culmulated calculation pub fn row_sum(&mut self, idx: usize) -> &BigUint { // This can never fail as we always add zero or one, so it's never empty. self.cumulative(idx).last().unwrap() } fn cumulative(&mut self, idx: usize) -> &[BigUint]
} #[cfg(not(test))] fn main() { let mut solver = Solver::new(); println!("rows"); for n in 1..11 { println!("{}: {}", n, solver.row_string(n)); } println!("sums"); for &y in &[23, 123, 1234, 12345] { println!("{}: {}", y, solver.row_sum(y)); } } #[cfg(test)] mod test { use super::Solver; use num::BigUint; #[test] fn test_cumulative() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_sum(n), &expected.parse::<BigUint>().unwrap()); }; t(23, "1255"); t(123, "2552338241"); t(1234, "156978797223733228787865722354959930"); } #[test] fn test_row() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_string(n), expected); }; t(1, "1"); t(2, "1, 1"); t(3, "1, 1, 1"); t(4, "1, 2, 1, 1"); t(5, "1, 2, 2, 1, 1"); t(6, "1, 3, 3, 2, 1, 1"); } }
{ for l in self.cache.len()..idx + 1 { let mut r : Vec<BigUint> = vec![Zero::zero()]; for x in 1..l + 1 { let w = { let y = &r[x-1]; let z = &self.cache[l-x][min(x, l-x)]; y + z }; r.push(w) } self.cache.push(r); } &self.cache[idx][..] }
identifier_body
9_billion_names_of_god_the_integer.rs
// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer extern crate num; use std::cmp::min; use num::{BigUint, Zero, One}; pub struct Solver { // The `cache` is a private implementation detail, // it would be an improvement to throw away unused values // from the cache (to reduce memory for larger inputs) cache: Vec<Vec<BigUint>> } impl Solver { pub fn new() -> Solver { // Setup the cache with the initial row Solver { cache: vec![vec![One::one()]] } } // Returns a string representing a line pub fn row_string(&mut self, idx: usize) -> String { let r = self.cumulative(idx); (0..idx).map(|i| &r[i+1] - &r[i]) .map(|n| n.to_string()) .collect::<Vec<String>>() .join(", ") } // Convenience method to access the last column in a culmulated calculation pub fn row_sum(&mut self, idx: usize) -> &BigUint { // This can never fail as we always add zero or one, so it's never empty. self.cumulative(idx).last().unwrap() } fn cumulative(&mut self, idx: usize) -> &[BigUint] { for l in self.cache.len()..idx + 1 { let mut r : Vec<BigUint> = vec![Zero::zero()]; for x in 1..l + 1 { let w = { let y = &r[x-1]; let z = &self.cache[l-x][min(x, l-x)]; y + z }; r.push(w) } self.cache.push(r); } &self.cache[idx][..] } } #[cfg(not(test))] fn main() { let mut solver = Solver::new(); println!("rows"); for n in 1..11 { println!("{}: {}", n, solver.row_string(n)); } println!("sums"); for &y in &[23, 123, 1234, 12345] { println!("{}: {}", y, solver.row_sum(y)); } }
use num::BigUint; #[test] fn test_cumulative() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_sum(n), &expected.parse::<BigUint>().unwrap()); }; t(23, "1255"); t(123, "2552338241"); t(1234, "156978797223733228787865722354959930"); } #[test] fn test_row() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_string(n), expected); }; t(1, "1"); t(2, "1, 1"); t(3, "1, 1, 1"); t(4, "1, 2, 1, 1"); t(5, "1, 2, 2, 1, 1"); t(6, "1, 3, 3, 2, 1, 1"); } }
#[cfg(test)] mod test { use super::Solver;
random_line_split
9_billion_names_of_god_the_integer.rs
// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer extern crate num; use std::cmp::min; use num::{BigUint, Zero, One}; pub struct Solver { // The `cache` is a private implementation detail, // it would be an improvement to throw away unused values // from the cache (to reduce memory for larger inputs) cache: Vec<Vec<BigUint>> } impl Solver { pub fn new() -> Solver { // Setup the cache with the initial row Solver { cache: vec![vec![One::one()]] } } // Returns a string representing a line pub fn row_string(&mut self, idx: usize) -> String { let r = self.cumulative(idx); (0..idx).map(|i| &r[i+1] - &r[i]) .map(|n| n.to_string()) .collect::<Vec<String>>() .join(", ") } // Convenience method to access the last column in a culmulated calculation pub fn row_sum(&mut self, idx: usize) -> &BigUint { // This can never fail as we always add zero or one, so it's never empty. self.cumulative(idx).last().unwrap() } fn
(&mut self, idx: usize) -> &[BigUint] { for l in self.cache.len()..idx + 1 { let mut r : Vec<BigUint> = vec![Zero::zero()]; for x in 1..l + 1 { let w = { let y = &r[x-1]; let z = &self.cache[l-x][min(x, l-x)]; y + z }; r.push(w) } self.cache.push(r); } &self.cache[idx][..] } } #[cfg(not(test))] fn main() { let mut solver = Solver::new(); println!("rows"); for n in 1..11 { println!("{}: {}", n, solver.row_string(n)); } println!("sums"); for &y in &[23, 123, 1234, 12345] { println!("{}: {}", y, solver.row_sum(y)); } } #[cfg(test)] mod test { use super::Solver; use num::BigUint; #[test] fn test_cumulative() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_sum(n), &expected.parse::<BigUint>().unwrap()); }; t(23, "1255"); t(123, "2552338241"); t(1234, "156978797223733228787865722354959930"); } #[test] fn test_row() { let mut solver = Solver::new(); let mut t = |n: usize, expected: &str| { assert_eq!(solver.row_string(n), expected); }; t(1, "1"); t(2, "1, 1"); t(3, "1, 1, 1"); t(4, "1, 2, 1, 1"); t(5, "1, 2, 2, 1, 1"); t(6, "1, 3, 3, 2, 1, 1"); } }
cumulative
identifier_name
linked_list.rs
use List::*; enum List { // Cons: 元组结构体,包含一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), // Nil: 末结点,表明链表结束 Nil, } impl List { // 创建一个空链表 fn new() -> List { Nil } // 向头部节点前一个位置追加元素 fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // 返回链表的长度 fn len(&self) -> u32 { // `self` 必须匹配,因为这个方法的行为取决于 `self` 的变化类型 // `self` 为 `&List` 类型,`*self` 为 `List` 类型,一个具体的 `T` 类型的匹配 // 要参考引用 `&T` 的匹配 match *self { // 不能得到 tail 的所有权,因为 `self` 是借用的; // 而是得到一个 tail 引用 Cons(_, ref tail) => 1 + tail.len(), // 基本情形:空列表的长度为 0 Nil => 0, } } // 将列表以字符串(堆分配的)的形式返回 fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { // `format!` 和 `print!` 类似,但返回的是一个堆分配的字符串,而不是 // 打印结果到控制台上 format!("{}, {}", head, tail.stringify()) } Nil => format!("Nil"), } } } fn main() { let mut list = List::new(); list = list.prepend(1); list = list.prepend(2); list = list.prepend(3); // 显示链表的最后状态 println!("linked list has length: {}", list.len()); println!("{}", list.stringify()); }
identifier_body
linked_list.rs
use List::*; enum List { // Cons: 元组结构体,包含一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), // Nil: 末结点,表明链表结束 Nil, } impl List { // 创建一个空链表 fn new() -> List { Nil } // 向头部节点前一个位置追加元素 fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // 返回链表的长度 fn len(&self) -> u32 { // `self` 必须匹配,因为这个方法的行为取决于 `self` 的变化类型 // `self` 为 `&List` 类型,`*self` 为 `List` 类型,一个具体的 `T` 类型的匹配 // 要参考引用 `&T` 的匹配 match *self { // 不能得到 tail 的所有权,因为 `self` 是借用的; // 而是得到一个 tail 引用 Cons(_, ref tail) => 1 + tail.len(), // 基本情形:空列表的长度为 0 Nil => 0, } } // 将列表以字符串(堆分配的)的形式返回 fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { // `format!` 和 `print!` 类似,但返回的是一个堆分配的字符串,而不是 // 打印结果到控制台上 format!("{}, {}", head, tail.stringify()) } Nil => format!("Nil"), } } } fn main() { let mut list = List::new(); list = list.prepend(1); list = list.prepend(2); list = list.prepend(3); // 显示链表的最后状态
println!("{}", list.stringify()); }
println!("linked list has length: {}", list.len());
random_line_split
linked_list.rs
use List::*; enum List { // Cons: 元组结构体,包含一个元素和一个指向下一节点的指针 Cons(u32, Box<List>), // Nil: 末结点,表明链表结束 Nil, } impl List { // 创建一个空链表 fn new() -> List { Nil } // 向头部节点前一个位置追加元素 fn prepend(self, elem: u32) -> List { Cons(elem, Box::new(self)) } // 返回链表的长度 fn len(&self) -> u
// `self` 必须匹配,因为这个方法的行为取决于 `self` 的变化类型 // `self` 为 `&List` 类型,`*self` 为 `List` 类型,一个具体的 `T` 类型的匹配 // 要参考引用 `&T` 的匹配 match *self { // 不能得到 tail 的所有权,因为 `self` 是借用的; // 而是得到一个 tail 引用 Cons(_, ref tail) => 1 + tail.len(), // 基本情形:空列表的长度为 0 Nil => 0, } } // 将列表以字符串(堆分配的)的形式返回 fn stringify(&self) -> String { match *self { Cons(head, ref tail) => { // `format!` 和 `print!` 类似,但返回的是一个堆分配的字符串,而不是 // 打印结果到控制台上 format!("{}, {}", head, tail.stringify()) } Nil => format!("Nil"), } } } fn main() { let mut list = List::new(); list = list.prepend(1); list = list.prepend(2); list = list.prepend(3); // 显示链表的最后状态 println!("linked list has length: {}", list.len()); println!("{}", list.stringify()); }
32 {
identifier_name
pool.rs
//! Client Connection Pooling use std::borrow::ToOwned; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. pub struct Pool<C: NetworkConnector> { connector: C, inner: Arc<Mutex<PoolImpl<<C as NetworkConnector>::Stream>>> } /// Config options for the `Pool`. #[derive(Debug)] pub struct Config { /// The maximum idle connections *per host*. pub max_idle: usize, } impl Default for Config { #[inline] fn default() -> Config { Config { max_idle: 5, } } } #[derive(Debug)] struct PoolImpl<S> { conns: HashMap<Key, Vec<S>>, config: Config, } type Key = (String, u16, Scheme); fn key<T: Into<Scheme>>(host: &str, port: u16, scheme: T) -> Key { (host.to_owned(), port, scheme.into()) } #[derive(Clone, PartialEq, Eq, Debug, Hash)] enum Scheme { Http, Https, Other(String) } impl<'a> From<&'a str> for Scheme { fn from(s: &'a str) -> Scheme { match s { "http" => Scheme::Http, "https" => Scheme::Https, s => Scheme::Other(String::from(s)) } } } impl Pool<HttpConnector> { /// Creates a `Pool` with an `HttpConnector`. #[inline] pub fn new(config: Config) -> Pool<HttpConnector> { Pool::with_connector(config, HttpConnector(None)) } } impl<C: NetworkConnector> Pool<C> { /// Creates a `Pool` with a specified `NetworkConnector`. #[inline] pub fn with_connector(config: Config, connector: C) -> Pool<C> { Pool { connector: connector, inner: Arc::new(Mutex::new(PoolImpl { conns: HashMap::new(), config: config, })) } } /// Clear all idle connections from the Pool, closing them. #[inline] pub fn clear_idle(&mut self) { self.inner.lock().unwrap().conns.clear(); } } impl<S> PoolImpl<S> { fn reuse(&mut self, key: Key, conn: S) { trace!("reuse {:?}", key); let conns = self.conns.entry(key).or_insert(vec![]); if conns.len() < self.config.max_idle { conns.push(conn); } } } impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector for Pool<C> { type Stream = PooledStream<S>; fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<PooledStream<S>> { let key = key(host, port, scheme); let mut locked = self.inner.lock().unwrap(); let mut should_remove = false; let conn = match locked.conns.get_mut(&key) { Some(ref mut vec) => { trace!("Pool had connection, using"); should_remove = vec.len() == 1; vec.pop().unwrap() } _ => try!(self.connector.connect(host, port, scheme)) }; if should_remove { locked.conns.remove(&key); } Ok(PooledStream { inner: Some((key, conn)), is_closed: false, is_drained: false, pool: self.inner.clone() }) } #[inline] fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { self.connector.set_ssl_verifier(verifier); } } /// A Stream that will try to be returned to the Pool when dropped. pub struct
<S> { inner: Option<(Key, S)>, is_closed: bool, is_drained: bool, pool: Arc<Mutex<PoolImpl<S>>> } impl<S: NetworkStream> Read for PooledStream<S> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.inner.as_mut().unwrap().1.read(buf) { Ok(0) => { self.is_drained = true; Ok(0) } r => r } } } impl<S: NetworkStream> Write for PooledStream<S> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.inner.as_mut().unwrap().1.write(buf) } #[inline] fn flush(&mut self) -> io::Result<()> { self.inner.as_mut().unwrap().1.flush() } } impl<S: NetworkStream> NetworkStream for PooledStream<S> { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.inner.as_mut().unwrap().1.peer_addr() } #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { self.is_closed = true; self.inner.as_mut().unwrap().1.close(how) } } impl<S> Drop for PooledStream<S> { fn drop(&mut self) { trace!("PooledStream.drop, is_closed={}, is_drained={}", self.is_closed, self.is_drained); if!self.is_closed && self.is_drained { self.inner.take().map(|(key, conn)| { if let Ok(mut pool) = self.pool.lock() { pool.reuse(key, conn); } // else poisoned, give up }); } } } #[cfg(test)] mod tests { use std::net::Shutdown; use mock::{MockConnector, ChannelMockConnector}; use net::{NetworkConnector, NetworkStream}; use std::sync::mpsc; use super::{Pool, key}; macro_rules! mocked { () => ({ Pool::with_connector(Default::default(), MockConnector) }) } #[test] fn test_connect_and_drop() { let pool = mocked!(); let key = key("127.0.0.1", 3000, "http"); pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; //reused { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } } #[test] fn test_closed() { let pool = mocked!(); let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); stream.close(Shutdown::Both).unwrap(); drop(stream); let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 0); } /// Tests that the `Pool::set_ssl_verifier` method sets the SSL verifier of /// the underlying `Connector` instance that it uses. #[test] fn test_set_ssl_verifier_delegates_to_connector() { let (tx, rx) = mpsc::channel(); let mut pool = Pool::with_connector( Default::default(), ChannelMockConnector::new(tx)); pool.set_ssl_verifier(Box::new(|_| { })); match rx.try_recv() { Ok(meth) => assert_eq!(meth, "set_ssl_verifier"), _ => panic!("Expected a call to `set_ssl_verifier`"), }; } }
PooledStream
identifier_name
pool.rs
//! Client Connection Pooling use std::borrow::ToOwned; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. pub struct Pool<C: NetworkConnector> { connector: C, inner: Arc<Mutex<PoolImpl<<C as NetworkConnector>::Stream>>> } /// Config options for the `Pool`. #[derive(Debug)] pub struct Config { /// The maximum idle connections *per host*. pub max_idle: usize, } impl Default for Config { #[inline] fn default() -> Config { Config { max_idle: 5, } } } #[derive(Debug)] struct PoolImpl<S> { conns: HashMap<Key, Vec<S>>, config: Config, } type Key = (String, u16, Scheme); fn key<T: Into<Scheme>>(host: &str, port: u16, scheme: T) -> Key { (host.to_owned(), port, scheme.into()) } #[derive(Clone, PartialEq, Eq, Debug, Hash)] enum Scheme { Http, Https, Other(String) } impl<'a> From<&'a str> for Scheme { fn from(s: &'a str) -> Scheme { match s { "http" => Scheme::Http, "https" => Scheme::Https, s => Scheme::Other(String::from(s)) } } } impl Pool<HttpConnector> { /// Creates a `Pool` with an `HttpConnector`. #[inline] pub fn new(config: Config) -> Pool<HttpConnector> { Pool::with_connector(config, HttpConnector(None)) } } impl<C: NetworkConnector> Pool<C> { /// Creates a `Pool` with a specified `NetworkConnector`. #[inline] pub fn with_connector(config: Config, connector: C) -> Pool<C> { Pool { connector: connector, inner: Arc::new(Mutex::new(PoolImpl { conns: HashMap::new(), config: config, })) } } /// Clear all idle connections from the Pool, closing them. #[inline] pub fn clear_idle(&mut self) { self.inner.lock().unwrap().conns.clear(); } } impl<S> PoolImpl<S> { fn reuse(&mut self, key: Key, conn: S) { trace!("reuse {:?}", key); let conns = self.conns.entry(key).or_insert(vec![]); if conns.len() < self.config.max_idle { conns.push(conn); } } } impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector for Pool<C> { type Stream = PooledStream<S>; fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<PooledStream<S>> { let key = key(host, port, scheme); let mut locked = self.inner.lock().unwrap(); let mut should_remove = false; let conn = match locked.conns.get_mut(&key) { Some(ref mut vec) => { trace!("Pool had connection, using"); should_remove = vec.len() == 1; vec.pop().unwrap() } _ => try!(self.connector.connect(host, port, scheme)) }; if should_remove { locked.conns.remove(&key); } Ok(PooledStream { inner: Some((key, conn)), is_closed: false, is_drained: false, pool: self.inner.clone() }) } #[inline] fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { self.connector.set_ssl_verifier(verifier); } } /// A Stream that will try to be returned to the Pool when dropped. pub struct PooledStream<S> { inner: Option<(Key, S)>, is_closed: bool, is_drained: bool, pool: Arc<Mutex<PoolImpl<S>>> } impl<S: NetworkStream> Read for PooledStream<S> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.inner.as_mut().unwrap().1.read(buf) { Ok(0) => { self.is_drained = true; Ok(0) } r => r } } } impl<S: NetworkStream> Write for PooledStream<S> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.inner.as_mut().unwrap().1.write(buf) } #[inline] fn flush(&mut self) -> io::Result<()> { self.inner.as_mut().unwrap().1.flush() } } impl<S: NetworkStream> NetworkStream for PooledStream<S> { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.inner.as_mut().unwrap().1.peer_addr() } #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { self.is_closed = true; self.inner.as_mut().unwrap().1.close(how) } } impl<S> Drop for PooledStream<S> { fn drop(&mut self) { trace!("PooledStream.drop, is_closed={}, is_drained={}", self.is_closed, self.is_drained); if!self.is_closed && self.is_drained { self.inner.take().map(|(key, conn)| { if let Ok(mut pool) = self.pool.lock() { pool.reuse(key, conn); } // else poisoned, give up }); } } } #[cfg(test)] mod tests { use std::net::Shutdown; use mock::{MockConnector, ChannelMockConnector}; use net::{NetworkConnector, NetworkStream}; use std::sync::mpsc; use super::{Pool, key}; macro_rules! mocked { () => ({ Pool::with_connector(Default::default(), MockConnector) }) } #[test] fn test_connect_and_drop() { let pool = mocked!(); let key = key("127.0.0.1", 3000, "http");
pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; //reused { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } } #[test] fn test_closed() { let pool = mocked!(); let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); stream.close(Shutdown::Both).unwrap(); drop(stream); let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 0); } /// Tests that the `Pool::set_ssl_verifier` method sets the SSL verifier of /// the underlying `Connector` instance that it uses. #[test] fn test_set_ssl_verifier_delegates_to_connector() { let (tx, rx) = mpsc::channel(); let mut pool = Pool::with_connector( Default::default(), ChannelMockConnector::new(tx)); pool.set_ssl_verifier(Box::new(|_| { })); match rx.try_recv() { Ok(meth) => assert_eq!(meth, "set_ssl_verifier"), _ => panic!("Expected a call to `set_ssl_verifier`"), }; } }
random_line_split
pool.rs
//! Client Connection Pooling use std::borrow::ToOwned; use std::collections::HashMap; use std::io::{self, Read, Write}; use std::net::{SocketAddr, Shutdown}; use std::sync::{Arc, Mutex}; use net::{NetworkConnector, NetworkStream, HttpConnector, ContextVerifier}; /// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. pub struct Pool<C: NetworkConnector> { connector: C, inner: Arc<Mutex<PoolImpl<<C as NetworkConnector>::Stream>>> } /// Config options for the `Pool`. #[derive(Debug)] pub struct Config { /// The maximum idle connections *per host*. pub max_idle: usize, } impl Default for Config { #[inline] fn default() -> Config { Config { max_idle: 5, } } } #[derive(Debug)] struct PoolImpl<S> { conns: HashMap<Key, Vec<S>>, config: Config, } type Key = (String, u16, Scheme); fn key<T: Into<Scheme>>(host: &str, port: u16, scheme: T) -> Key { (host.to_owned(), port, scheme.into()) } #[derive(Clone, PartialEq, Eq, Debug, Hash)] enum Scheme { Http, Https, Other(String) } impl<'a> From<&'a str> for Scheme { fn from(s: &'a str) -> Scheme { match s { "http" => Scheme::Http, "https" => Scheme::Https, s => Scheme::Other(String::from(s)) } } } impl Pool<HttpConnector> { /// Creates a `Pool` with an `HttpConnector`. #[inline] pub fn new(config: Config) -> Pool<HttpConnector> { Pool::with_connector(config, HttpConnector(None)) } } impl<C: NetworkConnector> Pool<C> { /// Creates a `Pool` with a specified `NetworkConnector`. #[inline] pub fn with_connector(config: Config, connector: C) -> Pool<C> { Pool { connector: connector, inner: Arc::new(Mutex::new(PoolImpl { conns: HashMap::new(), config: config, })) } } /// Clear all idle connections from the Pool, closing them. #[inline] pub fn clear_idle(&mut self) { self.inner.lock().unwrap().conns.clear(); } } impl<S> PoolImpl<S> { fn reuse(&mut self, key: Key, conn: S) { trace!("reuse {:?}", key); let conns = self.conns.entry(key).or_insert(vec![]); if conns.len() < self.config.max_idle { conns.push(conn); } } } impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector for Pool<C> { type Stream = PooledStream<S>; fn connect(&self, host: &str, port: u16, scheme: &str) -> ::Result<PooledStream<S>> { let key = key(host, port, scheme); let mut locked = self.inner.lock().unwrap(); let mut should_remove = false; let conn = match locked.conns.get_mut(&key) { Some(ref mut vec) => { trace!("Pool had connection, using"); should_remove = vec.len() == 1; vec.pop().unwrap() } _ => try!(self.connector.connect(host, port, scheme)) }; if should_remove { locked.conns.remove(&key); } Ok(PooledStream { inner: Some((key, conn)), is_closed: false, is_drained: false, pool: self.inner.clone() }) } #[inline] fn set_ssl_verifier(&mut self, verifier: ContextVerifier) { self.connector.set_ssl_verifier(verifier); } } /// A Stream that will try to be returned to the Pool when dropped. pub struct PooledStream<S> { inner: Option<(Key, S)>, is_closed: bool, is_drained: bool, pool: Arc<Mutex<PoolImpl<S>>> } impl<S: NetworkStream> Read for PooledStream<S> { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.inner.as_mut().unwrap().1.read(buf) { Ok(0) => { self.is_drained = true; Ok(0) } r => r } } } impl<S: NetworkStream> Write for PooledStream<S> { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.inner.as_mut().unwrap().1.write(buf) } #[inline] fn flush(&mut self) -> io::Result<()>
} impl<S: NetworkStream> NetworkStream for PooledStream<S> { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.inner.as_mut().unwrap().1.peer_addr() } #[inline] fn close(&mut self, how: Shutdown) -> io::Result<()> { self.is_closed = true; self.inner.as_mut().unwrap().1.close(how) } } impl<S> Drop for PooledStream<S> { fn drop(&mut self) { trace!("PooledStream.drop, is_closed={}, is_drained={}", self.is_closed, self.is_drained); if!self.is_closed && self.is_drained { self.inner.take().map(|(key, conn)| { if let Ok(mut pool) = self.pool.lock() { pool.reuse(key, conn); } // else poisoned, give up }); } } } #[cfg(test)] mod tests { use std::net::Shutdown; use mock::{MockConnector, ChannelMockConnector}; use net::{NetworkConnector, NetworkStream}; use std::sync::mpsc; use super::{Pool, key}; macro_rules! mocked { () => ({ Pool::with_connector(Default::default(), MockConnector) }) } #[test] fn test_connect_and_drop() { let pool = mocked!(); let key = key("127.0.0.1", 3000, "http"); pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; //reused { let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 1); assert_eq!(locked.conns.get(&key).unwrap().len(), 1); } } #[test] fn test_closed() { let pool = mocked!(); let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); stream.close(Shutdown::Both).unwrap(); drop(stream); let locked = pool.inner.lock().unwrap(); assert_eq!(locked.conns.len(), 0); } /// Tests that the `Pool::set_ssl_verifier` method sets the SSL verifier of /// the underlying `Connector` instance that it uses. #[test] fn test_set_ssl_verifier_delegates_to_connector() { let (tx, rx) = mpsc::channel(); let mut pool = Pool::with_connector( Default::default(), ChannelMockConnector::new(tx)); pool.set_ssl_verifier(Box::new(|_| { })); match rx.try_recv() { Ok(meth) => assert_eq!(meth, "set_ssl_verifier"), _ => panic!("Expected a call to `set_ssl_verifier`"), }; } }
{ self.inner.as_mut().unwrap().1.flush() }
identifier_body
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![feature(zero_one)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use acpi::Acpi; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::interrupt::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// ACPI pub mod acpi; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Disk drivers pub mod disk; /// Various drivers pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Filesystems pub mod fs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop() { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; for i in env().contexts.lock().iter().skip(1) { if i.interrupted { halt = false; break; } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } }
} else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } static BSS_TEST_ZERO: usize = 0; static BSS_TEST_NONZERO: usize = usize::MAX; /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { // Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr = &mut __bss_start; let end_ptr = &mut __bss_end; if start_ptr as *const _ as usize <= end_ptr as *const _ as usize { let size = end_ptr as *const _ as usize - start_ptr as *const _ as usize; memset(start_ptr, 0, size); } assert_eq!(BSS_TEST_ZERO, 0); assert_eq!(BSS_TEST_NONZERO, usize::MAX); } // Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); if let Some(acpi) = Acpi::new() { env.schemes.push(UnsafeCell::new(acpi)); } *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci::pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box InterruptScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); let _ = resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } //Do not catch init interrupt if interrupt < 0xFF { env().interrupts.lock()[interrupt as usize] += 1; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } i @ 0x21... 0x2F => env().on_irq(i as u8 - 0x20), 0x80 => if!syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0x9 => exception!("Coprocessor Segment Overrun"), // legacy 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"), 0xC => exception_error!("Stack-segment fault"), 0xD => exception_error!("General protection fault"), 0xE => exception_error!("Page fault"), 0x10 => exception!("x87 floating-point exception"), 0x11 => exception_error!("Alignment check exception"), 0x12 => exception!("Machine check exception"), 0x13 => exception!("
} _ => (), }
random_line_split
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![feature(zero_one)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use acpi::Acpi; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::interrupt::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// ACPI pub mod acpi; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Disk drivers pub mod disk; /// Various drivers pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Filesystems pub mod fs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop() { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; for i in env().contexts.lock().iter().skip(1) { if i.interrupted { halt = false; break; } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } static BSS_TEST_ZERO: usize = 0; static BSS_TEST_NONZERO: usize = usize::MAX; /// Initialize kernel unsafe fn
(font_data: usize, tss_data: usize) { // Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr = &mut __bss_start; let end_ptr = &mut __bss_end; if start_ptr as *const _ as usize <= end_ptr as *const _ as usize { let size = end_ptr as *const _ as usize - start_ptr as *const _ as usize; memset(start_ptr, 0, size); } assert_eq!(BSS_TEST_ZERO, 0); assert_eq!(BSS_TEST_NONZERO, usize::MAX); } // Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); if let Some(acpi) = Acpi::new() { env.schemes.push(UnsafeCell::new(acpi)); } *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci::pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box InterruptScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); let _ = resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } //Do not catch init interrupt if interrupt < 0xFF { env().interrupts.lock()[interrupt as usize] += 1; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } i @ 0x21... 0x2F => env().on_irq(i as u8 - 0x20), 0x80 => if!syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0x9 => exception!("Coprocessor Segment Overrun"), // legacy 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"), 0xC => exception_error!("Stack-segment fault"), 0xD => exception_error!("General protection fault"), 0xE => exception_error!("Page fault"), 0x10 => exception!("x87 floating-point exception"), 0x11 => exception_error!("Alignment check exception"), 0x12 => exception!("Machine check exception"), 0x13 =>
init
identifier_name
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![feature(zero_one)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use acpi::Acpi; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::interrupt::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// ACPI pub mod acpi; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Disk drivers pub mod disk; /// Various drivers pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Filesystems pub mod fs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop()
context_switch(false); } } /// Event poll loop fn poll_loop() { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw { console.redraw = false; console.display.flip(); } } unsafe { context_switch(false) }; } } static BSS_TEST_ZERO: usize = 0; static BSS_TEST_NONZERO: usize = usize::MAX; /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { // Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr = &mut __bss_start; let end_ptr = &mut __bss_end; if start_ptr as *const _ as usize <= end_ptr as *const _ as usize { let size = end_ptr as *const _ as usize - start_ptr as *const _ as usize; memset(start_ptr, 0, size); } assert_eq!(BSS_TEST_ZERO, 0); assert_eq!(BSS_TEST_NONZERO, usize::MAX); } // Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); if let Some(acpi) = Acpi::new() { env.schemes.push(UnsafeCell::new(acpi)); } *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci::pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box InterruptScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); let _ = resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } //Do not catch init interrupt if interrupt < 0xFF { env().interrupts.lock()[interrupt as usize] += 1; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } i @ 0x21... 0x2F => env().on_irq(i as u8 - 0x20), 0x80 => if!syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0x9 => exception!("Coprocessor Segment Overrun"), // legacy 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"), 0xC => exception_error!("Stack-segment fault"), 0xD => exception_error!("General protection fault"), 0xE => exception_error!("Page fault"), 0x10 => exception!("x87 floating-point exception"), 0x11 => exception_error!("Alignment check exception"), 0x12 => exception!("Machine check exception"), 0x13 =>
{ loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; for i in env().contexts.lock().iter().skip(1) { if i.interrupted { halt = false; break; } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); }
identifier_body
main.rs
#![feature(augmented_assignments)] #![feature(asm)] #![feature(box_syntax)] #![feature(collections)] #![feature(const_fn)] #![feature(core_intrinsics)] #![feature(core_str_ext)] #![feature(core_slice_ext)] #![feature(fnbox)] #![feature(fundamental)] #![feature(lang_items)] #![feature(op_assign_traits)] #![feature(unboxed_closures)] #![feature(unsafe_no_drop_flag)] #![feature(unwind_attributes)] #![feature(vec_push_all)] #![feature(zero_one)] #![no_std] #[macro_use] extern crate alloc; #[macro_use] extern crate collections; use acpi::Acpi; use alloc::boxed::Box; use collections::string::{String, ToString}; use collections::vec::Vec; use core::cell::UnsafeCell; use core::{ptr, mem, usize}; use core::slice::SliceExt; use common::event::{self, EVENT_KEY, EventOption}; use common::memory; use common::paging::Page; use common::time::Duration; use drivers::pci; use drivers::pio::*; use drivers::ps2::*; use drivers::rtc::*; use drivers::serial::*; use env::Environment; pub use externs::*; use graphics::display; use programs::executor::execute; use programs::scheme::*; use scheduler::{Context, Regs, TSS}; use scheduler::context::context_switch; use schemes::Url; use schemes::arp::*; use schemes::context::*; use schemes::debug::*; use schemes::ethernet::*; use schemes::icmp::*; use schemes::interrupt::*; use schemes::ip::*; use schemes::memory::*; // use schemes::display::*; use syscall::handle::*; /// Common std-like functionality #[macro_use] pub mod common; /// ACPI pub mod acpi; /// Allocation pub mod alloc_system; /// Audio pub mod audio; /// Disk drivers pub mod disk; /// Various drivers pub mod drivers; /// Environment pub mod env; /// Externs pub mod externs; /// Filesystems pub mod fs; /// Various graphical methods pub mod graphics; /// Network pub mod network; /// Panic pub mod panic; /// Programs pub mod programs; /// Schemes pub mod schemes; /// Scheduling pub mod scheduler; /// Sync primatives pub mod sync; /// System calls pub mod syscall; /// USB input/output pub mod usb; pub static mut TSS_PTR: Option<&'static mut TSS> = None; pub static mut ENV_PTR: Option<&'static mut Environment> = None; pub fn env() -> &'static Environment { unsafe { match ENV_PTR { Some(&mut ref p) => p, None => unreachable!(), } } } /// Pit duration static PIT_DURATION: Duration = Duration { secs: 0, nanos: 2250286, }; /// Idle loop (active while idle) unsafe fn idle_loop() { loop { asm!("cli" : : : : "intel", "volatile"); let mut halt = true; for i in env().contexts.lock().iter().skip(1) { if i.interrupted { halt = false; break; } } if halt { asm!("sti" : : : : "intel", "volatile"); asm!("hlt" : : : : "intel", "volatile"); } else { asm!("sti" : : : : "intel", "volatile"); } context_switch(false); } } /// Event poll loop fn poll_loop() { loop { env().on_poll(); unsafe { context_switch(false) }; } } /// Event loop fn event_loop() { { let mut console = env().console.lock(); console.instant = false; } let mut cmd = String::new(); loop { loop { let mut console = env().console.lock(); match env().events.lock().pop_front() { Some(event) => { if console.draw { match event.to_option() { EventOption::Key(key_event) => { if key_event.pressed { match key_event.scancode { event::K_F2 => { console.draw = false; } event::K_BKSP => if!cmd.is_empty() { console.write(&[8]); cmd.pop(); }, _ => match key_event.character { '\0' => (), '\n' => { console.command = Some(cmd.clone()); cmd.clear(); console.write(&[10]); } _ => { cmd.push(key_event.character); console.write(&[key_event.character as u8]); } }, } } } _ => (), } } else { if event.code == EVENT_KEY && event.b as u8 == event::K_F1 && event.c > 0 { console.draw = true; console.redraw = true; } else { // TODO: Magical orbital hack unsafe { for scheme in env().schemes.iter() { if (*scheme.get()).scheme() == "orbital" { (*scheme.get()).event(&event); break; } } } } } } None => break, } } { let mut console = env().console.lock(); console.instant = false; if console.draw && console.redraw
} unsafe { context_switch(false) }; } } static BSS_TEST_ZERO: usize = 0; static BSS_TEST_NONZERO: usize = usize::MAX; /// Initialize kernel unsafe fn init(font_data: usize, tss_data: usize) { // Zero BSS, this initializes statics that are set to 0 { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let start_ptr = &mut __bss_start; let end_ptr = &mut __bss_end; if start_ptr as *const _ as usize <= end_ptr as *const _ as usize { let size = end_ptr as *const _ as usize - start_ptr as *const _ as usize; memset(start_ptr, 0, size); } assert_eq!(BSS_TEST_ZERO, 0); assert_eq!(BSS_TEST_NONZERO, usize::MAX); } // Setup paging, this allows for memory allocation Page::init(); memory::cluster_init(); // Unmap first page to catch null pointer errors (after reading memory map) Page::new(0).unmap(); display::fonts = font_data; TSS_PTR = Some(&mut *(tss_data as *mut TSS)); ENV_PTR = Some(&mut *Box::into_raw(Environment::new())); match ENV_PTR { Some(ref mut env) => { env.contexts.lock().push(Context::root()); env.console.lock().draw = true; debug!("Redox {} bits\n", mem::size_of::<usize>() * 8); if let Some(acpi) = Acpi::new() { env.schemes.push(UnsafeCell::new(acpi)); } *(env.clock_realtime.lock()) = Rtc::new().time(); env.schemes.push(UnsafeCell::new(Ps2::new())); env.schemes.push(UnsafeCell::new(Serial::new(0x3F8, 0x4))); pci::pci_init(env); env.schemes.push(UnsafeCell::new(DebugScheme::new())); env.schemes.push(UnsafeCell::new(box ContextScheme)); env.schemes.push(UnsafeCell::new(box InterruptScheme)); env.schemes.push(UnsafeCell::new(box MemoryScheme)); // session.items.push(box RandomScheme); // session.items.push(box TimeScheme); env.schemes.push(UnsafeCell::new(box EthernetScheme)); env.schemes.push(UnsafeCell::new(box ArpScheme)); env.schemes.push(UnsafeCell::new(box IcmpScheme)); env.schemes.push(UnsafeCell::new(box IpScheme { arp: Vec::new() })); // session.items.push(box DisplayScheme); Context::spawn("kpoll".to_string(), box move || { poll_loop(); }); Context::spawn("kevent".to_string(), box move || { event_loop(); }); Context::spawn("karp".to_string(), box move || { ArpScheme::reply_loop(); }); Context::spawn("kicmp".to_string(), box move || { IcmpScheme::reply_loop(); }); env.contexts.lock().enabled = true; if let Ok(mut resource) = Url::from_str("file:/schemes/").open() { let mut vec: Vec<u8> = Vec::new(); let _ = resource.read_to_end(&mut vec); for folder in String::from_utf8_unchecked(vec).lines() { if folder.ends_with('/') { let scheme_item = SchemeItem::from_url(&Url::from_string("file:/schemes/" .to_string() + &folder)); env.schemes.push(UnsafeCell::new(scheme_item)); } } } Context::spawn("kinit".to_string(), box move || { { let wd_c = "file:/\0"; do_sys_chdir(wd_c.as_ptr()); let stdio_c = "debug:\0"; do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); do_sys_open(stdio_c.as_ptr(), 0); } execute(Url::from_str("file:/apps/login/main.bin"), Vec::new()); debug!("INIT: Failed to execute\n"); loop { context_switch(false); } }); }, None => unreachable!(), } } #[cold] #[inline(never)] #[no_mangle] /// Take regs for kernel calls and exceptions pub extern "cdecl" fn kernel(interrupt: usize, mut regs: &mut Regs) { macro_rules! exception_inner { ($name:expr) => ({ { let contexts = ::env().contexts.lock(); if let Some(context) = contexts.current() { debugln!("PID {}: {}", context.pid, context.name); } } debugln!(" INT {:X}: {}", interrupt, $name); debugln!(" CS: {:08X} IP: {:08X} FLG: {:08X}", regs.cs, regs.ip, regs.flags); debugln!(" SS: {:08X} SP: {:08X} BP: {:08X}", regs.ss, regs.sp, regs.bp); debugln!(" AX: {:08X} BX: {:08X} CX: {:08X} DX: {:08X}", regs.ax, regs.bx, regs.cx, regs.dx); debugln!(" DI: {:08X} SI: {:08X}", regs.di, regs.di); let cr0: usize; let cr2: usize; let cr3: usize; let cr4: usize; unsafe { asm!("mov $0, cr0" : "=r"(cr0) : : : "intel", "volatile"); asm!("mov $0, cr2" : "=r"(cr2) : : : "intel", "volatile"); asm!("mov $0, cr3" : "=r"(cr3) : : : "intel", "volatile"); asm!("mov $0, cr4" : "=r"(cr4) : : : "intel", "volatile"); } debugln!(" CR0: {:08X} CR2: {:08X} CR3: {:08X} CR4: {:08X}", cr0, cr2, cr3, cr4); let sp = regs.sp as *const u32; for y in -15..16 { debug!(" {:>3}:", y * 8 * 4); for x in 0..8 { debug!(" {:08X}", unsafe { ptr::read(sp.offset(-(x + y * 8))) }); } debug!("\n"); } }) }; macro_rules! exception { ($name:expr) => ({ exception_inner!($name); loop { do_sys_exit(usize::MAX); } }) }; macro_rules! exception_error { ($name:expr) => ({ let error = regs.ip; regs.ip = regs.cs; regs.cs = regs.flags; regs.flags = regs.sp; regs.sp = regs.ss; regs.ss = 0; //regs.ss = regs.error; exception_inner!($name); debugln!(" ERR: {:08X}", error); loop { do_sys_exit(usize::MAX); } }) }; if interrupt >= 0x20 && interrupt < 0x30 { if interrupt >= 0x28 { unsafe { Pio8::new(0xA0).write(0x20) }; } unsafe { Pio8::new(0x20).write(0x20) }; } //Do not catch init interrupt if interrupt < 0xFF { env().interrupts.lock()[interrupt as usize] += 1; } match interrupt { 0x20 => { { let mut clock_monotonic = env().clock_monotonic.lock(); *clock_monotonic = *clock_monotonic + PIT_DURATION; } { let mut clock_realtime = env().clock_realtime.lock(); *clock_realtime = *clock_realtime + PIT_DURATION; } let switch = { let mut contexts = ::env().contexts.lock(); if let Some(mut context) = contexts.current_mut() { context.slices -= 1; context.slice_total += 1; context.slices == 0 } else { false } }; if switch { unsafe { context_switch(true) }; } } i @ 0x21... 0x2F => env().on_irq(i as u8 - 0x20), 0x80 => if!syscall_handle(regs) { exception!("Unknown Syscall"); }, 0xFF => { unsafe { init(regs.ax, regs.bx); idle_loop(); } }, 0x0 => exception!("Divide by zero exception"), 0x1 => exception!("Debug exception"), 0x2 => exception!("Non-maskable interrupt"), 0x3 => exception!("Breakpoint exception"), 0x4 => exception!("Overflow exception"), 0x5 => exception!("Bound range exceeded exception"), 0x6 => exception!("Invalid opcode exception"), 0x7 => exception!("Device not available exception"), 0x8 => exception_error!("Double fault"), 0x9 => exception!("Coprocessor Segment Overrun"), // legacy 0xA => exception_error!("Invalid TSS exception"), 0xB => exception_error!("Segment not present exception"), 0xC => exception_error!("Stack-segment fault"), 0xD => exception_error!("General protection fault"), 0xE => exception_error!("Page fault"), 0x10 => exception!("x87 floating-point exception"), 0x11 => exception_error!("Alignment check exception"), 0x12 => exception!("Machine check exception"), 0x13 =>
{ console.redraw = false; console.display.flip(); }
conditional_block
cleanup-rvalue-scopes.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.
#![feature(macro_rules)] use std::ops::Drop; static mut FLAGS: u64 = 0; struct Box<T> { f: T } struct AddFlags { bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg(exp: u64, _x: &AddFlags) { check_flags(exp); } fn pass<T>(v: T) -> T { v } fn check_flags(exp: u64) { unsafe { let x = FLAGS; FLAGS = 0; println!("flags {}, expected {}", x, exp); assert_eq!(x, exp); } } impl AddFlags { fn check_flags<'a>(&'a self, exp: u64) -> &'a AddFlags { check_flags(exp); self } fn bits(&self) -> u64 { self.bits } } impl Drop for AddFlags { fn drop(&mut self) { unsafe { FLAGS = FLAGS + self.bits; } } } macro_rules! end_of_block( ($pat:pat, $expr:expr) => ( { println!("end_of_block({})", stringify!({let $pat = $expr;})); { // Destructor here does not run until exit from the block. let $pat = $expr; check_flags(0); } check_flags(1); } ) ) macro_rules! end_of_stmt( ($pat:pat, $expr:expr) => ( { println!("end_of_stmt({})", stringify!($expr)); { // Destructor here run after `let` statement // terminates. let $pat = $expr; check_flags(1); } check_flags(0); } ) ) pub fn main() { // In all these cases, we trip over the rules designed to cover // the case where we are taking addr of rvalue and storing that // addr into a stack slot, either via `let ref` or via a `&` in // the initializer. end_of_block!(_x, AddFlags(1)); end_of_block!(_x, &AddFlags(1)); end_of_block!(_x, & &AddFlags(1)); end_of_block!(_x, Box { f: AddFlags(1) }); end_of_block!(_x, Box { f: &AddFlags(1) }); end_of_block!(_x, Box { f: &AddFlags(1) }); end_of_block!(_x, pass(AddFlags(1))); end_of_block!(ref _x, AddFlags(1)); end_of_block!(AddFlags { bits: ref _x }, AddFlags(1)); end_of_block!(&AddFlags { bits }, &AddFlags(1)); end_of_block!((_, ref _y), (AddFlags(1), 22)); end_of_block!(~ref _x, ~AddFlags(1)); end_of_block!(~_x, ~AddFlags(1)); end_of_block!(_, { { check_flags(0); &AddFlags(1) } }); end_of_block!(_, &((Box { f: AddFlags(1) }).f)); end_of_block!(_, &(([AddFlags(1)])[0])); // LHS does not create a ref binding, so temporary lives as long // as statement, and we do not move the AddFlags out: end_of_stmt!(_, AddFlags(1)); end_of_stmt!((_, _), (AddFlags(1), 22)); // `&` operator appears inside an arg to a function, // so it is not prolonged: end_of_stmt!(ref _x, arg(0, &AddFlags(1))); // autoref occurs inside receiver, so temp lifetime is not // prolonged: end_of_stmt!(ref _x, AddFlags(1).check_flags(0).bits()); // No reference is created on LHS, thus RHS is moved into // a temporary that lives just as long as the statement. end_of_stmt!(AddFlags { bits }, AddFlags(1)); }
// Test that destructors for rvalue temporaries run either at end of // statement or end of block, as appropriate given the temporary // lifetime rules.
random_line_split
cleanup-rvalue-scopes.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 that destructors for rvalue temporaries run either at end of // statement or end of block, as appropriate given the temporary // lifetime rules. #![feature(macro_rules)] use std::ops::Drop; static mut FLAGS: u64 = 0; struct Box<T> { f: T } struct AddFlags { bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg(exp: u64, _x: &AddFlags) { check_flags(exp); } fn pass<T>(v: T) -> T { v } fn check_flags(exp: u64) { unsafe { let x = FLAGS; FLAGS = 0; println!("flags {}, expected {}", x, exp); assert_eq!(x, exp); } } impl AddFlags { fn check_flags<'a>(&'a self, exp: u64) -> &'a AddFlags
fn bits(&self) -> u64 { self.bits } } impl Drop for AddFlags { fn drop(&mut self) { unsafe { FLAGS = FLAGS + self.bits; } } } macro_rules! end_of_block( ($pat:pat, $expr:expr) => ( { println!("end_of_block({})", stringify!({let $pat = $expr;})); { // Destructor here does not run until exit from the block. let $pat = $expr; check_flags(0); } check_flags(1); } ) ) macro_rules! end_of_stmt( ($pat:pat, $expr:expr) => ( { println!("end_of_stmt({})", stringify!($expr)); { // Destructor here run after `let` statement // terminates. let $pat = $expr; check_flags(1); } check_flags(0); } ) ) pub fn main() { // In all these cases, we trip over the rules designed to cover // the case where we are taking addr of rvalue and storing that // addr into a stack slot, either via `let ref` or via a `&` in // the initializer. end_of_block!(_x, AddFlags(1)); end_of_block!(_x, &AddFlags(1)); end_of_block!(_x, & &AddFlags(1)); end_of_block!(_x, Box { f: AddFlags(1) }); end_of_block!(_x, Box { f: &AddFlags(1) }); end_of_block!(_x, Box { f: &AddFlags(1) }); end_of_block!(_x, pass(AddFlags(1))); end_of_block!(ref _x, AddFlags(1)); end_of_block!(AddFlags { bits: ref _x }, AddFlags(1)); end_of_block!(&AddFlags { bits }, &AddFlags(1)); end_of_block!((_, ref _y), (AddFlags(1), 22)); end_of_block!(~ref _x, ~AddFlags(1)); end_of_block!(~_x, ~AddFlags(1)); end_of_block!(_, { { check_flags(0); &AddFlags(1) } }); end_of_block!(_, &((Box { f: AddFlags(1) }).f)); end_of_block!(_, &(([AddFlags(1)])[0])); // LHS does not create a ref binding, so temporary lives as long // as statement, and we do not move the AddFlags out: end_of_stmt!(_, AddFlags(1)); end_of_stmt!((_, _), (AddFlags(1), 22)); // `&` operator appears inside an arg to a function, // so it is not prolonged: end_of_stmt!(ref _x, arg(0, &AddFlags(1))); // autoref occurs inside receiver, so temp lifetime is not // prolonged: end_of_stmt!(ref _x, AddFlags(1).check_flags(0).bits()); // No reference is created on LHS, thus RHS is moved into // a temporary that lives just as long as the statement. end_of_stmt!(AddFlags { bits }, AddFlags(1)); }
{ check_flags(exp); self }
identifier_body
cleanup-rvalue-scopes.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 that destructors for rvalue temporaries run either at end of // statement or end of block, as appropriate given the temporary // lifetime rules. #![feature(macro_rules)] use std::ops::Drop; static mut FLAGS: u64 = 0; struct Box<T> { f: T } struct AddFlags { bits: u64 } fn AddFlags(bits: u64) -> AddFlags { AddFlags { bits: bits } } fn arg(exp: u64, _x: &AddFlags) { check_flags(exp); } fn pass<T>(v: T) -> T { v } fn check_flags(exp: u64) { unsafe { let x = FLAGS; FLAGS = 0; println!("flags {}, expected {}", x, exp); assert_eq!(x, exp); } } impl AddFlags { fn check_flags<'a>(&'a self, exp: u64) -> &'a AddFlags { check_flags(exp); self } fn bits(&self) -> u64 { self.bits } } impl Drop for AddFlags { fn
(&mut self) { unsafe { FLAGS = FLAGS + self.bits; } } } macro_rules! end_of_block( ($pat:pat, $expr:expr) => ( { println!("end_of_block({})", stringify!({let $pat = $expr;})); { // Destructor here does not run until exit from the block. let $pat = $expr; check_flags(0); } check_flags(1); } ) ) macro_rules! end_of_stmt( ($pat:pat, $expr:expr) => ( { println!("end_of_stmt({})", stringify!($expr)); { // Destructor here run after `let` statement // terminates. let $pat = $expr; check_flags(1); } check_flags(0); } ) ) pub fn main() { // In all these cases, we trip over the rules designed to cover // the case where we are taking addr of rvalue and storing that // addr into a stack slot, either via `let ref` or via a `&` in // the initializer. end_of_block!(_x, AddFlags(1)); end_of_block!(_x, &AddFlags(1)); end_of_block!(_x, & &AddFlags(1)); end_of_block!(_x, Box { f: AddFlags(1) }); end_of_block!(_x, Box { f: &AddFlags(1) }); end_of_block!(_x, Box { f: &AddFlags(1) }); end_of_block!(_x, pass(AddFlags(1))); end_of_block!(ref _x, AddFlags(1)); end_of_block!(AddFlags { bits: ref _x }, AddFlags(1)); end_of_block!(&AddFlags { bits }, &AddFlags(1)); end_of_block!((_, ref _y), (AddFlags(1), 22)); end_of_block!(~ref _x, ~AddFlags(1)); end_of_block!(~_x, ~AddFlags(1)); end_of_block!(_, { { check_flags(0); &AddFlags(1) } }); end_of_block!(_, &((Box { f: AddFlags(1) }).f)); end_of_block!(_, &(([AddFlags(1)])[0])); // LHS does not create a ref binding, so temporary lives as long // as statement, and we do not move the AddFlags out: end_of_stmt!(_, AddFlags(1)); end_of_stmt!((_, _), (AddFlags(1), 22)); // `&` operator appears inside an arg to a function, // so it is not prolonged: end_of_stmt!(ref _x, arg(0, &AddFlags(1))); // autoref occurs inside receiver, so temp lifetime is not // prolonged: end_of_stmt!(ref _x, AddFlags(1).check_flags(0).bits()); // No reference is created on LHS, thus RHS is moved into // a temporary that lives just as long as the statement. end_of_stmt!(AddFlags { bits }, AddFlags(1)); }
drop
identifier_name
htmloptionelement.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::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOptionElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLOptionElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOptionElement { pub htmlelement: HTMLElement } impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } } pub trait HTMLOptionElementMethods { } impl Reflectable for HTMLOptionElement { fn reflector<'a>(&'a self) -> &'a Reflector
}
{ self.htmlelement.reflector() }
identifier_body
htmloptionelement.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::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOptionElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLOptionElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOptionElement { pub htmlelement: HTMLElement } impl HTMLOptionElementDerived for EventTarget { fn
(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } } pub trait HTMLOptionElementMethods { } impl Reflectable for HTMLOptionElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
is_htmloptionelement
identifier_name
htmloptionelement.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::Bindings::HTMLOptionElementBinding; use dom::bindings::codegen::InheritTypes::HTMLOptionElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document; use dom::element::HTMLOptionElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLOptionElement { pub htmlelement: HTMLElement } impl HTMLOptionElementDerived for EventTarget { fn is_htmloptionelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLOptionElementTypeId)) } } impl HTMLOptionElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLOptionElement { HTMLOptionElement { htmlelement: HTMLElement::new_inherited(HTMLOptionElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLOptionElement> { let element = HTMLOptionElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLOptionElementBinding::Wrap) } } pub trait HTMLOptionElementMethods { } impl Reflectable for HTMLOptionElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
random_line_split
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Parse and re-serialize a HTML5 document. /// /// This is meant to produce the exact same output (ignoring stderr) as /// /// java -classpath htmlparser-1.4.jar nu.validator.htmlparser.tools.HTML2HTML /// /// where htmlparser-1.4.jar comes from http://about.validator.nu/htmlparser/ extern crate html5ever; use std::io; use std::default::Default; use html5ever::sink::rcdom::RcDom; use html5ever::driver::ParseOpts; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse, one_input, serialize}; #[allow(unstable)] fn main()
{ let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a doctype at the very beginning. io::stdout().write_str("<!DOCTYPE html>\n") .ok().expect("writing DOCTYPE failed"); serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
identifier_body
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Parse and re-serialize a HTML5 document. /// /// This is meant to produce the exact same output (ignoring stderr) as /// /// java -classpath htmlparser-1.4.jar nu.validator.htmlparser.tools.HTML2HTML /// /// where htmlparser-1.4.jar comes from http://about.validator.nu/htmlparser/ extern crate html5ever; use std::io; use std::default::Default; use html5ever::sink::rcdom::RcDom; use html5ever::driver::ParseOpts; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse, one_input, serialize}; #[allow(unstable)] fn
() { let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a doctype at the very beginning. io::stdout().write_str("<!DOCTYPE html>\n") .ok().expect("writing DOCTYPE failed"); serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
main
identifier_name
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// Parse and re-serialize a HTML5 document. /// /// This is meant to produce the exact same output (ignoring stderr) as /// /// java -classpath htmlparser-1.4.jar nu.validator.htmlparser.tools.HTML2HTML /// /// where htmlparser-1.4.jar comes from http://about.validator.nu/htmlparser/ extern crate html5ever; use std::io; use std::default::Default; use html5ever::sink::rcdom::RcDom; use html5ever::driver::ParseOpts; use html5ever::tree_builder::TreeBuilderOpts; use html5ever::{parse, one_input, serialize}; #[allow(unstable)] fn main() { let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a doctype at the very beginning. io::stdout().write_str("<!DOCTYPE html>\n")
serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
.ok().expect("writing DOCTYPE failed");
random_line_split
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. Only one constant can be defined for a single name at any given moment. #[derive(Clone)] pub struct ScopeStack<K, V>(Vec<BTreeMap<K, V>>); impl<K: Ord + Eq, V> ScopeStack<K, V> { pub fn new() -> ScopeStack<K, V> { ScopeStack(Vec::new()) } pub fn push(&mut self, scope: BTreeMap<K, V>) where K: Debug, V: Debug, { for key in scope.keys() { assert!( !self.contains_key(key), "ICE: ScopeStack::push: Key `{:?}` already exists\n : {:?}", key, self ); } self.0.push(scope); }
pub fn split_off(&mut self, at: usize) -> Vec<BTreeMap<K, V>> { self.0.split_off(at) } pub fn extend(&mut self, xs: Vec<BTreeMap<K, V>>) { self.0.extend(xs) } pub fn contains_key<Q:?Sized>(&self, key: &Q) -> bool where Q: Ord + Eq, K: Borrow<Q>, { self.0.iter().any(|scope| scope.contains_key(key)) } pub fn get_height<Q:?Sized>(&self, key: &Q) -> Option<usize> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate() { if scope.contains_key(key) { return Some(height); } } None } pub fn get<Q:?Sized>(&self, key: &Q) -> Option<&V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_with_height(key).map(|(v, _)| v) } pub fn get_mut<Q:?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_mut_with_height(key).map(|(v, _)| v) } pub fn remove<Q:?Sized>(&mut self, key: &Q) -> Option<V> where Q: Ord + Eq, K: Borrow<Q>, { for scope in self.0.iter_mut().rev() { if let Some(def) = scope.remove(key) { return Some(def); } } None } pub fn get_with_height<Q:?Sized>(&self, key: &Q) -> Option<(&V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate().rev() { if let Some(def) = scope.get(key) { return Some((def, height)); } } None } pub fn get_mut_with_height<Q:?Sized>(&mut self, key: &Q) -> Option<(&mut V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter_mut().enumerate().rev() { if let Some(def) = scope.get_mut(key) { return Some((def, height)); } } None } } impl<K: Debug + Ord + Eq, V: Debug> Debug for ScopeStack<K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.0, f) } } struct AddMapNode<K, V> { key: K, val: V, /// null indicates no next node next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMapNode<K, V> { fn entry<'a, Q>(&'a self, key: &Q) -> Option<(&'a K, &'a V)> where K: Borrow<Q> + PartialEq<Q>, { if &self.key == key { Some((&self.key, &self.val)) } else { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } } fn add(&self, key: K, val: V) -> (&K, &V) where K: PartialEq<K>, { if self.key == key { panic!("Key already exists in map") } else { unsafe { match *self.next { None => { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } Some(ref next_node) => next_node.add(key, val), } } } } } /// A map which can only grow. /// /// Implemented with a linked list pub struct AddMap<K, V> { next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMap<K, V> where K: PartialEq<K>, { pub fn new() -> Self { AddMap { next: Box::into_raw(Box::new(None)), } } /// Get reference to key and value in map associated with `key` /// /// Executes in `O(n)` time pub fn entry<Q>(&self, key: &Q) -> Option<(&K, &V)> where K: Borrow<Q> + PartialEq<Q>, { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } /// Returns whether the map contains `key` pub fn contains_key<Q>(&self, key: &Q) -> bool where K: Borrow<Q> + PartialEq<Q>, { self.entry(key).is_some() } /// Insert the value `val` with key `key` in map /// /// Returns reference to entry in map. /// Executes in `O(n)` time /// /// # Panics /// /// Panics if `key` already exists in list pub fn add(&self, key: K, val: V) -> (&K, &V) { unsafe { if (*self.next).is_none() { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } else { (*self.next).as_ref().unwrap().add(key, val) } } } }
pub fn pop(&mut self) -> Option<BTreeMap<K, V>> { self.0.pop() }
random_line_split
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. Only one constant can be defined for a single name at any given moment. #[derive(Clone)] pub struct ScopeStack<K, V>(Vec<BTreeMap<K, V>>); impl<K: Ord + Eq, V> ScopeStack<K, V> { pub fn new() -> ScopeStack<K, V> { ScopeStack(Vec::new()) } pub fn push(&mut self, scope: BTreeMap<K, V>) where K: Debug, V: Debug, { for key in scope.keys() { assert!( !self.contains_key(key), "ICE: ScopeStack::push: Key `{:?}` already exists\n : {:?}", key, self ); } self.0.push(scope); } pub fn pop(&mut self) -> Option<BTreeMap<K, V>> { self.0.pop() } pub fn split_off(&mut self, at: usize) -> Vec<BTreeMap<K, V>> { self.0.split_off(at) } pub fn extend(&mut self, xs: Vec<BTreeMap<K, V>>) { self.0.extend(xs) } pub fn contains_key<Q:?Sized>(&self, key: &Q) -> bool where Q: Ord + Eq, K: Borrow<Q>, { self.0.iter().any(|scope| scope.contains_key(key)) } pub fn get_height<Q:?Sized>(&self, key: &Q) -> Option<usize> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate() { if scope.contains_key(key) { return Some(height); } } None } pub fn get<Q:?Sized>(&self, key: &Q) -> Option<&V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_with_height(key).map(|(v, _)| v) } pub fn get_mut<Q:?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_mut_with_height(key).map(|(v, _)| v) } pub fn remove<Q:?Sized>(&mut self, key: &Q) -> Option<V> where Q: Ord + Eq, K: Borrow<Q>,
pub fn get_with_height<Q:?Sized>(&self, key: &Q) -> Option<(&V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate().rev() { if let Some(def) = scope.get(key) { return Some((def, height)); } } None } pub fn get_mut_with_height<Q:?Sized>(&mut self, key: &Q) -> Option<(&mut V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter_mut().enumerate().rev() { if let Some(def) = scope.get_mut(key) { return Some((def, height)); } } None } } impl<K: Debug + Ord + Eq, V: Debug> Debug for ScopeStack<K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.0, f) } } struct AddMapNode<K, V> { key: K, val: V, /// null indicates no next node next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMapNode<K, V> { fn entry<'a, Q>(&'a self, key: &Q) -> Option<(&'a K, &'a V)> where K: Borrow<Q> + PartialEq<Q>, { if &self.key == key { Some((&self.key, &self.val)) } else { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } } fn add(&self, key: K, val: V) -> (&K, &V) where K: PartialEq<K>, { if self.key == key { panic!("Key already exists in map") } else { unsafe { match *self.next { None => { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } Some(ref next_node) => next_node.add(key, val), } } } } } /// A map which can only grow. /// /// Implemented with a linked list pub struct AddMap<K, V> { next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMap<K, V> where K: PartialEq<K>, { pub fn new() -> Self { AddMap { next: Box::into_raw(Box::new(None)), } } /// Get reference to key and value in map associated with `key` /// /// Executes in `O(n)` time pub fn entry<Q>(&self, key: &Q) -> Option<(&K, &V)> where K: Borrow<Q> + PartialEq<Q>, { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } /// Returns whether the map contains `key` pub fn contains_key<Q>(&self, key: &Q) -> bool where K: Borrow<Q> + PartialEq<Q>, { self.entry(key).is_some() } /// Insert the value `val` with key `key` in map /// /// Returns reference to entry in map. /// Executes in `O(n)` time /// /// # Panics /// /// Panics if `key` already exists in list pub fn add(&self, key: K, val: V) -> (&K, &V) { unsafe { if (*self.next).is_none() { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } else { (*self.next).as_ref().unwrap().add(key, val) } } } }
{ for scope in self.0.iter_mut().rev() { if let Some(def) = scope.remove(key) { return Some(def); } } None }
identifier_body
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. Only one constant can be defined for a single name at any given moment. #[derive(Clone)] pub struct ScopeStack<K, V>(Vec<BTreeMap<K, V>>); impl<K: Ord + Eq, V> ScopeStack<K, V> { pub fn new() -> ScopeStack<K, V> { ScopeStack(Vec::new()) } pub fn push(&mut self, scope: BTreeMap<K, V>) where K: Debug, V: Debug, { for key in scope.keys() { assert!( !self.contains_key(key), "ICE: ScopeStack::push: Key `{:?}` already exists\n : {:?}", key, self ); } self.0.push(scope); } pub fn pop(&mut self) -> Option<BTreeMap<K, V>> { self.0.pop() } pub fn split_off(&mut self, at: usize) -> Vec<BTreeMap<K, V>> { self.0.split_off(at) } pub fn extend(&mut self, xs: Vec<BTreeMap<K, V>>) { self.0.extend(xs) } pub fn contains_key<Q:?Sized>(&self, key: &Q) -> bool where Q: Ord + Eq, K: Borrow<Q>, { self.0.iter().any(|scope| scope.contains_key(key)) } pub fn
<Q:?Sized>(&self, key: &Q) -> Option<usize> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate() { if scope.contains_key(key) { return Some(height); } } None } pub fn get<Q:?Sized>(&self, key: &Q) -> Option<&V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_with_height(key).map(|(v, _)| v) } pub fn get_mut<Q:?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_mut_with_height(key).map(|(v, _)| v) } pub fn remove<Q:?Sized>(&mut self, key: &Q) -> Option<V> where Q: Ord + Eq, K: Borrow<Q>, { for scope in self.0.iter_mut().rev() { if let Some(def) = scope.remove(key) { return Some(def); } } None } pub fn get_with_height<Q:?Sized>(&self, key: &Q) -> Option<(&V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate().rev() { if let Some(def) = scope.get(key) { return Some((def, height)); } } None } pub fn get_mut_with_height<Q:?Sized>(&mut self, key: &Q) -> Option<(&mut V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter_mut().enumerate().rev() { if let Some(def) = scope.get_mut(key) { return Some((def, height)); } } None } } impl<K: Debug + Ord + Eq, V: Debug> Debug for ScopeStack<K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.0, f) } } struct AddMapNode<K, V> { key: K, val: V, /// null indicates no next node next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMapNode<K, V> { fn entry<'a, Q>(&'a self, key: &Q) -> Option<(&'a K, &'a V)> where K: Borrow<Q> + PartialEq<Q>, { if &self.key == key { Some((&self.key, &self.val)) } else { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } } fn add(&self, key: K, val: V) -> (&K, &V) where K: PartialEq<K>, { if self.key == key { panic!("Key already exists in map") } else { unsafe { match *self.next { None => { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } Some(ref next_node) => next_node.add(key, val), } } } } } /// A map which can only grow. /// /// Implemented with a linked list pub struct AddMap<K, V> { next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMap<K, V> where K: PartialEq<K>, { pub fn new() -> Self { AddMap { next: Box::into_raw(Box::new(None)), } } /// Get reference to key and value in map associated with `key` /// /// Executes in `O(n)` time pub fn entry<Q>(&self, key: &Q) -> Option<(&K, &V)> where K: Borrow<Q> + PartialEq<Q>, { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } /// Returns whether the map contains `key` pub fn contains_key<Q>(&self, key: &Q) -> bool where K: Borrow<Q> + PartialEq<Q>, { self.entry(key).is_some() } /// Insert the value `val` with key `key` in map /// /// Returns reference to entry in map. /// Executes in `O(n)` time /// /// # Panics /// /// Panics if `key` already exists in list pub fn add(&self, key: K, val: V) -> (&K, &V) { unsafe { if (*self.next).is_none() { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } else { (*self.next).as_ref().unwrap().add(key, val) } } } }
get_height
identifier_name
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. Only one constant can be defined for a single name at any given moment. #[derive(Clone)] pub struct ScopeStack<K, V>(Vec<BTreeMap<K, V>>); impl<K: Ord + Eq, V> ScopeStack<K, V> { pub fn new() -> ScopeStack<K, V> { ScopeStack(Vec::new()) } pub fn push(&mut self, scope: BTreeMap<K, V>) where K: Debug, V: Debug, { for key in scope.keys() { assert!( !self.contains_key(key), "ICE: ScopeStack::push: Key `{:?}` already exists\n : {:?}", key, self ); } self.0.push(scope); } pub fn pop(&mut self) -> Option<BTreeMap<K, V>> { self.0.pop() } pub fn split_off(&mut self, at: usize) -> Vec<BTreeMap<K, V>> { self.0.split_off(at) } pub fn extend(&mut self, xs: Vec<BTreeMap<K, V>>) { self.0.extend(xs) } pub fn contains_key<Q:?Sized>(&self, key: &Q) -> bool where Q: Ord + Eq, K: Borrow<Q>, { self.0.iter().any(|scope| scope.contains_key(key)) } pub fn get_height<Q:?Sized>(&self, key: &Q) -> Option<usize> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate() { if scope.contains_key(key) { return Some(height); } } None } pub fn get<Q:?Sized>(&self, key: &Q) -> Option<&V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_with_height(key).map(|(v, _)| v) } pub fn get_mut<Q:?Sized>(&mut self, key: &Q) -> Option<&mut V> where Q: Ord + Eq, K: Borrow<Q>, { self.get_mut_with_height(key).map(|(v, _)| v) } pub fn remove<Q:?Sized>(&mut self, key: &Q) -> Option<V> where Q: Ord + Eq, K: Borrow<Q>, { for scope in self.0.iter_mut().rev() { if let Some(def) = scope.remove(key) { return Some(def); } } None } pub fn get_with_height<Q:?Sized>(&self, key: &Q) -> Option<(&V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate().rev() { if let Some(def) = scope.get(key) { return Some((def, height)); } } None } pub fn get_mut_with_height<Q:?Sized>(&mut self, key: &Q) -> Option<(&mut V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter_mut().enumerate().rev() { if let Some(def) = scope.get_mut(key) { return Some((def, height)); } } None } } impl<K: Debug + Ord + Eq, V: Debug> Debug for ScopeStack<K, V> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.0, f) } } struct AddMapNode<K, V> { key: K, val: V, /// null indicates no next node next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMapNode<K, V> { fn entry<'a, Q>(&'a self, key: &Q) -> Option<(&'a K, &'a V)> where K: Borrow<Q> + PartialEq<Q>, { if &self.key == key
else { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } } fn add(&self, key: K, val: V) -> (&K, &V) where K: PartialEq<K>, { if self.key == key { panic!("Key already exists in map") } else { unsafe { match *self.next { None => { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } Some(ref next_node) => next_node.add(key, val), } } } } } /// A map which can only grow. /// /// Implemented with a linked list pub struct AddMap<K, V> { next: *mut Option<AddMapNode<K, V>>, } impl<K, V> AddMap<K, V> where K: PartialEq<K>, { pub fn new() -> Self { AddMap { next: Box::into_raw(Box::new(None)), } } /// Get reference to key and value in map associated with `key` /// /// Executes in `O(n)` time pub fn entry<Q>(&self, key: &Q) -> Option<(&K, &V)> where K: Borrow<Q> + PartialEq<Q>, { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } /// Returns whether the map contains `key` pub fn contains_key<Q>(&self, key: &Q) -> bool where K: Borrow<Q> + PartialEq<Q>, { self.entry(key).is_some() } /// Insert the value `val` with key `key` in map /// /// Returns reference to entry in map. /// Executes in `O(n)` time /// /// # Panics /// /// Panics if `key` already exists in list pub fn add(&self, key: K, val: V) -> (&K, &V) { unsafe { if (*self.next).is_none() { *self.next = Some(AddMapNode { key: key, val: val, next: Box::into_raw(Box::new(None)), }); let next = (*self.next).as_ref().unwrap(); (&next.key, &next.val) } else { (*self.next).as_ref().unwrap().add(key, val) } } } }
{ Some((&self.key, &self.val)) }
conditional_block
cssstylerule.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 cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods}; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use selectors::parser::SelectorList; use servo_arc::Arc; use std::mem; use style::selector_parser::SelectorParser; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::{StyleRule, Origin}; #[dom_struct] pub struct CSSStyleRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] stylerule: Arc<Locked<StyleRule>>, style_decl: MutNullableJS<CSSStyleDeclaration>, } impl CSSStyleRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>) -> CSSStyleRule { CSSStyleRule { cssrule: CSSRule::new_inherited(parent_stylesheet), stylerule: stylerule, style_decl: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>) -> Root<CSSStyleRule> { reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule), window, CSSStyleRuleBinding::Wrap) } } impl SpecificCSSRule for CSSStyleRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::STYLE_RULE } fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.stylerule.read_with(&guard).to_css_string(&guard).into() } } impl CSSStyleRuleMethods for CSSStyleRule { // https://drafts.csswg.org/cssom/#dom-cssstylerule-style fn Style(&self) -> Root<CSSStyleDeclaration> { self.style_decl.or_init(|| { let guard = self.cssrule.shared_lock().read(); CSSStyleDeclaration::new( self.global().as_window(), CSSStyleOwner::CSSRule( JS::from_ref(self.upcast()), self.stylerule.read_with(&guard).block.clone() ), None, CSSModificationAccess::ReadWrite ) }) } // https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext fn SelectorText(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); let stylerule = self.stylerule.read_with(&guard); return DOMString::from_string(stylerule.selectors.to_css_string()); } // https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext fn
(&self, value: DOMString) { // It's not clear from the spec if we should use the stylesheet's namespaces. // https://github.com/w3c/csswg-drafts/issues/1511 let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read(); let parser = SelectorParser { stylesheet_origin: Origin::Author, namespaces: &namespaces, url_data: None, }; let mut css_parser = CssParserInput::new(&*value); let mut css_parser = CssParser::new(&mut css_parser); if let Ok(mut s) = SelectorList::parse(&parser, &mut css_parser) { // This mirrors what we do in CSSStyleOwner::mutate_associated_block. let mut guard = self.cssrule.shared_lock().write(); let stylerule = self.stylerule.write_with(&mut guard); mem::swap(&mut stylerule.selectors, &mut s); // It seems like we will want to avoid having to invalidate all // stylesheets eventually! self.global().as_window().Document().invalidate_stylesheets(); } } }
SetSelectorText
identifier_name
cssstylerule.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 cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods}; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use selectors::parser::SelectorList; use servo_arc::Arc; use std::mem; use style::selector_parser::SelectorParser; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::{StyleRule, Origin}; #[dom_struct] pub struct CSSStyleRule { cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] stylerule: Arc<Locked<StyleRule>>, style_decl: MutNullableJS<CSSStyleDeclaration>, } impl CSSStyleRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>) -> CSSStyleRule { CSSStyleRule { cssrule: CSSRule::new_inherited(parent_stylesheet), stylerule: stylerule, style_decl: Default::default(), } } #[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>) -> Root<CSSStyleRule>
} impl SpecificCSSRule for CSSStyleRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::STYLE_RULE } fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.stylerule.read_with(&guard).to_css_string(&guard).into() } } impl CSSStyleRuleMethods for CSSStyleRule { // https://drafts.csswg.org/cssom/#dom-cssstylerule-style fn Style(&self) -> Root<CSSStyleDeclaration> { self.style_decl.or_init(|| { let guard = self.cssrule.shared_lock().read(); CSSStyleDeclaration::new( self.global().as_window(), CSSStyleOwner::CSSRule( JS::from_ref(self.upcast()), self.stylerule.read_with(&guard).block.clone() ), None, CSSModificationAccess::ReadWrite ) }) } // https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext fn SelectorText(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); let stylerule = self.stylerule.read_with(&guard); return DOMString::from_string(stylerule.selectors.to_css_string()); } // https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext fn SetSelectorText(&self, value: DOMString) { // It's not clear from the spec if we should use the stylesheet's namespaces. // https://github.com/w3c/csswg-drafts/issues/1511 let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read(); let parser = SelectorParser { stylesheet_origin: Origin::Author, namespaces: &namespaces, url_data: None, }; let mut css_parser = CssParserInput::new(&*value); let mut css_parser = CssParser::new(&mut css_parser); if let Ok(mut s) = SelectorList::parse(&parser, &mut css_parser) { // This mirrors what we do in CSSStyleOwner::mutate_associated_block. let mut guard = self.cssrule.shared_lock().write(); let stylerule = self.stylerule.write_with(&mut guard); mem::swap(&mut stylerule.selectors, &mut s); // It seems like we will want to avoid having to invalidate all // stylesheets eventually! self.global().as_window().Document().invalidate_stylesheets(); } } }
{ reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule), window, CSSStyleRuleBinding::Wrap) }
identifier_body